path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
models/final.ipynb
###Markdown Importing libraries ###Code import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model from keras.layers import Conv2D, MaxPooling2D, InputLayer from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization from keras import applications import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Initialization ###Code model_weights = 'bottleneck_fc_model.h5' ## image dimensions img_h, img_w = 150, 150 ## epochs epochs = 50 ## batch Size batch_size = 32 ## total no of train and validation samples nb_train_samples = 3000 nb_validation_samples = 800 ## data set directory train_data_dir = r'train' validation_data_dir = r'validation' ###Output _____no_output_____ ###Markdown Model ###Code ## vgg16 network model = applications.vgg16.VGG16(include_top = False, weights = 'imagenet', input_shape=(150,150,3)) print('Model loaded.') top_model = Sequential() # top_model.add(Dense(128)) top_model.add(Conv2D(128,(3,3),input_shape = model.output_shape[1:])) top_model.add(BatchNormalization(axis=3)) top_model.add(Activation('relu')) top_model.add(MaxPooling2D(pool_size = (2, 2))) top_model.add(Flatten()) top_model.add(Dense(256, activation = 'relu')) top_model.add(Dropout(0.6)) top_model.add(Dense(1, activation = 'sigmoid')) top_model.load_weights(model_weights, by_name = True, skip_mismatch = True) model = Model(inputs=model.input, outputs=top_model(model.output)) for layer in model.layers[:15]: layer.trainable = False model.compile(loss = 'binary_crossentropy', optimizer = tf.keras.optimizers.SGD(learning_rate = 1e-4, momentum = 0.9), metrics = ['accuracy']) ###Output Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5 58892288/58889256 [==============================] - 0s 0us/step 58900480/58889256 [==============================] - 0s 0us/step Model loaded. ###Markdown Data Preprocessing ###Code ## data augmentation train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.3, zoom_range = 0.2, horizontal_flip = True, rotation_range=20) test_datagen = ImageDataGenerator(rescale=1. / 255) ## train data train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(img_w, img_h), batch_size=batch_size, class_mode='binary') ## validation data validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size=(img_w, img_h), batch_size=batch_size, class_mode='binary') ###Output Found 3000 images belonging to 2 classes. Found 800 images belonging to 2 classes. ###Markdown Model Train ###Code ## training and testing model with the data set history = model.fit(train_generator, batch_size = batch_size, epochs = epochs, validation_data = validation_generator) ## plot accuracy graph plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Training and Validation accuracy') plt.legend(['accuracy','validation accuracy']) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.show() ## plot loss graph plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Training and Validation loss') plt.legend(['loss','validation loss']) plt.xlabel('Epochs') plt.ylabel('Loss') plt.show() ###Output Epoch 1/50 71/94 [=====================>........] - ETA: 1:52 - loss: 0.8299 - accuracy: 0.5428
month06/DATASCIENCE/DS_day07_student/code/Airline_customer_analysis_code/code/.ipynb_checkpoints/Untitled-checkpoint.ipynb
###Markdown 航空公司客户价值分析 读取数据 数据描述性分析 数据预处理 1. 去除票价为空的数据 2.只保留票价不为0,平均折扣率不为0,总飞行公里数大于0的记录。 构建特征 ###Code ## 选取需求特征 ## 构建L特征 ## 合并特征 ###Output _____no_output_____
gotdrawn.ipynb
###Markdown GotDrawnUpdating GetsDrawnDotCom with title feature.Taking getsdrawndotcom code and adding in features such as comments.Getting rid of folder structure. ###Code import os import requests import re import json import arrow import praw import dominate from dominate.tags import * import shutil from time import gmtime, strftime gotdrndir = ('/home/wcmckee/gotdrawn/imgs') r = praw.Reddit(user_agent='getsdrawndotcom') fulcom = [] fuldic = dict() getrn = r.get_subreddit('redditgetsdrawn') rnew = getrn.get_new() for rnc in rnew: fulcom.append(rnc) artes = arrow.utcnow() yrpath = artes.strftime('%Y') mntpath = artes.strftime('%m') dapth = artes.strftime('%d') if os.path.isdir(gotdrndir) == True: print 'its true' else: print 'its false' os.mkdir(gotdrndir) imgszpath = (gotdrndir) yrzpat = (imgszpath + '/' + yrpath) mntzpat = (yrzpat + '/' + mntpath) datzpat = (mntzpat + '/' + dapth) imgszpath dayform = ('/imgs/' + yrpath + '/' + mntpath + '/' + dapth) dayform if os.path.isdir(yrzpat) == True: print 'its true' else: print 'its false' os.mkdir(yrzpat) if os.path.isdir(mntzpat) == True: print 'its true' else: print 'its false' os.mkdir(mntzpat) if os.path.isdir(datzpat) == True: print 'its true' else: print 'its false' os.mkdir(datzpat) datzpat mntzpat datzpat if os.path.isdir(yrpath) == True: print 'its true' else: print 'its false' os.mkdir(yrpath) #mthzpath = (yrzpat + '/' + #if os.path( print artes.date() print artes.time() dati = artes.datetime #Random logo from logo folder. #5 to choose from. import random, random choice out of a list import random imglis = ['img1', 'img2', 'img3', 'img4', 'img0'] random.choice(imglis) os.listdir('/home/wcmckee/gotdrawn/logo') import PIL imed = PIL imed.PILLOW_VERSION #import pillow os.chdir('/home/wcmckee/gotdrawn/') imlocdir = (dayform + '/' + str(flc.author) + '-reference.png') imlocdir doc = dominate.document(title='GetsDrawn') with doc.head: link(rel='stylesheet', href='style.css') script(type ='text/javascript', src='script.js') #str(str2) with div(): attr(cls='header') h1('GetsDrawn') p(img('/imgs/getsdrawn-bw.png', src='/imgs/getsdrawn-bw.png')) #p(img('imgs/15/01/02/ReptileLover82-reference.png', src= 'imgs/15/01/02/ReptileLover82-reference.png')) h1('Updated ', str(artes.datetime)) #p(panz) #p(bodycom) with doc: with div(id='body').add(ol()): for flc in fulcom: if 'http://i.imgur.com' in flc.url: p(h1(flc.title)) p(img(imlocdir, src= imlocdir)) #p(img(flc.url, src = flc.url)) p(str(flc.author)) #res = requests.get(flc.url, stream=True) #with open(str(flc.author) + '-' + str(artes.date()) + '-reference.png', 'wb') as outfil: # shutil.copyfileobj(res.raw, outfil) # del res for flcz in flc.comments: p(flcz.body) #for rdz in reliz: #h1(rdz.title) #a(rdz.url) #p(img(rdz, src='%s' % rdz)) #print rdz #p(img(rdz, src = rdz)) #p(rdz) #print rdz.url #if '.jpg' in rdz.url: # img(rdz.urlz) #else: # a(rdz.urlz) #h1(str(rdz.author)) #li(img(i.lower(), src='%s' % i)) with div(): attr(cls='body') p('GotDrawn is open source') a('https://github.com/getsdrawn/getsdrawndotcom') a('https://reddit.com/r/redditgetsdrawn') #print doc docre = doc.render() #s = docre.decode('ascii', 'ignore') yourstring = docre.encode('ascii', 'ignore').decode('ascii') indfil = ('/home/wcmckee/gotdrawn/index.html') mkind = open(indfil, 'w') mkind.write(yourstring) mkind.close() fertz = datzpat + '/' fertz print doc os.chdir(fertz) for flc in fulcom: if 'http://i.imgur.com' in flc.url: print flc.title print flc.url print flc.author res = requests.get(flc.url, stream=True) with open(str(flc.author) + '-' + str(artes.date()) + '-reference.png', 'wb') as outfil: shutil.copyfileobj(res.raw, outfil) del res for flcz in flc.comments: print flcz.body flcz.author flcz.body ###Output _____no_output_____
ExampleNotebooks/Non Linear Regression.ipynb
###Markdown Do Linear Regression for Simple as well as Plynomial Features (try different Degrees, 3, 4, 5 and see their effect) for the six states ###Code import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures df1 = pd.read_csv("../data/sevenday_rolling_average_of_new_cases.csv") # df1.head(10) # df1.tail(10) df2 = pd.read_csv("../data/sevenday_rolling_average_of_new_deaths.csv") # df2.head(10) # df2.tail(10) # Fitting Linear Regression to the dataset lin = LinearRegression() # Fitting Polynomial Regression to the dataset, degree = 4 poly = PolynomialFeatures(degree = 4) ####### Dataset for California ################ print('************* Data Set for California *****************') list_x1 = df1[['CA']] list_y1 = df2['CA'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() print('************* Data Set for Florida *****************') list_x1 = df1[['FL']] list_y1 = df2['FL'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() print('************* Data Set for Georgia *****************') list_x1 = df1[['GA']] list_y1 = df2['GA'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() print('************* Data Set for Illinois *****************') list_x1 = df1[['IL']] list_y1 = df2['IL'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() print('************* Data Set for Wisconsin *****************') list_x1 = df1[['WI']] list_y1 = df2['WI'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() print('************* Data Set for Texas *****************') list_x1 = df1[['TX']] list_y1 = df2['TX'] lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() def nonLinearFit(list_x1,list_y1,title="Title",xtitle="X",ytitle="Y"): lin = LinearRegression() poly = PolynomialFeatures(degree = 4) lin.fit(list_x1, list_y1) X_poly = poly.fit_transform(list_x1) poly.fit(X_poly, list_y1) lin2 = LinearRegression() lin2.fit(X_poly, list_y1) # Visualising the Linear Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin.predict(list_x1), color = 'green') plt.title('Linear Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() # Visualising the Polynomial Regression results plt.scatter(list_x1, list_y1, color = 'red') plt.plot(list_x1, lin2.predict(poly.fit_transform(list_x1)), color = 'green') plt.title('Polynomial Regression') plt.xlabel('Number of Cases') plt.ylabel('Number of Deaths') plt.show() nonLinearFit(list_x1,list_y1) ###Output _____no_output_____
exercises/solutions/ex07/LearningAndPlanning.ipynb
###Markdown Exercise 7) Learning and Planning In this exercise, we will again investigate the inverted pendulum from the `gym` environment. We want to check, which benefits the implementation of planning offers.Please note that the parameter $n$ has a different meaning in the context of planning (number of planning steps per actual step) than in the context of n-step learning. ###Code import numpy as np import gym gym.logger.set_level(40) import random import time from tqdm.notebook import tqdm import matplotlib.pyplot as plt plt.style.use('seaborn-talk') ###Output _____no_output_____ ###Markdown We will reuse the discretization routine from the previous exercise: ###Code d_T = 15 d_theta = 15 d_omega = 15 def discretize_state(states): limits = [1, 1, 8] nb_disc_intervals = [d_theta, d_theta, d_omega] # bring to value range [-1, 1] norm_states = [state / limit for state, limit in zip(states, limits)] interval_lengths = [2 / d for d in nb_disc_intervals] disc_state = [(norm_state + 1) // interval_length for norm_state, interval_length in zip(norm_states, interval_lengths)] disc_state = [(state - 1) if state == d else state for state, d in zip(disc_state, nb_disc_intervals)] # ensure that disc_state < d return np.array(disc_state) def continualize_action(disc_action): limit = 2 interval_length = 2 / (d_T-1) norm_action = disc_action * interval_length cont_action = (norm_action - 1) * limit return np.array(cont_action).flatten() ###Output _____no_output_____ ###Markdown 1) Dyna-Q Write a Dyna-Q algorithm to solve the inverted pendulum. Check the quality of the result for different number of episodes, number of steps per episode and number of planning steps per interaction.Make sure that the total number of learning steps stays the same for different n, such that comparisons are fair:$\text{episodes} \cdot \text{steps} \cdot (1+n) = \text{const.}$Interesting metrics for a comparison could be e.g. the execution time (the tqdm loading bar shows execution time of loops, alternatively you can use the time.time() command to get the momentary system time in seconds) and training stability. ![](DynaQ_Algo.png) Solution 1) The solution code is given below. ###Code def pendulumDynaQ(alpha, gamma, epsilon, n, nb_episodes, nb_steps): env = gym.make('Pendulum-v0') env = env.unwrapped action_values = np.zeros([d_theta, d_theta, d_omega, d_T]) pi = np.zeros([d_theta, d_theta, d_omega]) model = {} # dictionary cumulative_reward_history = [] # we can use this to figure out how well the learning worked for j in tqdm(range(nb_episodes), position=0, leave=True): ### BEGIN SOLUTION rewards = [] # this time, this list is only for monitoring state = env.reset() # initialize x_0 state = tuple(discretize_state(state).astype(int)) for k in range(nb_steps): # sample experiences for the model if np.random.uniform(0, 1) < epsilon: action = np.random.choice(d_T) # explorative action else: action = pi[state].astype(int) # exploitative action cont_action = continualize_action(action) next_state, reward, done, _ = env.step(cont_action) next_state = tuple(discretize_state(next_state).astype(int)) # learn from the momentary experience action_values[state][action] += alpha * (reward + gamma * np.max(action_values[next_state]) - action_values[state][action] ) pi[state] = np.argmax(action_values[state]) model[state, action] = (next_state, reward) # update the model accoring to the latest experience state = next_state rewards.append(reward) # learn from the model, IMPORTANT: USE DIFFERENT VARIABLES HERE for i in range(n): # sample a random key from the dict: this state action combination has surely been taken in the past x, u = random.sample(model.keys(), 1)[0] x_1, r = model[x, u] action_values[x][u] += alpha * (r + gamma * np.max(action_values[x_1]) - action_values[x][u] ) pi[x] = np.argmax(action_values[x]) if done: break cumulative_reward_history.append(np.sum(rewards)) env.close() ### END SOLUTION return cumulative_reward_history, pi ###Output _____no_output_____ ###Markdown Function to evaluate and render the measurement using the gym environment: ###Code def experiment(pi,nb_steps = 300): # Runs the inverted pendulum experiment using policy pi for nb_steps steps env = gym.make('Pendulum-v0') env = env.unwrapped state = env.reset() # initialize x_0 disc_state = tuple(discretize_state(state).astype(int)) # only tuples of integers can be used as index disc_action = pi[disc_state].astype(int) for k in range(nb_steps): cont_action = continualize_action(disc_action) env.render() # comment out for faster execution state, reward, done, _ = env.step(cont_action) disc_state = tuple(discretize_state(state).astype(int)) if done: break disc_action = pi[disc_state].astype(int) # exploitative action env.close() ###Output _____no_output_____ ###Markdown Let's use nb_episodes = 5000, nb_steps = 500, n = 0 as a first try. This is effectively Q learning.\begin{align}5000 \cdot 500 \cdot (0+1) &= 2.5 \cdot 10^6\end{align}The resulting policy is satisfactory. ###Code ### train print("Run without planning") no_planning_history, no_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 0, nb_episodes = 5000, nb_steps = 500) ### run and render the experiment experiment(no_planning_pi,nb_steps = 300) ###Output _____no_output_____ ###Markdown Now let's try $n=9$ with the same nb_steps = 500:\begin{align}\text{nb_episodes} &= \frac{2.5 \cdot 10^6}{500 \cdot (9+1)} = 500\end{align}The resulting policy also looks good. ###Code ### train print("Run with planning") with_planning_history, with_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 9, nb_episodes = 500, nb_steps = 500) ### run and render the experiment experiment(with_planning_pi,nb_steps = 300) ###Output _____no_output_____ ###Markdown Now lets compare the cumulative rewards: ###Code plt.plot(no_planning_history) plt.plot(with_planning_history) plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.show() ###Output _____no_output_____ ###Markdown The cumulative reward over the episodes both seems to have high variance.So why should we prefer the planning method? Planning leads to the agent interacting less often with the "real" environment, such that in the end fewer interaction time is needed. 2) Simulation-based planning Although it can be useful for small state spaces, building a system model by storing large amounts of state transitions like in task (1) is rarely feasible in engineering. As engineers, we are capable of a more efficient way of system modeling that we can utilize here: differential equations.Using a state-space model allows to efficiently integrate existing pre-knowledge into the Dyna-Q algorithm we already used. To do so, write a class `pendulum_model` that implements a model of the pendulum. This class should work similar to `gym`: it should at least have a `step` and a `reset` method. In the step method, make use of forward Euler integration to simulate the system dynamics. In the reset method, allow to pass an optional initial state to the model, such that we can easily compare model and environment. If no initial state is passed to the `reset` function, a random initial state should be determined.Integrate this model into a Dyna-Q algorithm. Model of the pendulum in differential-equation form for change of the angular frequency $\omega$ and the angle $\theta$ depending on the torque $T_\mathrm{u}$:\begin{align}\dot{\omega} &= -\frac{3 g}{2 l} \text{sin}(\theta +\pi) + \frac{1}{J} T_\mathrm{u}\\\dot{\theta} &= \omega\end{align}Parameters (gravity constant $g$, mass $m$, length $l$ and intertia $J$ of the pendulum):\begin{align}g&=10 \, \frac{\text{m}}{\text{s}^2}&m&=1 \, \text{kg}&l&=1 \, \text{m}&J&=\frac{1}{3} m l^2\end{align}Forward Euler integration:\begin{align}\dot{x}(k T_S) \approx \frac{x[k+1] - x[k]}{T_S}\end{align}with sampling time $T_S = 0.05 \, \text{s}$Reward function:\begin{align}r_{k+1} = -(\theta^2[k] + 0.1 \, \text{s}^2 \cdot \omega^2[k] + 0.001 \frac{1}{(\text{N}\text{m})^2} \cdot T_\mathrm{u}^2[k])\end{align}Limitations of state and action space:\begin{align}\theta &\in [-\pi, \pi]&\omega &\in [-8 \, \frac{1}{\text{s}}, 8 \, \frac{1}{\text{s}}]&T_\mathrm{u} &\in [-2 \, \text{N}\text{m}, 2 \, \text{N}\text{m}]\end{align}And of course input and output space:\begin{align}\text{action}&=T_\mathrm{u}&\text{state}&=\begin{bmatrix}\text{cos}(\theta)\\\text{sin}(\theta)\\\omega\end{bmatrix}\end{align} Solution 2) Model-based planning does not necessarily run faster than experience-based planning. However, experience-based planning fails to cover the whole state space especially in the earlier episodes when there are too few experiences. On the other hand, model-based planning can, of course, only be performed if a state-space model with accurate parametrization is available. In order to overcome parametric deviations between state-space model and environment, one could even use the measurements from the actual environment in order to identify the parameters of the model during runtime. ###Code class pendulum_model: def __init__(self, dt=0.05, m=1, g=10, l=1): ### BEGIN SOLUTION self.max_speed = 8 self.max_torque = 2 self.dt = dt # sampling time in s self.g = g # gravity in m / s^2 self.m = m # mass in kg self.l = l # length in m self.J = 1 / 3 * m * l ** 2 # pedulums moment of inertia in kg * m^2 ### END SOLUTION def reset(self, state=None): ### BEGIN SOLUTION # if no state is give, set randomly if np.any(state == None): self.theta = np.random.uniform(-np.pi, +np.pi) self.omega = np.random.uniform(-self.max_speed, +self.max_speed) # else set initial state as given else: self.theta = np.arctan2(state[1], state[0]) self.omega = state[2] state = np.array([np.cos(self.theta), np.sin(self.theta), self.omega]) ### END SOLUTION return state def step(self, T_u): ### BEGIN SOLUTION T_u = np.clip(T_u, -self.max_torque, +self.max_torque)[0] reward = -(self.angle_normalize(self.theta)** 2 + 0.1 * self.omega ** 2 + 0.001 * (T_u ** 2)) # differential-equations for state values self.omega = self.omega + self.dt * (-3 * self.g/(2 * self.l) * np.sin(self.theta + np.pi) + 1 / self.J * T_u) self.theta = self.theta + self.dt * self.omega self.omega = np.clip(self.omega, -self.max_speed, +self.max_speed) state = np.array([np.cos(self.theta), np.sin(self.theta), self.omega]) ### END SOLUTION return state, reward def angle_normalize(self, theta): # usage of this helper function is optional return (((theta+np.pi) % (2*np.pi)) - np.pi) ###Output _____no_output_____ ###Markdown The following cell is for debugging of the `pendulum_model` class. ###Code env = gym.make('Pendulum-v0') env = env.unwrapped # removes a builtin time limit of k_T = 200, we want to determine the time limit ourselves model = pendulum_model() state = env.reset() print(state) m_state = model.reset(state) # model is set to state of env for _ in range(10000): print(f"state: {state}") print(f"model: {m_state}") print() action = env.action_space.sample() state, reward, done, _ = env.step(action) # take action on env m_state, m_reward = model.step(action) # take the same action on model print(f"reward difference: {reward- m_reward}, env_reward:{reward}, model_reward:{m_reward}") env.close() ###Output [ 0.04729206 -0.9988811 -0.48690693] state: [ 0.04729206 -0.9988811 -0.48690693] model: [ 0.04729206 -0.9988811 -0.48690693] reward difference: 0.0, env_reward:-2.347137870403856, model_reward:-2.347137870403856 state: [-0.02615445 -0.99965791 -1.46934266] model: [-0.0150763 -0.99988635 -1.2477315 ] reward difference: -0.09548089253936443, env_reward:-2.7685024582029105, model_reward:-2.673021565663546 state: [-0.12529803 -0.99211915 -1.98941596] model: [-0.11413574 -0.99346516 -1.98616275] reward difference: -0.03931346760092058, env_reward:-3.275556891403601, model_reward:-3.2362434238026805 state: [-0.26933651 -0.96304613 -2.94151574] model: [-0.24882617 -0.96854816 -2.74166215] reward difference: -0.19142615552259734, env_reward:-4.2672246797117035, model_reward:-4.075798524189106 state: [-0.42766097 -0.90393921 -3.38399161] model: [-0.41156654 -0.91137972 -3.45408283] reward difference: -0.023132419701973994, env_reward:-5.196133355529123, model_reward:-5.173000935827149 state: [-0.6001189 -0.79991081 -4.03492281] model: [-0.58994085 -0.80744647 -4.13626646] reward difference: 0.026882021822394186, env_reward:-6.532633679678635, model_reward:-6.559515701501029 state: [-0.7634742 -0.64583833 -4.50051541] model: [-0.76287116 -0.64655053 -4.73513428] reward difference: 0.21213356246643933, env_reward:-7.976606911111203, model_reward:-8.188740473577642 state: [-0.89805163 -0.43989006 -4.93289137] model: [-0.90382025 -0.42791233 -5.21744704] reward difference: 0.3604319264297384, env_reward:-9.651926459831943, model_reward:-10.012358386261681 state: [-0.98409673 -0.17763342 -5.53790301] model: [-0.98648809 -0.16383297 -5.55213599] reward difference: 0.09898179977324872, env_reward:-11.848332956347834, model_reward:-11.947314756121083 state: [-0.99331007 0.11547775 -5.8863412 ] model: [-0.99284287 0.11942795 -5.68577137] reward difference: -0.25615792332739495, env_reward:-12.622020937337883, model_reward:-12.365863014010488 state: [-0.92217274 0.38677829 -5.62798912] model: [-0.92141329 0.38858402 -5.58761322] reward difference: -0.05603260059965187, env_reward:-10.699492385421461, model_reward:-10.64345978482181 state: [-0.7868492 0.61714531 -5.35948208] model: [-0.78755992 0.61623808 -5.29725404] reward difference: -0.06060532801335761, env_reward:-9.005808287672984, model_reward:-8.945202959659627 state: [-0.60988103 0.79249298 -4.99552698] model: [-0.61693183 0.78701659 -4.84002067] reward difference: -0.11311016325189716, env_reward:-7.453939041676244, model_reward:-7.340828878424347 state: [-0.42512089 0.90513658 -4.33630033] model: [-0.43722651 0.89935142 -4.24651538] reward difference: -0.022947198758467735, env_reward:-5.921001441148226, model_reward:-5.898054242389758 state: [-0.24621588 0.96921501 -3.806429 ] model: [-0.27014144 0.96282065 -3.57945087] reward difference: -0.07690324469501775, env_reward:-4.7609447013560615, model_reward:-4.684041456661044 state: [-0.1028942 0.99469231 -2.91394714] model: [-0.13071198 0.99142038 -2.84905685] reward difference: 0.057160156166453646, env_reward:-3.653470540796465, model_reward:-3.7106306969629186 state: [ 0.01720364 0.99985201 -2.40562246] model: [-0.0252156 0.99968204 -2.11737629] reward difference: 0.0032412844849423195, env_reward:-2.993054088069994, model_reward:-2.996295372554936 state: [ 0.10608643 0.99435691 -1.78163882] model: [ 0.04346353 0.99905501 -1.37391003] reward difference: 0.05925356843606355, env_reward:-2.4634088805560816, model_reward:-2.522662448992145 state: [ 0.14931752 0.9887893 -0.8718319 ] model: [ 0.07422973 0.99724117 -0.61641681] reward difference: 0.182486086370651, env_reward:-2.0958453491376874, model_reward:-2.2783314355083384 state: [ 0.16248864 0.98671041 -0.26668534] model: [0.06801094 0.99768458 0.1246918 ] reward difference: 0.2713558817624311, env_reward:-1.9907758626585592, model_reward:-2.2621317444209903 state: [0.15051906 0.98860711 0.24237986] model: [0.02499054 0.99968769 0.86140685] reward difference: 0.44227817769181543, env_reward:-2.024730186000297, model_reward:-2.4670083636921123 state: [0.08816519 0.99610587 1.25626974] model: [-0.05621693 0.99841858 1.62479434] reward difference: 0.555587689923438, env_reward:-2.3592169314034903, model_reward:-2.9148046213269283 state: [-0.02599657 0.99966203 2.2855861 ] model: [-0.17473103 0.9846162 2.38772012] reward difference: 0.547987397602447, env_reward:-3.0754641441889206, model_reward:-3.6234515417913675 state: [-0.19025837 0.98173405 3.30851647] model: [-0.32652495 0.94518858 3.13984147] reward difference: 0.40881863213494185, env_reward:-4.20075779485148, model_reward:-4.609576426986422 state: [-0.37775543 0.92590541 3.91891171] model: [-0.50099366 0.86545095 3.84243764] reward difference: 0.49752680177334785, env_reward:-5.371057638946997, model_reward:-5.868584440720345 state: [-0.57378169 0.81900829 4.47489842] model: [-0.68088969 0.73238599 4.48460374] reward difference: 0.6293018604132294, env_reward:-6.763225499860063, model_reward:-7.392527360273292 state: [-0.76202704 0.64754521 5.10643786] model: [-0.84185687 0.53970086 5.03475739] reward difference: 0.5998660694273941, env_reward:-8.547682346866026, model_reward:-9.14754841629342 state: [-0.91100921 0.412386 5.58574035] model: [-0.95589009 0.29372458 5.43921521] reward difference: 0.5443012112176469, env_reward:-10.501959507080816, model_reward:-11.046260718298463 state: [-0.99296995 0.11836674 6.12853394] model: [-0.99989398 0.01456126 5.67118385] reward difference: 0.10044873925641618, env_reward:-12.89415216462199, model_reward:-12.994600903878407 state: [-0.98127326 -0.19262083 6.24954377] model: [-0.96387111 -0.26636909 5.68371654] reward difference: -1.1163038348633485, env_reward:-12.59497385000322, model_reward:-11.47867001513987 state: [-0.87821621 -0.47826382 6.09688835] model: [-0.85574849 -0.51739204 5.48353023] reward difference: -0.9467752870514872, env_reward:-10.702854393648584, model_reward:-9.756079106597097 state: [-0.7112208 -0.70296868 5.61772573] model: [-0.69794404 -0.7161523 5.08946296] reward difference: -0.6536613280578596, env_reward:-8.735068404278886, model_reward:-8.081407076221026 state: [-0.51136547 -0.85936334 5.08920703] model: [-0.51833977 -0.85517477 4.55228412] reward difference: -0.4833155714978714, env_reward:-7.0324607859734245, model_reward:-6.549145214475553 state: [-0.30380415 -0.95273451 4.5617996 ] model: [-0.34202449 -0.93969104 3.9167588 ] reward difference: -0.39345561279745755, env_reward:-5.614279998321623, model_reward:-5.220824385524166 state: [-0.10924498 -0.99401486 3.98439079] model: [-0.18702034 -0.98235604 3.21884762] reward difference: -0.28089682477633726, env_reward:-4.410817109231205, model_reward:-4.129920284454868 state: [ 0.0530908 -0.99858969 3.25158456] model: [-0.06394863 -0.99795319 2.48271584] reward difference: -0.07171283884069046, env_reward:-3.3614458095173347, model_reward:-3.2897329706766443 state: [ 0.18394988 -0.98293562 2.63775272] model: [ 0.02305598 -0.99973418 1.74100647] reward difference: 0.08240824524532808, env_reward:-2.6172906693401954, model_reward:-2.6996989145855235 state: [ 0.28391827 -0.95884848 2.05749358] model: [ 0.07294583 -0.9973359 0.99905296] reward difference: 0.2739653522538599, env_reward:-2.0727066825692653, model_reward:-2.346672034823125 state: [ 0.36052075 -0.93275119 1.61896093] model: [ 0.08615778 -0.9962815 0.26508122] reward difference: 0.5040250588160831, env_reward:-1.70722915176797, model_reward:-2.211254210584053 state: [ 0.39869385 -0.91708408 0.82532059] model: [ 0.06188348 -0.99808338 -0.48683375] reward difference: 0.885049722562034, env_reward:-1.4171496089224476, model_reward:-2.3021993314844815 state: [ 0.41416931 -0.91019986 0.33875608] model: [ 6.56352874e-04 -9.99999785e-01 -1.22533386e+00] reward difference: 1.2958067883193332, env_reward:-1.3198417084933332, model_reward:-2.6156484968126663 state: [ 0.40124767 -0.9159696 -0.28302783] model: [-0.09780158 -0.99520593 -1.9722904 ] reward difference: 1.8249505074727752, env_reward:-1.3493641656187378, model_reward:-3.174314673091513 state: [ 0.36170026 -0.93229444 -0.85575174] model: [-0.23148832 -0.97283768 -2.71298219] reward difference: 2.4769751834531237, env_reward:-1.5152291007909446, model_reward:-3.9922042842440684 state: [ 0.2842293 -0.95875633 -1.63777011] model: [-0.39488695 -0.91872972 -3.44675033] reward difference: 3.1822381743105796, env_reward:-1.9146823917112008, model_reward:-5.0969205660217805 state: [ 0.16076576 -0.98699259 -2.53472054] model: [-0.57547053 -0.81782251 -4.14469178] reward difference: 3.8589053777047595, env_reward:-2.628802853441939, model_reward:-6.487708231146699 state: [ 2.20812436e-04 -9.99999976e-01 -3.22491286e+00] model: [-0.75191179 -0.65926373 -4.75555606] reward difference: 4.61970767117165, env_reward:-3.5079339203931936, model_reward:-8.127641591564844 state: [-0.2053384 -0.97869103 -4.14060558] model: [-0.89741352 -0.4411904 -5.25828849] reward difference: 5.098057893820938, env_reward:-4.8765511221278075, model_reward:-9.974609015948745 state: [-0.42539464 -0.90500795 -4.65176884] model: [-0.98419575 -0.17708396 -5.57803854] reward difference: 5.689421526448203, env_reward:-6.20479076787388, model_reward:-11.894212294322083 state: [-0.64942606 -0.76042474 -5.34863051] model: [-0.99422046 0.10735774 -5.71175679] reward difference: 4.419376126499072, env_reward:-8.050806322372445, model_reward:-12.470182448871517 state: [-0.84921556 -0.52804633 -6.1533706 ] model: [-0.92501813 0.37992298 -5.64295956] reward difference: 0.2869971967029574, env_reward:-10.470439828155685, model_reward:-10.757437024858643 state: [-0.97299875 -0.2308104 -6.46775751] model: [-0.79157769 0.61106854 -5.35393494] reward difference: -3.6059941593861566, env_reward:-12.644335554345197, model_reward:-9.03834139495904 state: [-0.99444276 0.10527863 -6.76769137] model: [-0.61964303 0.78488376 -4.90197484] reward difference: -6.3817471265246875, env_reward:-13.800622611417555, model_reward:-7.418875484892868 state: [-0.90971856 0.41522542 -6.45432997] model: [-0.43785212 0.89904701 -4.3015919 ] reward difference: -5.581424675850777, env_reward:-11.529600701506208, model_reward:-5.948176025655431 state: [-0.74711974 0.66468947 -5.9777506 ] model: [-0.26890482 0.96316676 -3.61904862] reward difference: -4.69663831770155, env_reward:-9.403607360508051, model_reward:-4.706969042806501 state: [-0.54329718 0.83954046 -5.38717435] model: [-0.12730585 0.99186351 -2.8920706 ] reward difference: -3.7827234408972124, env_reward:-7.506205731653463, model_reward:-3.7234822907562504 state: [-0.31930164 0.94765314 -4.98734085] model: [-0.01966778 0.99980657 -2.15966406] reward difference: -3.0853769774851165, env_reward:-6.08155960846947, model_reward:-2.9961826309843533 state: [-0.11416164 0.99346219 -4.21162755] model: [ 0.05063731 0.99871711 -1.40656046] reward difference: -2.105045849291529, env_reward:-4.61391517653009, model_reward:-2.5088693272385605 state: [ 0.05544588 0.99846169 -3.39770821] model: [ 0.08326653 0.99652731 -0.65408149] reward difference: -1.1954028344515697, env_reward:-3.4506462719343496, model_reward:-2.25524343748278 state: [ 0.18638301 0.98247716 -2.64010046] model: [0.0785943 0.99690668 0.09375206] reward difference: -0.3832752109523896, env_reward:-2.6119140521246007, model_reward:-2.228638841172211 state: [ 0.28720505 0.95786912 -2.07656645] model: [0.03702868 0.9993142 0.83276588] reward difference: 0.3534630916938424, env_reward:-2.0683166070567145, model_reward:-2.421779698750557 state: [ 0.35232766 0.93587671 -1.37498813] model: [-0.04202099 0.99911673 1.58141036] reward difference: 1.1963567524901668, env_reward:-1.6588781483861865, model_reward:-2.8552349008763533 state: [ 0.39730491 0.91768666 -0.97042122] model: [-0.157173 0.98757109 2.31588088] reward difference: 2.0795476205309322, env_reward:-1.4450025881229736, model_reward:-3.524550208653906 state: [ 0.41214217 0.91111955 -0.32451624] model: [-0.30558187 0.9521658 3.05444119] reward difference: 3.148593523027377, env_reward:-1.3240083808099399, model_reward:-4.472601903837317 state: [0.39281581 0.91961717 0.42224832] model: [-0.4786674 0.87799631 3.77173679] reward difference: 4.327258022160408, env_reward:-1.3837736536460394, model_reward:-5.711031675806447 state: [0.35483189 0.93493012 0.81914576] model: [-0.6593215 0.75186113 4.41559325] reward difference: 5.670595266474288, env_reward:-1.5266247481731439, model_reward:-7.197220014647431 state: [0.28519849 0.95846848 1.47041473] model: [-0.82418728 0.56631733 4.97699266] reward difference: 7.067753967180879, env_reward:-1.8590306399043701, model_reward:-8.92678460708525 state: [0.18323514 0.98306911 2.09874409] model: [-0.94533678 0.32609564 5.39720456] reward difference: 8.442924168205922, env_reward:-2.3637763463460377, model_reward:-10.80670051455196 state: [0.04943295 0.99877744 2.69646419] model: [-0.99872865 0.05040926 5.63479721] reward difference: 9.688799486437166, env_reward:-3.04348076127105, model_reward:-12.732280247708216 state: [-0.13277891 0.99114568 3.65250579] model: [-0.97281228 -0.23159503 5.68295208] reward difference: 7.447746844224604, env_reward:-4.2385762109872624, model_reward:-11.686323055211867 state: [-0.35266635 0.93574914 4.54493634] model: [-0.87296291 -0.48778659 5.51670937] reward difference: 4.175806609812435, env_reward:-5.798500900525779, model_reward:-9.974307510338214 state: [-0.57221756 0.82010186 4.97576615] model: [-0.7203993 -0.69355955 5.13732032] reward difference: 1.0524177196035822, env_reward:-7.228243086745829, model_reward:-8.280660806349411 state: [-0.77651271 0.63010159 5.59809965] model: [-0.54257723 -0.84000592 4.61751351] reward difference: -2.4548631582990614, env_reward:-9.185309825406721, model_reward:-6.7304466671076595 state: [-0.92785714 0.37293583 5.99025828] model: [-0.36564694 -0.93075363 3.98348819] reward difference: -5.832401023402368, env_reward:-11.205069107469514, model_reward:-5.372668084067146 state: [-0.99836485 0.05716311 6.49953663] model: [-0.20795393 -0.97813862 3.2969018 ] reward difference: -9.481561400585587, env_reward:-13.741038308968601, model_reward:-4.2594769083830135 state: [-0.9672425 -0.25385417 6.27714337] model: [-0.08188917 -0.99664144 2.55003455] reward difference: -8.881132271067647, env_reward:-12.266618271122779, model_reward:-3.3854860000551312 state: [-0.83912549 -0.54393787 6.36919908] model: [ 0.00885271 -0.99996081 1.81667579] reward difference: -7.873738411912299, env_reward:-10.644637400375288, model_reward:-2.770898988462988 state: [-0.63606972 -0.77163159 6.12558892] model: [ 0.06255806 -0.99804133 1.07492234] reward difference: -6.4705393062619265, env_reward:-8.863137718529886, model_reward:-2.3925984122679593 state: [-0.38983111 -0.92088637 5.77891718] model: [ 0.07941492 -0.99684165 0.33799394] reward difference: -4.99000051216426, env_reward:-7.225463728385939, model_reward:-2.2354632162216794 state: [-0.14354764 -0.98964341 5.12805864] model: [ 0.05908186 -0.99825314 -0.40764698] reward difference: -3.2685860345810585, env_reward:-5.570385338429996, model_reward:-2.3017993038489375 state: [ 0.075712 -0.99712973 4.39659547] model: [ 0.00132637 -0.99999912 -1.15579837] reward difference: -1.5712425336371254, env_reward:-4.170452973888315, model_reward:-2.5992104402511895 state: [ 0.2441405 -0.96973987 3.41697499] model: [-0.09440217 -0.99553414 -1.91738637] reward difference: 0.22001235015895837, env_reward:-2.9221640366128945, model_reward:-3.142176386771853 state: [ 0.37952159 -0.92518288 2.85291739] model: [-0.22538353 -0.97427012 -2.65587461] reward difference: 1.7287526827822361, env_reward:-2.2099109322657737, model_reward:-3.93866361504801 state: [ 0.47778163 -0.87847864 2.17697179] model: [-0.38630357 -0.9223717 -3.38568012] reward difference: 3.3924741597038555, env_reward:-1.6246888514444675, model_reward:-5.017163011148323 state: [ 0.54057933 -0.84129305 1.4599569 ] model: [-0.56516977 -0.82497463 -4.08036669] reward difference: 5.167581678392129, env_reward:-1.2145645579836186, model_reward:-6.382146236375748 state: [ 0.56610235 -0.82433496 0.61288662] model: [-0.74205725 -0.67033651 -4.70990269] reward difference: 7.035057477311948, env_reward:-0.977339450609326, model_reward:-8.012396927921275 state: [ 0.57127484 -0.82075883 0.12576714] model: [-0.88958649 -0.45676676 -5.20609848] reward difference: 8.896044537008429, env_reward:-0.9319457730558378, model_reward:-9.827990310064267 state: [ 0.53924307 -0.84215017 -0.7704045 ] model: [-0.98081014 -0.19496529 -5.56270367] reward difference: 10.707704662220795, env_reward:-1.0618706111677845, model_reward:-11.769575273388579 state: [ 0.47901005 -0.87780942 -1.40022858] model: [-0.99602255 0.08910153 -5.70883822] reward difference: 11.232380307786718, env_reward:-1.3444360363232037, model_reward:-12.576816344109922 state: [ 0.38027 -0.92487552 -2.18876802] model: [-0.9317309 0.36314947 -5.64852119] reward difference: 8.990041934675999, env_reward:-1.8736967897961485, model_reward:-10.863738724472148 state: [ 0.23807337 -0.97124717 -2.9941302 ] model: [-0.80165772 0.59778332 -5.38174437] reward difference: 6.484130973214587, env_reward:-2.6664849183296604, model_reward:-9.150615891544247 state: [ 0.05410402 -0.9985353 -3.72502495] model: [-0.63142283 0.77543872 -4.93352985] reward difference: 3.8274563625433915, env_reward:-3.688573550560574, model_reward:-7.516029913103965 state: [-0.17501097 -0.98456648 -4.60094718] model: [-0.44884429 0.89360998 -4.35830184] reward difference: 0.8779880109276181, env_reward:-5.16792866864401, model_reward:-6.045916679571628 state: [-0.4270318 -0.90423661 -5.30581531] model: [-0.27746144 0.96073677 -3.68641652] reward difference: -2.0746529029026783, env_reward:-6.863328640483804, model_reward:-4.7886757375811255 state: [-0.67475802 -0.73803904 -5.98858213] model: [-0.13245572 0.99118892 -2.96609341] reward difference: -5.146866001054104, env_reward:-8.932298303080513, model_reward:-3.78543230202641 state: [-0.86950194 -0.49392953 -6.27112554] model: [-0.02238663 0.99974939 -2.20915242] reward difference: -7.796997486668447, env_reward:-10.827185214844892, model_reward:-3.030187728176445 state: [-0.98019288 -0.19804524 -6.34480022] model: [ 0.04981596 0.99875841 -1.44450176] reward difference: -10.160385743644941, env_reward:-12.683002372440056, model_reward:-2.522616628795114 state: [-0.99289154 0.11902264 -6.37337452] model: [ 0.0842085 0.99644816 -0.68943496] reward difference: -10.939031508799783, env_reward:-13.198007070951318, model_reward:-2.2589755621515355 state: [-0.90322759 0.42916187 -6.48518358] model: [0.08182439 0.99664676 0.04784735] reward difference: -9.268122070807465, env_reward:-11.485170845007973, model_reward:-2.2170487742005083 state: [-0.73170966 0.68161644 -6.12809708] model: [0.04204891 0.99911555 0.79709318] reward difference: -7.074652185378586, env_reward:-9.476660133162977, model_reward:-2.4020079477843903 state: [-0.52182343 0.85305352 -5.43679473] model: [-0.03570282 0.99936245 1.55543435] reward difference: -4.626553936119985, env_reward:-7.449600143916911, model_reward:-2.823046207796925 state: [-0.30776873 0.9514612 -4.722801 ] model: [-0.15056892 0.98859951 2.30866636] reward difference: -2.2805256764496535, env_reward:-5.779790317462261, model_reward:-3.4992646410126076 state: [-0.12028685 0.99273918 -3.84536435] model: [-0.29939559 0.95412907 3.05830804] reward difference: 0.11097518950954655, env_reward:-4.340112760322959, model_reward:-4.451087949832505 state: [ 0.04063591 0.99917402 -3.22451844] model: [-0.47278187 0.8811795 3.76771941] reward difference: 2.2954275631593544, env_reward:-3.38198292230645, model_reward:-5.6774104854658045 state: [ 0.156742 0.98763958 -2.33487815] model: [-0.65503274 0.7556005 4.43561703] reward difference: 4.645916451723423, env_reward:-2.5429705972555547, model_reward:-7.188887048978978 state: [ 0.23269067 0.9725508 -1.54904751] model: [-0.82173822 0.56986516 5.00457244] reward difference: 6.907346569102724, env_reward:-2.0254488838677256, model_reward:-8.93279545297045 state: [ 0.26619591 0.96391895 -0.69202003] model: [-0.94459947 0.32822528 5.43835203] reward difference: 9.096356224701601, env_reward:-1.7431414428131522, model_reward:-10.839497667514754 state: [ 0.27421998 0.96166699 -0.16668225] model: [-0.99871543 0.0506704 5.67464092] reward difference: 11.099147742561662, env_reward:-1.6747572463994846, model_reward:-12.773904988961148 state: [0.24955601 0.96836037 0.51113526] model: [-0.97255356 -0.23267911 5.71047208] reward difference: 9.945444679617657, env_reward:-1.7650944801735442, model_reward:-11.710539159791201 state: [0.18497425 0.98274337 1.32352147] model: [-0.87184237 -0.48978656 5.54026855] reward difference: 7.8923253587860085, env_reward:-2.0936825813766657, model_reward:-9.986007940162674 state: [0.09030776 0.99591391 1.91229397] model: [-0.71782668 -0.69622184 5.16551437] reward difference: 5.734964935263662, env_reward:-2.559944159705742, model_reward:-8.294909094969404 state: [-0.03003061 0.99954898 2.40932178] model: [-0.53890196 -0.84236849 4.63085261] reward difference: 3.5806328536933156, env_reward:-3.143170826311823, model_reward:-6.723803680005139 state: [-0.18807475 0.98215472 3.18332836] model: [-0.36079333 -0.93264579 4.00029348] reward difference: 1.252553408653215, env_reward:-4.112379921557817, model_reward:-5.3649333302110325 state: [-0.38403809 0.92331725 4.09928508] model: [-0.20222523 -0.97933904 3.30977617] reward difference: -1.2974408764607865, env_reward:-5.543548733955506, model_reward:-4.246107857494719 state: [-0.6008114 0.79939081 5.00699882] model: [-0.07425949 -0.99723895 2.58603318] reward difference: -4.0394207460690605, env_reward:-7.417724117759613, model_reward:-3.3783033716905524 state: [-0.80642144 0.59134124 5.87119105] model: [ 0.0182379 -0.99983368 1.85133643] reward difference: -6.988346051284605, env_reward:-9.742300628637466, model_reward:-2.753954577352861 state: [-0.95221698 0.30542237 6.44678136] model: [ 0.07357564 -0.99728964 1.10806539] reward difference: -9.807601513403997, env_reward:-12.173423761534726, model_reward:-2.36582224813073 state: [-0.99946179 -0.03280448 6.86384658] model: [ 0.09198686 -0.99576022 0.36949808] reward difference: -12.175621139015098, env_reward:-14.375806095394873, model_reward:-2.2001849563797755 state: [-0.93113739 -0.36466857 6.80932945] model: [ 0.07311091 -0.99732382 -0.37881777] reward difference: -10.043052883415559, env_reward:-12.301300480446532, model_reward:-2.258247597030974 state: [-0.76968294 -0.63842633 6.38350241] model: [ 0.01645411 -0.99986462 -1.13442692] reward difference: -7.528530588914652, env_reward:-10.076915658439473, model_reward:-2.5483850695248207 state: [-0.53849845 -0.8426265 6.19380543] model: [-0.07696243 -0.99703399 -1.86986924] reward difference: -5.348569610508734, env_reward:-8.41367933622522, model_reward:-3.0651097257164865 state: [-0.28412174 -0.95878821 5.61127614] model: [-0.20630504 -0.97848773 -2.61517271] reward difference: -2.7567935234560252, env_reward:-6.606870186013028, model_reward:-3.8500766625570026 state: [-0.03099646 -0.99951949 5.14177737] model: [-0.36592374 -0.93064484 -3.33655889] reward difference: -0.3116160797832439, env_reward:-5.209736994314107, model_reward:-4.898120914530863 state: [ 0.19072894 -0.98164274 4.45812184] model: [-0.54483083 -0.83854598 -4.03124331] reward difference: 2.3458039651849916, env_reward:-3.8910237838949557, model_reward:-6.236827749079947 state: [ 0.37936946 -0.92524527 3.94420089] model: [-0.72334825 -0.69048339 -4.64903724] reward difference: 4.871024749570644, env_reward:-2.95284096569197, model_reward:-7.823865715262614 state: [ 0.51835866 -0.85516332 3.1163157 ] model: [-0.87591018 -0.4824742 -5.17359735] reward difference: 7.612720838220163, env_reward:-2.0238777664338006, model_reward:-9.636598604653964 state: [ 0.62334774 -0.78194475 2.56172487] model: [-0.9743636 -0.22497906 -5.53111391] reward difference: 10.09237817893164, env_reward:-1.462306363935284, model_reward:-11.554684542866923 state: [ 0.69615329 -0.71789317 1.94016808] model: [-0.99830926 0.05812583 -5.70160312] reward difference: 11.740733596057616, env_reward:-1.0177655468871298, model_reward:-12.758499142944746 state: [ 0.74634445 -0.66555989 1.45054875] model: [-0.94244176 0.33437035 -5.65556872] reward difference: 10.301469453052258, env_reward:-0.7431796683650129, model_reward:-11.04464912141727 state: [ 0.78445483 -0.62018596 1.18528024] model: [-0.81930883 0.57335246 -5.39309588] reward difference: 8.72649061874861, env_reward:-0.5918014505050365, model_reward:-9.318292069253646 state: [ 0.79756306 -0.60323558 0.4285598 ] model: [-0.65283534 0.75749985 -4.97766059] reward difference: 7.2480824508785275, env_reward:-0.4411676745479459, model_reward:-7.689250125426473 state: [ 0.78831409 -0.61527303 -0.30361045] model: [-0.4707541 0.88226446 -4.42352288] reward difference: 5.755803915866255, env_reward:-0.4503173045204281, model_reward:-6.206121220386684 state: [ 0.77080821 -0.63706727 -0.55910484] model: [-0.29797347 0.95457415 -3.75152651] reward difference: 4.408583656194538, env_reward:-0.5083104126162828, model_reward:-4.916894068810821 state: [ 0.73657152 -0.67635966 -1.0424313 ] model: [-0.15020476 0.98865491 -3.0358722 ] reward difference: 3.2250295078903815, env_reward:-0.660522433779799, model_reward:-3.8855519416701805 state: [ 0.68035144 -0.73288602 -1.594904 ] model: [-0.03593558 0.99935411 -2.29664117] reward difference: 2.1781009401925093, env_reward:-0.9326822030615654, model_reward:-3.110783143254075 state: [ 0.60585084 -0.79557825 -1.94814321] model: [ 0.04091048 0.99916282 -1.53730432] reward difference: 1.350990985396404, env_reward:-1.2259673205820012, model_reward:-2.576958305978405 state: [ 0.50216842 -0.86476984 -2.4946085 ] model: [ 0.08010704 0.99678627 -0.78542129] reward difference: 0.5698988140919741, env_reward:-1.7143090111207946, model_reward:-2.2842078252127687 state: [ 0.35511395 -0.93482302 -3.26137011] model: [ 0.08228686 0.99660869 -0.0437408 ] reward difference: -0.3067641184190655, env_reward:-2.5223682721138685, model_reward:-2.215604153694803 state: [ 0.16543947 -0.98621995 -3.93664722] model: [0.04711217 0.99888961 0.70500772] reward difference: -1.1513360232369476, env_reward:-3.523944450765516, model_reward:-2.3726084275285686 state: [-0.05888117 -0.998265 -4.50237706] model: [-0.02601103 0.99966166 1.46287168] reward difference: -1.9192972715456778, env_reward:-4.683728783993971, model_reward:-2.7644315124482937 state: [-0.32159875 -0.94687604 -5.37004408] model: [-0.13592537 0.99071908 2.20666951] reward difference: -3.0856740174156725, env_reward:-6.490773972624565, model_reward:-3.4050999552088923 state: [-0.57840073 -0.81575278 -5.78698764] model: [-0.28074085 0.95978361 2.96436949] reward difference: -3.813237476366285, env_reward:-8.13436400132036, model_reward:-4.321126524954075 ###Markdown Using $-\mathrm{sin}(\theta)$ instead of $\mathrm{sin}(\theta +\pi)$ makes no difference when assuming analytical precision, but due to numeric errors these formulations will still yield different results in numpy, mainly because $\pi$ is represented with finite (float) precision. In order to yield the same numbers as in `gym`, we will still make use of the (more cumbersome) $\mathrm{sin}(\theta +\pi)$. Write a function for the Dyna-Q algorithm, which uses the model we defined above: ###Code def pendulumModelDynaQ(alpha, gamma, epsilon, n, nb_episodes, nb_steps): env = gym.make('Pendulum-v0') env = env.unwrapped model = pendulum_model() action_values = np.zeros([d_theta, d_theta, d_omega, d_T]) pi = np.zeros([d_theta, d_theta, d_omega]) cumulative_reward_history = [] # we can use this to figure out how well the learning worked for j in tqdm(range(nb_episodes), position=0, leave=True): ### BEGIN SOLUTION rewards = [] # this time, this list is only for monitoring state = env.reset() # initialize x_0 state = tuple(discretize_state(state).astype(int)) for k in range(nb_steps): # sample experiences for the model if np.random.uniform(0, 1) < epsilon: action = np.random.choice(d_T) # explorative action else: action = pi[state].astype(int) # exploitative action cont_action = continualize_action(action) next_state, reward, done, _ = env.step(cont_action) next_state = tuple(discretize_state(next_state).astype(int)) # learn from the momentary experience action_values[state][action] += alpha * (reward + gamma * np.max(action_values[next_state]) - action_values[state][action] ) pi[state] = np.argmax(action_values[state]) # no model update is needed state = next_state rewards.append(reward) # learn from the model, IMPORTANT: USE DIFFERENT VARIABLES HERE for i in range(n): x = model.reset() # if no state is passed to the model, state is initialized randomly u_d = np.random.choice(d_T) x_d = tuple(discretize_state(x).astype(int)) u = continualize_action(u_d) x_1, r = model.step(u) x_1_d = tuple(discretize_state(x_1).astype(int)) action_values[x_d][u_d] += alpha * (r + gamma * np.max(action_values[x_1_d]) - action_values[x_d][u_d] ) pi[x_d] = np.argmax(action_values[x_d]) if done: break cumulative_reward_history.append(np.sum(rewards)) env.close() ### END SOLUTION return cumulative_reward_history, pi ###Output _____no_output_____ ###Markdown Use the following cell to compare the learing from experience from 1) to the learning using the defined model: (Beware, nb_steps = 10000 can take some time) ###Code ### train both setups once print("Run with planning from experience") exp_planning_history, exp_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 19, nb_episodes = 30, nb_steps = 10000) print("Run with planning from model") model_planning_history, model_planning_pi = pendulumModelDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 19, nb_episodes = 30, nb_steps = 10000) plt.plot(exp_planning_history) plt.plot(model_planning_history) plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.show() ###Output Run with planning from experience ###Markdown Use the following cell to execute the policy we got using the model: ###Code experiment(model_planning_pi,nb_steps = 300) ###Output _____no_output_____ ###Markdown Extra-task:Change the model parameters (e.g. $g$, $m$, $l$) so that our model differs from the "real world" (we got from gym).What do you observe By changing the parameters our model differs from the "real world". Depending on the amount of difference, the learing curve looks worse than the one with the correct values. The experiment result is also depending on the random starting position. Depending on the parameter difference, the experiment can not be executed successfully any more. Try to change the parameters on your own. The Following learning curve results from a parameter change using $g =20 \, \frac{\text{m}}{\text{s}^2}, m = 5 \, \text{kg and } l = 2 \, \text{m}$: ###Code plt.plot(exp_planning_history, label="exp") plt.plot(model_planning_history, label="model") plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.legend(loc="upper left") plt.show() ###Output _____no_output_____
Slintel_Assignment_2.ipynb
###Markdown - importing the libraries here... ###Code import nltk # nltk.download() import pandas as pd import spacy # from spacy import displacy # from collections import Counter import en_core_web_lg nlp = en_core_web_lg.load() # !python -m spacy download en_core_web_lg master = pd.read_csv("/content/master-company-sheet.csv") blogs = pd.read_csv("/content/news-data.csv") output = pd.read_csv("/content/output-sheet.csv") print("master sheet", master.head()) print("\n\nmaster sheet data types\n", master.dtypes) print("blogs sheet", blogs.head()) print("\n\n blogs sheet data types\n", blogs.dtypes) print("output sheet", output.head()) print("\n\n output sheet data types\n", output.dtypes) def dictionary_with_title_description(df): " This function will return dictionaries containing blog id, company names from title, and company name from description" company_names_title = {} # initialising empty dictionary for company names extracted from title company_names_description = {} # initialising empty dictionary for company names extracted from description descriptionDict = {} # {index : [blog_id, title, description], index_2 : ...} for i in range(0, len(df)): descriptionDict.setdefault(i, []) # The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. descriptionDict[i].append(df.loc[i, "_id"]) # will be adding multiple values in a single key (Here, adding _id) # title descriptionDict.setdefault(i, []) descriptionDict[i].append(df.loc[i, "title"]) # adding title as value in dictionay # description descriptionDict.setdefault(i, []) descriptionDict[i].append(df.loc[i, "description"]) #adding description as value in the dictionary for i in range(0, len(df)): doc = nlp(descriptionDict[i][2]) for X in doc.ents: #print((X.text, X.label_, type(X.text), type(X.label_))) if X.label_ == 'ORG': company_names_description.setdefault(descriptionDict[i][0], []) company_names_description[descriptionDict[i][0]].append(X.text) # company_names_description.update({descriptionDict[i][0]:X.text}) print("company_names FROM description - ",company_names_description) for i in range(0, len(df)): titl = nlp(descriptionDict[i][1]) for X in titl.ents: #print((X.text, X.label_, type(X.text), type(X.label_))) if X.label_ == 'ORG': # company_names_title.update({descriptionDict[i][0]:X.text}) company_names_title.setdefault(descriptionDict[i][0], []) company_names_title[descriptionDict[i][0]].append(X.text) print("company_names FROM title - ",company_names_title) return descriptionDict, company_names_description, company_names_title descriptionDict, company_names_description, company_names_title = dictionary_with_title_description(blogs) final_dictionary = {} try: for key, value in company_names_description.items(): # print("Value at o", value[0]) for j in range(0, len(master)): for k in range(0, len(value)): if (value[k] == master.loc[j, "name"]): final_dictionary.setdefault(key, []) final_dictionary[key].append(master.loc[j, "_id"]) except: print("RA") final_dictionary try: for key, value in company_names_title.items(): # print("Value at o", value[0]) for j in range(0, len(master)): for k in range(0, len(value)): if (value[k] == master.loc[j, "name"]): final_dictionary.setdefault(key, []) final_dictionary[key].append(master.loc[j, "_id"]) except: print("RA") final_dictionary blogs.set_index("_id") for k, v in final_dictionary.items(): new_row = {'blog_id':k, 'title': blogs["title"][k], 'description': blogs["description"][k], 'company_ids': final_dictionary[k]} output = output.append(new_row, ignore_index=True) output output.to_csv("output-sheet_new_lg.csv", index = False) ###Output _____no_output_____
pure/4.sets.ipynb
###Markdown SetSets are used to store multiple items in a single variable.Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.A set is a collection which is unordered, unchangeable*, and unindexed.* Note: Set items are unchangeable, but you can remove items and add new items. ###Code # Sets are written with curly brackets. thisset = {"apple", "banana", "cherry"} print(thisset) ###Output {'apple', 'banana', 'cherry'} ###Markdown Set ItemsSet items are unordered, unchangeable, and do not allow duplicate values. UnorderedUnordered means that the items in a set do not have a defined order.Set items can appear in a different order every time you use them, and cannot be referred to by index or key. UnchangeableSet items are unchangeable, meaning that we cannot change the items after the set has been created.Once a set is created, you cannot change its items, but you can remove items and add new items. Duplicates Not AllowedSets cannot have two items with the same value. ###Code # The set() constructor thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset) thisset = {"apple", "banana", "cherry"} mylist = ["kiwi", "orange"] thisset.update(mylist) print(thisset) # remove item thisset = {"apple", "banana", "cherry"} thisset.remove("banana") print(thisset) # Note: If the item to remove does not exist, discard() will NOT raise an error. thisset = {"apple", "banana", "cherry"} thisset.discard("banana") print(thisset) ###Output {'apple', 'cherry'} {'apple', 'cherry'} ###Markdown Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed. ###Code #Join Two Sets set1 = {"a", "b", "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) #Update set1 = {"a", "b", "c"} set2 = {1, 2, 3} set1.update(set2) print(set1) ###Output {'c', 1, 2, 3, 'b', 'a'} {'c', 1, 2, 3, 'b', 'a'} ###Markdown Note: Both union() and update() will exclude any duplicate items. ###Code # Keep ONLY the Duplicates #The intersection_update() method will keep only the items that are present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(x) #The intersection() method will return a new set, that only contains the items that are present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z) #Keep All, But NOT the Duplicates x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(x) ###Output {'apple'} {'apple'} {'microsoft', 'google', 'banana', 'cherry'}
0.1 dataset and feature.ipynb
###Markdown Once you have the data in place, you can generate a new Dataset instance from the database.txt file。 The following uses database txt file from July 2015 (data_0.6.July_2015.tar). ###Code from neurosynth.base.dataset import Dataset dataset = Dataset('data/database.txt') ###Output _____no_output_____ ###Markdown Once initialized, the Dataset instance contains activation data from nearly 10,000 published neuroimaging articles. But it doesn't yet have any features attached to those data, so let's add some: ###Code dataset.add_features('data/feature_v4-topics-400.txt') ###Output _____no_output_____ ###Markdown Now our Dataset has both activation data and some features we can use to manipulate the data with. In this case, the features are just term-based tags--i.e., words that occur in the abstracts of the articles from which the dataset is drawn (for details, see the Neurosynth website). https://github.com/neurosynth/neurosynth ###Code dataset.save('data/neurosynth_0.6_400_4.pkl') ###Output _____no_output_____
notebooks/3_atlas_extension/HLCA_extension_data_preprocessing/Budinger_2020_Bharat.ipynb
###Markdown This script does the preparation of Budinger_2020/BharatThe original dataset is at `../../../../../../datasets/projects/20210309_Saliba_covidFibrosis_ignacio.ibarra_malte.luecken/bharat_et_al_full.h5ad`It was used for Wendisch et al. Here Malte/Nacho are refining it to be used in the HLCA ###Code import scanpy as sc ad = sc.read_h5ad('bharat_et_al_full.h5ad') ad.shape ad ad.obs_names = list(ad.obs['Unnamed: 0']) # ad.obs # the numbers in ad.X are raw counts ad.raw is None # ad.to_df()['A1BG'].describe() ## check mito content quickly import matplotlib.pyplot as plt ad.obs['% of mito genes'].describe() ad.obs ###Output _____no_output_____ ###Markdown Remove all HEALTHY cells (these are already in the atlas and for that reason readding them is redundant. ###Code ad.obs['orig.ident'].value_counts().shape ad = ad[ad.obs['Sample Status'] != 'Control',:] ad.obs['Sample Status'] = 'COVID-19 plt.hist(ad.obs['% of mito genes'], bins=20) filter_mt = False if filter_mt: mt_thr = 20 print('# before', ad.shape) ad = ad[ad.obs['% of mito genes'] < mt_thr,:] print('# after', ad.shape) plt.hist(ad.obs['% of mito genes'], bins=20) ###Output _____no_output_____ ###Markdown Make object lightweight ###Code del ad.uns del ad.obsm del ad.varm del ad.obsp ###Output _____no_output_____ ###Markdown Clean adata.var ###Code for c in ad.var.columns: del ad.var[c] ###Output _____no_output_____ ###Markdown I don't think this could divided into multiple samples. No clear batch, su assuming everything got sequenced together. ###Code ad.obs[['Sample Source', 'Sample Name', 'Sample Status', 'orig.ident']].value_counts() ad.obs['dataset'] = 'Bundinger2021' ad.obs['study'] = 'Bundinger2021' ad.obs['original_celltype_ann'] = ad.obs['Cell Type'] ad.obs['condition'] = ad.obs['Sample Status'] ad.obs['subject_ID'] = ad.obs['Sample Name'] ad.obs['sample'] = ad.obs['orig.ident'] ad.obs = ad.obs[ad.obs.columns[-6:]] # this is based on the paraphrasing of the manuscript info age_by_subject_ID = {'PMB 1': 53, 'PMB 2': 57, 'Case 1': 27} sex_by_subject_ID = {'PMB 1': 'M', 'PMB 2': 'F', 'Case 1': 'F'} ethn_by_subject_ID = {'PMB 1': None, 'PMB 2': None, 'Case 1': 'Latina'} bmi_by_subject_ID = {'PMB 1': None, 'PMB 2': None, 'Case 1': 25.2} ad.obs['age'] = ad.obs['subject_ID'].map(age_by_subject_ID) ad.obs['sex'] = ad.obs['subject_ID'].map(sex_by_subject_ID) ad.obs['ethnicity'] = ad.obs['subject_ID'].map(ethn_by_subject_ID) ad.obs['bmi'] = ad.obs['subject_ID'].map(bmi_by_subject_ID) ad.obs ad.obs['sample'].value_counts().shape # subset to 2000 HVGs that Lisa uses import pandas as pd gene_set = pd.read_csv('genes_for_mapping.csv') # gene_set = set(gene_set['gene_symbols']) len(set(ad.var.index).intersection(gene_set['gene_symbols'])) import preprocessing as pp ad_sub = pp.subset_and_pad_adata(gene_set, ad) ad.shape, ad_sub.shape ad.obs['subject_ID'].value_counts() ###Output _____no_output_____ ###Markdown Write a full and subsetted version of h5ad ###Code # Clean adata.var full_path = '../../../data/HLCA_extended/extension_datasets/ready/full/bharat.h5ad' ad.write(full_path, compression='lzf') subsetted_path = '../../../data/HLCA_extended/extension_datasets/ready/subsetted/bharat_sub.h5ad' ad_sub.write(subsetted_path, compression='lzf') ad.obs ###Output _____no_output_____ ###Markdown Modify access to be checked ###Code !chmod 777 $full_path !chmod 777 $subsetted_path ###Output _____no_output_____
Neural Networks and Deep Learning/03 Building Deep Neural Network - Step by Step/Building_your_Deep_Neural_Network_Step_by_Step_v8a.ipynb
###Markdown Building your Deep Neural Network: Step by StepWelcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!- In this notebook, you will implement all the functions required to build a deep neural network.- In the next assignment, you will use these functions to build a deep neural network for image classification.**After this assignment you will be able to:**- Use non-linear units like ReLU to improve your model- Build a deeper neural network (with more than 1 hidden layer)- Implement an easy-to-use neural network class**Notation**:- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example.- Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).Let's get started! Updates to Assignment If you were working on a previous version* The current notebook filename is version "4a". * You can find your work in the file directory as version "4".* To see the file directory, click on the Coursera logo at the top left of the notebook. List of Updates* compute_cost unit test now includes tests for Y = 0 as well as Y = 1. This catches a possible bug before students get graded.* linear_backward unit test now has a more complete unit test that catches a possible bug before students get graded. 1 - PackagesLet's first import all the packages that you will need during this assignment. - [numpy](www.numpy.org) is the main package for scientific computing with Python.- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.- dnn_utils provides some necessary functions for this notebook.- testCases provides some test cases to assess the correctness of your functions- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed. ###Code import numpy as np import h5py import matplotlib.pyplot as plt from testCases_v4a import * from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ###Output _____no_output_____ ###Markdown 2 - Outline of the AssignmentTo build your neural network, you will be implementing several "helper functions". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions that will walk you through the necessary steps. Here is an outline of this assignment, you will:- Initialize the parameters for a two-layer network and for an $L$-layer neural network.- Implement the forward propagation module (shown in purple in the figure below). - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$). - We give you the ACTIVATION function (relu/sigmoid). - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function. - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.- Compute the loss.- Implement the backward propagation module (denoted in red in the figure below). - Complete the LINEAR part of a layer's backward propagation step. - We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward) - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function. - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function- Finally update the parameters. **Figure 1****Note** that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps. 3 - InitializationYou will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to $L$ layers. 3.1 - 2-layer Neural Network**Exercise**: Create and initialize the parameters of the 2-layer neural network.**Instructions**:- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. - Use random initialization for the weight matrices. Use `np.random.randn(shape)*0.01` with the correct shape.- Use zero initialization for the biases. Use `np.zeros(shape)`. ###Code # GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: parameters -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ np.random.seed(1) ### START CODE HERE ### (≈ 4 lines of code) W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros((n_y, 1)) ### END CODE HERE ### assert(W1.shape == (n_h, n_x)) assert(b1.shape == (n_h, 1)) assert(W2.shape == (n_y, n_h)) assert(b2.shape == (n_y, 1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters parameters = initialize_parameters(3,2,1) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) ###Output W1 = [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] b1 = [[ 0.] [ 0.]] W2 = [[ 0.01744812 -0.00761207]] b2 = [[ 0.]] ###Markdown **Expected output**: **W1** [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] **b1** [[ 0.] [ 0.]] **W2** [[ 0.01744812 -0.00761207]] **b2** [[ 0.]] 3.2 - L-layer Neural NetworkThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep`, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. Thus for example if the size of our input $X$ is $(12288, 209)$ (with $m=209$ examples) then: **Shape of W** **Shape of b** **Activation** **Shape of Activation** **Layer 1** $(n^{[1]},12288)$ $(n^{[1]},1)$ $Z^{[1]} = W^{[1]} X + b^{[1]} $ $(n^{[1]},209)$ **Layer 2** $(n^{[2]}, n^{[1]})$ $(n^{[2]},1)$ $Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ $(n^{[2]}, 209)$ $\vdots$ $\vdots$ $\vdots$ $\vdots$ $\vdots$ **Layer L-1** $(n^{[L-1]}, n^{[L-2]})$ $(n^{[L-1]}, 1)$ $Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ $(n^{[L-1]}, 209)$ **Layer L** $(n^{[L]}, n^{[L-1]})$ $(n^{[L]}, 1)$ $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$ $(n^{[L]}, 209)$ Remember that when we compute $W X + b$ in python, it carries out broadcasting. For example, if: $$ W = \begin{bmatrix} j & k & l\\ m & n & o \\ p & q & r \end{bmatrix}\;\;\; X = \begin{bmatrix} a & b & c\\ d & e & f \\ g & h & i \end{bmatrix} \;\;\; b =\begin{bmatrix} s \\ t \\ u\end{bmatrix}\tag{2}$$Then $WX + b$ will be:$$ WX + b = \begin{bmatrix} (ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\ (ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\ (pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u\end{bmatrix}\tag{3} $$ **Exercise**: Implement initialization for an L-layer Neural Network. **Instructions**:- The model's structure is *[LINEAR -> RELU] $ \times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.- Use zeros initialization for the biases. Use `np.zeros(shape)`.- We will store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for the "Planar Data classification model" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! - Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).```python if L == 1: parameters["W" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01 parameters["b" + str(L)] = np.zeros((layer_dims[1], 1))``` ###Code # GRADED FUNCTION: initialize_parameters_deep def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1]) bl -- bias vector of shape (layer_dims[l], 1) """ np.random.seed(3) parameters = {} L = len(layer_dims) # number of layers in the network for l in range(1, L): ### START CODE HERE ### (≈ 2 lines of code) parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01 parameters['b' + str(l)] = np.zeros((layer_dims[l], 1)) ### END CODE HERE ### assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1])) assert(parameters['b' + str(l)].shape == (layer_dims[l], 1)) return parameters parameters = initialize_parameters_deep([5,4,3]) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) ###Output W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]] b1 = [[ 0.] [ 0.] [ 0.] [ 0.]] W2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716] [-0.01023785 -0.00712993 0.00625245 -0.00160513] [-0.00768836 -0.00230031 0.00745056 0.01976111]] b2 = [[ 0.] [ 0.] [ 0.]] ###Markdown **Expected output**: **W1** [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]] **b1** [[ 0.] [ 0.] [ 0.] [ 0.]] **W2** [[-0.01185047 -0.0020565 0.01486148 0.00236716] [-0.01023785 -0.00712993 0.00625245 -0.00160513] [-0.00768836 -0.00230031 0.00745056 0.01976111]] **b2** [[ 0.] [ 0.] [ 0.]] 4 - Forward propagation module 4.1 - Linear Forward Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:- LINEAR- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. - [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID (whole model)The linear forward module (vectorized over all the examples) computes the following equations:$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\tag{4}$$where $A^{[0]} = X$. **Exercise**: Build the linear part of forward propagation.**Reminder**:The mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help. ###Code # GRADED FUNCTION: linear_forward def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) Returns: Z -- the input of the activation function, also called pre-activation parameter cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass efficiently """ ### START CODE HERE ### (≈ 1 line of code) Z = np.dot(W, A) + b ### END CODE HERE ### assert(Z.shape == (W.shape[0], A.shape[1])) cache = (A, W, b) return Z, cache A, W, b = linear_forward_test_case() Z, linear_cache = linear_forward(A, W, b) print("Z = " + str(Z)) ###Output Z = [[ 3.26295337 -1.23429987]] ###Markdown **Expected output**: **Z** [[ 3.26295337 -1.23429987]] 4.2 - Linear-Activation ForwardIn this notebook, you will use two activation functions:- **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** items: the activation value "`a`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call: ``` pythonA, activation_cache = sigmoid(Z)```- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the `relu` function. This function returns **two** items: the activation value "`A`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:``` pythonA, activation_cache = relu(Z)``` For more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.**Exercise**: Implement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation "g" can be sigmoid() or relu(). Use linear_forward() and the correct activation function. ###Code # GRADED FUNCTION: linear_activation_forward def linear_activation_forward(A_prev, W, b, activation): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: A -- the output of the activation function, also called the post-activation value cache -- a python tuple containing "linear_cache" and "activation_cache"; stored for computing the backward pass efficiently """ if activation == "sigmoid": # Inputs: "A_prev, W, b". Outputs: "A, activation_cache". ### START CODE HERE ### (≈ 2 lines of code) Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = sigmoid(Z) ### END CODE HERE ### elif activation == "relu": # Inputs: "A_prev, W, b". Outputs: "A, activation_cache". ### START CODE HERE ### (≈ 2 lines of code) Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = relu(Z) ### END CODE HERE ### assert (A.shape == (W.shape[0], A_prev.shape[1])) cache = (linear_cache, activation_cache) return A, cache A_prev, W, b = linear_activation_forward_test_case() A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid") print("With sigmoid: A = " + str(A)) A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu") print("With ReLU: A = " + str(A)) ###Output With sigmoid: A = [[ 0.96890023 0.11013289]] With ReLU: A = [[ 3.43896131 0. ]] ###Markdown **Expected output**: **With sigmoid: A ** [[ 0.96890023 0.11013289]] **With ReLU: A ** [[ 3.43896131 0. ]] **Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers. d) L-Layer Model For even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID. **Figure 2** : *[LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model**Exercise**: Implement the forward propagation of the above model.**Instruction**: In the code below, the variable `AL` will denote $A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\hat{Y}$.) **Tips**:- Use the functions you had previously written - Use a for loop to replicate [LINEAR->RELU] (L-1) times- Don't forget to keep track of the caches in the "caches" list. To add a new value `c` to a `list`, you can use `list.append(c)`. ###Code # GRADED FUNCTION: L_model_forward def L_model_forward(X, parameters): """ Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- last post-activation value caches -- list of caches containing: every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1) """ caches = [] A = X L = len(parameters) // 2 # number of layers in the neural network # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list. for l in range(1, L): A_prev = A ### START CODE HERE ### (≈ 2 lines of code) A, cache = linear_activation_forward(A_prev, parameters["W" + str(l)], parameters["b" + str(l)], activation = "relu") caches.append(cache) ### END CODE HERE ### # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list. ### START CODE HERE ### (≈ 2 lines of code) AL, cache = linear_activation_forward(A, parameters["W" + str(L)], parameters["b" + str(L)], activation = "sigmoid") caches.append(cache) ### END CODE HERE ### assert(AL.shape == (1,X.shape[1])) return AL, caches X, parameters = L_model_forward_test_case_2hidden() AL, caches = L_model_forward(X, parameters) print("AL = " + str(AL)) print("Length of caches list = " + str(len(caches))) ###Output AL = [[ 0.03921668 0.70498921 0.19734387 0.04728177]] Length of caches list = 3 ###Markdown **AL** [[ 0.03921668 0.70498921 0.19734387 0.04728177]] **Length of caches list ** 3 Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$, you can compute the cost of your predictions. 5 - Cost functionNow you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.**Exercise**: Compute the cross-entropy cost $J$, using the following formula: $$-\frac{1}{m} \sum\limits_{i = 1}^{m} (y^{(i)}\log\left(a^{[L] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right)) \tag{7}$$ ###Code # GRADED FUNCTION: compute_cost def compute_cost(AL, Y): """ Implement the cost function defined by equation (7). Arguments: AL -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples) Returns: cost -- cross-entropy cost """ m = Y.shape[1] # Compute loss from aL and y. ### START CODE HERE ### (≈ 1 lines of code) cost = -(1. / m) * np.sum(Y * np.log(AL) + (1. - Y) * np.log(1. - AL)) ### END CODE HERE ### cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17). assert(cost.shape == ()) return cost Y, AL = compute_cost_test_case() print("cost = " + str(compute_cost(AL, Y))) ###Output cost = 0.279776563579 ###Markdown **Expected Output**: **cost** 0.2797765635793422 6 - Backward propagation moduleJust like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. **Reminder**: **Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID* *The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.* <!-- For those of you who are expert in calculus (you don't need to be to do this assignment), the chain rule of calculus can be used to derive the derivative of the loss $\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:$$\frac{d \mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \frac{d\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\frac{{da^{[2]}}}{{dz^{[2]}}}\frac{{dz^{[2]}}}{{da^{[1]}}}\frac{{da^{[1]}}}{{dz^{[1]}}} \tag{8} $$In order to calculate the gradient $dW^{[1]} = \frac{\partial L}{\partial W^{[1]}}$, you use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial W^{[1]}}$. During the backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.Equivalently, in order to calculate the gradient $db^{[1]} = \frac{\partial L}{\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial b^{[1]}}$.This is why we talk about **backpropagation**.!-->Now, similar to forward propagation, you are going to build the backward propagation in three steps:- LINEAR backward- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation- [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model) 6.1 - Linear backwardFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).Suppose you have already calculated the derivative $dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$. **Figure 4** The three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:$$ dW^{[l]} = \frac{\partial \mathcal{J} }{\partial W^{[l]}} = \frac{1}{m} dZ^{[l]} A^{[l-1] T} \tag{8}$$$$ db^{[l]} = \frac{\partial \mathcal{J} }{\partial b^{[l]}} = \frac{1}{m} \sum_{i = 1}^{m} dZ^{[l](i)}\tag{9}$$$$ dA^{[l-1]} = \frac{\partial \mathcal{L} }{\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \tag{10}$$ **Exercise**: Use the 3 formulas above to implement linear_backward(). ###Code # GRADED FUNCTION: linear_backward def linear_backward(dZ, cache): """ Implement the linear portion of backward propagation for a single layer (layer l) Arguments: dZ -- Gradient of the cost with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ A_prev, W, b = cache m = A_prev.shape[1] ### START CODE HERE ### (≈ 3 lines of code) dW = (1. / m) * np.dot(dZ, A_prev.T) db = (1. / m) * np.sum(dZ, axis=1, keepdims=True) dA_prev = np.dot(W.T, dZ) ### END CODE HERE ### assert (dA_prev.shape == A_prev.shape) assert (dW.shape == W.shape) assert (db.shape == b.shape) return dA_prev, dW, db # Set up some test inputs dZ, linear_cache = linear_backward_test_case() dA_prev, dW, db = linear_backward(dZ, linear_cache) print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db)) ###Output dA_prev = [[-1.15171336 0.06718465 -0.3204696 2.09812712] [ 0.60345879 -3.72508701 5.81700741 -3.84326836] [-0.4319552 -1.30987417 1.72354705 0.05070578] [-0.38981415 0.60811244 -1.25938424 1.47191593] [-2.52214926 2.67882552 -0.67947465 1.48119548]] dW = [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716] [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808] [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]] db = [[-0.14713786] [-0.11313155] [-0.13209101]] ###Markdown ** Expected Output**: ```dA_prev = [[-1.15171336 0.06718465 -0.3204696 2.09812712] [ 0.60345879 -3.72508701 5.81700741 -3.84326836] [-0.4319552 -1.30987417 1.72354705 0.05070578] [-0.38981415 0.60811244 -1.25938424 1.47191593] [-2.52214926 2.67882552 -0.67947465 1.48119548]]dW = [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716] [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808] [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]db = [[-0.14713786] [-0.11313155] [-0.13209101]]``` 6.2 - Linear-Activation backwardNext, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. To help you implement `linear_activation_backward`, we provided two backward functions:- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:```pythondZ = sigmoid_backward(dA, activation_cache)```- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:```pythondZ = relu_backward(dA, activation_cache)```If $g(.)$ is the activation function, `sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \tag{11}$$. **Exercise**: Implement the backpropagation for the *LINEAR->ACTIVATION* layer. ###Code # GRADED FUNCTION: linear_activation_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATION layer. Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ linear_cache, activation_cache = cache if activation == "relu": ### START CODE HERE ### (≈ 2 lines of code) dZ = relu_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) ### END CODE HERE ### elif activation == "sigmoid": ### START CODE HERE ### (≈ 2 lines of code) dZ = sigmoid_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) ### END CODE HERE ### return dA_prev, dW, db dAL, linear_activation_cache = linear_activation_backward_test_case() dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "sigmoid") print ("sigmoid:") print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db) + "\n") dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "relu") print ("relu:") print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db)) ###Output sigmoid: dA_prev = [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] dW = [[ 0.10266786 0.09778551 -0.01968084]] db = [[-0.05729622]] relu: dA_prev = [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] dW = [[ 0.44513824 0.37371418 -0.10478989]] db = [[-0.20837892]] ###Markdown **Expected output with sigmoid:** dA_prev [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] dW [[ 0.10266786 0.09778551 -0.01968084]] db [[-0.05729622]] **Expected output with relu:** dA_prev [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] dW [[ 0.44513824 0.37371418 -0.10478989]] db [[-0.20837892]] 6.3 - L-Model Backward Now you will implement the backward function for the whole network. Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. **Figure 5** : Backward pass ** Initializing backpropagation**:To backpropagate through this network, we know that the output is, $A^{[L]} = \sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \frac{\partial \mathcal{L}}{\partial A^{[L]}}$.To do so, use this formula (derived using calculus which you don't need in-depth knowledge of):```pythondAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) derivative of cost with respect to AL```You can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : $$grads["dW" + str(l)] = dW^{[l]}\tag{15} $$For example, for $l=3$ this would store $dW^{[l]}$ in `grads["dW3"]`.**Exercise**: Implement backpropagation for the *[LINEAR->RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model. ###Code # GRADED FUNCTION: L_model_backward def L_model_backward(AL, Y, caches): """ Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) caches -- list of caches containing: every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2) the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1]) Returns: grads -- A dictionary with the gradients grads["dA" + str(l)] = ... grads["dW" + str(l)] = ... grads["db" + str(l)] = ... """ grads = {} L = len(caches) # the number of layers m = AL.shape[1] Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL # Initializing the backpropagation ### START CODE HERE ### (1 line of code) dAL = - (np.divide(Y, AL) - np.divide(1. - Y, 1. - AL)) ### END CODE HERE ### # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"] ### START CODE HERE ### (approx. 2 lines) current_cache = caches[L-1] grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid") ### END CODE HERE ### # Loop from l=L-2 to l=0 for l in reversed(range(L-1)): # lth layer: (RELU -> LINEAR) gradients. # Inputs: "grads["dA" + str(l + 1)], current_cache". Outputs: "grads["dA" + str(l)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)] ### START CODE HERE ### (approx. 5 lines) current_cache = caches[l] dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 1)], current_cache, activation = "relu") grads["dA" + str(l)] = dA_prev_temp grads["dW" + str(l + 1)] = dW_temp grads["db" + str(l + 1)] = db_temp ### END CODE HERE ### return grads AL, Y_assess, caches = L_model_backward_test_case() grads = L_model_backward(AL, Y_assess, caches) print_grads(grads) ###Output dW1 = [[ 0.41010002 0.07807203 0.13798444 0.10502167] [ 0. 0. 0. 0. ] [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] db1 = [[-0.22007063] [ 0. ] [-0.02835349]] dA1 = [[ 0.12913162 -0.44014127] [-0.14175655 0.48317296] [ 0.01663708 -0.05670698]] ###Markdown **Expected Output** dW1 [[ 0.41010002 0.07807203 0.13798444 0.10502167] [ 0. 0. 0. 0. ] [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] db1 [[-0.22007063] [ 0. ] [-0.02835349]] dA1 [[ 0.12913162 -0.44014127] [-0.14175655 0.48317296] [ 0.01663708 -0.05670698]] 6.4 - Update ParametersIn this section you will update the parameters of the model, using gradient descent: $$ W^{[l]} = W^{[l]} - \alpha \text{ } dW^{[l]} \tag{16}$$$$ b^{[l]} = b^{[l]} - \alpha \text{ } db^{[l]} \tag{17}$$where $\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. **Exercise**: Implement `update_parameters()` to update your parameters using gradient descent.**Instructions**:Update parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. ###Code # GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate): """ Update parameters using gradient descent Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Returns: parameters -- python dictionary containing your updated parameters parameters["W" + str(l)] = ... parameters["b" + str(l)] = ... """ L = len(parameters) // 2 # number of layers in the neural network # Update rule for each parameter. Use a for loop. ### START CODE HERE ### (≈ 3 lines of code) for l in range(L): parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)] parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)] ### END CODE HERE ### return parameters parameters, grads = update_parameters_test_case() parameters = update_parameters(parameters, grads, 0.1) print ("W1 = "+ str(parameters["W1"])) print ("b1 = "+ str(parameters["b1"])) print ("W2 = "+ str(parameters["W2"])) print ("b2 = "+ str(parameters["b2"])) ###Output W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008] [-1.76569676 -0.80627147 0.51115557 -1.18258802] [-1.0535704 -0.86128581 0.68284052 2.20374577]] b1 = [[-0.04659241] [-1.28888275] [ 0.53405496]] W2 = [[-0.55569196 0.0354055 1.32964895]] b2 = [[-0.84610769]]
examples/The Partion Function and Boltzmann Statistics.ipynb
###Markdown Computing the Partion Function The schrodinger_X() modules provide eigenstates that can be used directly in an ensemble of your choice (each with there own unique free energy). In this document, we will cover the availible ensemble implimented in QWavE and how to do some simple boltzmann statistics. Canonical Ensemble The canonical ensemble represents the possible states of a mechanicla system in thermal equilibrium with a heat bath at a fixed temperature. The principle thermodynamic variables of the canonical ensemble are the temperature ($T$), number of particles ($N$), and volume of the system ($V$). Making this an $NVT$ system (more on this in another exercise). The partition function within the canonical ensemble is computed as: $$ q(t) = \sum_j \text{exp}(\frac{-e_{j}}{k_{b}T}) $$ where $e_{j}$ are the eigen energies from the Schrodinger equation, and $k_{b}$ is the Boltzmann constant. Once you have evaluated the eigenvalues, you simply need to supply them to the q_PESq() module (using appropriate units). ###Code # Load required modules from QWavE import qwave import numpy as np from scipy import constants import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Lets evaluate the canonical partition function for a two-state system. Lets put the H atom in a 1D box and get the first two eigenstates of the system. ###Code # import some constants hartree_to_ev = constants.physical_constants['Hartree energy in eV'][0] # convert hartree to eV au_to_kg =constants.physical_constants['atomic unit of mass'][0] # convert kg to atomic units kb = constants.physical_constants['Boltzmann constant in eV/K'][0] # Boltzmann constant h = constants.physical_constants['Planck constant in eV s'][0] # planck constant temp = np.linspace(1,500,1000) # Temperature range (cannot evaluate partition function at 0 K) # Temperature step must also be small to ensure derivative is taken appropriately bl = 6 # bohr m = 1.67e-27/au_to_kg # approximate mass of a proton eigen,wave = qwave.schrodinger_box(bl,m,len_eigval=2) #len_eigval forces the number of eigen states to calculate (default = 10) eig = eigen*hartree_to_ev qPESq = qwave.q_PESq(eig,temp,kb) # q_PESq takes three options # Make sure eig and kb are in the same units ###Output _____no_output_____ ###Markdown And as simple as that, you now have the partion function. The partion function itself isn't particularly useful, but it is useful in obtaining some Boltzamnn statistics of your system. Now that we have the partition function for the H atom in a box, let use it to solve for some useful quantities Boltzmann Statistics Probability of occupying a particular state At a given temperature, it is often useful to know the relative occupation of states. The bolt_prob() module evaluates said probabilites for a range of temperatures: $$ p(i,T) = \frac{1}{q(T)} \text{exp}(\frac{-e_{i}}{k_{b}T}) $$ where $P(i,T)$ is the probablity of being in state $i$ at temperature $T$, and $q(T)$ is the partition function. ###Code # Evaluate the probablility of being in the ground state Prob_0 = qwave.bolt_prob(eig,0,qPESq,temp,kb) # where 0 here corresponds to the ground state Prob_1 = qwave.bolt_prob(eig,1,qPESq,temp,kb) # and 1 corresponds to the first excited state plt.plot(temp,Prob_0,color='blue',linewidth=5,label='Groundstate') plt.plot(temp,Prob_1,color='red',linewidth=5,label='First Excited') plt.hlines(0.5,0,500,color='gray',linestyle='dashed') plt.xlabel('Temperature (K)', size=16) plt.ylabel('Probability', size=16) plt.xticks(size=14) plt.yticks(size=14) plt.xlim(0,500) plt.legend(fontsize=14) plt.show() ###Output _____no_output_____ ###Markdown As you can see, the ground state is populated at low temperatures and the excited states are empty.As the temperature increases the probability of occupying excited states increases.As T $\rightarrow \infty$, the probabitly of being in any state approaches $\sum_{i=0}^{2} e_{i}/2 $ ###Code # We can also check to make sure the probability of finding the particle at any state is equal to 1 Tot_Prob = [] for j in range(0,len(temp)): Prob = [] for i in range(0,len(eig)): Prob.append(qwave.bolt_prob(eig,i,qPESq,temp,kb)[0]) Tot_Prob.append(np.sum(Prob)) plt.plot(temp,Tot_Prob,color='black',linewidth=5,label='Total Probability') plt.xlabel('Temperature (K)', size=16) plt.ylabel('Probability', size=16) plt.xticks(size=14) plt.yticks(size=14) plt.title('Total Probability over all States',size=18) plt.show() ###Output _____no_output_____ ###Markdown Average Energy and Variance Another useful quantity is the average energy and variance. The average energy (or ensemble average) within the canonical ensemble is defined as: $$ = \sum_{j} e_{j}p_{j} = \frac{\sum_{j} e_{j} \text{exp}(-e_{j}/k_{b}T)}{\sum_{j} \text{exp}(-e_{j}/k_{b}T)} $$ or by differentiation: $$ = -\frac{\partial \text{ln}(q(T))}{\partial \beta} $$ (which is how QWavE evaluates the average energy) where $\beta$ is $1/k_{b}T$. The variance in the energy can also be defined as: $$ - ^2 = k_{b}T^{2}\frac{\partial E}{\partial T}$$ Which is equivalent to the constant volume heat capacity ($C_{v}$) without the leading constants ###Code avgE, var, cv = qwave.avg_energy(qPESq,temp,kb) plt.plot(temp,avgE/sum(eig),linewidth=5,color='blue') plt.hlines(0.5,0,500,color='gray',linestyle='dashed') plt.ylabel(r'Average Energy ($<E>$/$\sum e$)',size=14) plt.xlabel(r'Temperature (K)',size=14) plt.xticks(size=14) plt.yticks(size=14) plt.show() plt.plot(temp,cv/sum(eig),linewidth=5,color='red') plt.ylabel(r'Heat Capacity ($C_{v}$/$\sum e$)',size=14) plt.xlabel(r'Temperature (K)',size=14) plt.xticks(size=14) plt.yticks(size=14) plt.show() ###Output _____no_output_____ ###Markdown These results are in excellent agreement with analytical solutions for the two-state model (http://www.physics.rutgers.edu/~gersh/351/Lecture%2021.pdf slide 10) Predefined Partion Functions For ease of use, we have also incorporated other commonly used partition functions dervied from the canonical partition function. These include the: harmonic oscillator, hindered translator, rigid rotor, and others. We will show example of using these other functions in another jupyter notebook. In this example, we will harmonic oscillator partition function to find the average energy and heat capacity of an einstein crystal. The harmonic oscillator partition function is defined as: $$ q_{HO}(T) = \frac{\exp{(\frac{\nu}{2 k_{b}T})}}{1-\exp{(\frac{\nu}{k_{b}T})}}$$ where $\nu$ is a frequency (cm$^{-1}$) ###Code bl = 2 # bohr m = 4.65e-26/au_to_kg # approximate mass of a CO molecule nu = 2143 #cm-1 temp = np.linspace(2.5,5000,10000) eigen,wave = qwave.schrodinger_HO(bl,m,nu) #len_eigval forces the number of eigen states to calculate (default = 10) eig = eigen*hartree_to_ev qPESq = qwave.q_PESq(eig,temp,kb) # q_PESq takes three options # Make sure eig and kb are in the same units qHO = qwave.q_HO(nu,temp,kb,h) # q_HO takes an additional parameter which is plancks constant in which ever units are appropriate x = np.linspace(0,1.8) y = x plt.plot(x,y,linestyle='dashed',color='gray') plt.plot(qPESq,qHO,marker='o',markerfacecolor='None',markeredgecolor='red') plt.xticks(size=14) plt.yticks(size=14) plt.xlabel('q_PESq partition function',size=14) plt.ylabel('q_HO partition function',size=14) plt.show() ###Output _____no_output_____ ###Markdown As you can see, both modules give the same result. NOTE: in order to achieve perfect parity, the box length needs to be adjusted to "match" with the curvature of the potential, change the box length from 2 to 10 to see what happens. As such, it is highly recommended to use the q_HO (or other analytic expressions) when you know the shape of the potential. Now, lets run through the same exercise to get the average energy and Cv of the einstein crystal ###Code avgE, var, cv = qwave.avg_energy(qHO,temp,kb) plt.plot(temp,avgE/sum(eig),linewidth=5,color='blue') # plt.hlines(0.5,0,500,color='gray',linestyle='dashed') plt.ylabel(r'Average Energy ($<E>$/$\sum e$)',size=14) plt.xlabel(r'Temperature (K)',size=14) plt.xticks(size=14) plt.yticks(size=14) plt.show() plt.plot(temp,cv/sum(eig),linewidth=5,color='red') plt.ylabel(r'Heat Capacity ($C_{v}$/$\sum e$)',size=14) plt.xlabel(r'Temperature (K)',size=14) plt.xticks(size=14) plt.yticks(size=14) plt.show() ###Output _____no_output_____
notebooks/4-Evaluation/1-DB-Evaluation-TSVD.ipynb
###Markdown Assign to each developer a label of its cluster ###Code kmeans = cluster.KMeans(n_clusters=5, init=centers, n_init=1, max_iter=1).fit(dev2) kmeans.cluster_centers = np.array(centers) clusters = kmeans.predict(dev2) dev['cluster'] = clusters dev.head() ###Output _____no_output_____ ###Markdown Within cluster variance ###Code def WCV(dev, centers): WCV = np.zeros(5) for i in range(5): # clusters X = dev[dev.cluster==i].iloc[:,1:-1] c = [np.array(centers)[i]] d = distance.cdist(X, c) WCV[i] = d.sum()/d.shape[0] return [WCV, WCV.sum()] cluster, total = WCV(dev, centers) print(cluster) print(total) ###Output [ 107036.88884768 3897443.04091219 23130150.52049431 27642915.56625457 64784179.54550792] 119561725.56201667 ###Markdown Between cluster variance ###Code def BCV(dev, centers): BCV = np.zeros(5) x = [np.array(dev.iloc[:,1:-1].mean())] for i in range(5): n = dev[dev.cluster==i].shape[0] c = [np.array(centers)[i]] d = distance.cdist(c, x) BCV[i] = n*d.sum() return [BCV, BCV.sum()] cluster, total = BCV(dev, centers) print(cluster) print(total) ###Output [3.02542518e+10 1.60925046e+09 1.45831849e+10 2.17787469e+09 1.00199655e+10] 58644527338.20222 ###Markdown **Davies–Bouldin index:** ###Code def DB(dev, centers): wcv, _ = WCV(dev, centers) # mean distance of all elements in cluster to centroid DBC = np.zeros((5,5)) # distance between centroids DavisBouldin = 0 for i in range(5): # clusters max = 0 for j in range(5): ci = [np.array(centers)[i]] cj = [np.array(centers)[j]] d = distance.cdist(ci, cj) DBC[i,j] = d.sum() if i != j: val = (wcv[i]+wcv[j])/DBC[i,j] if val > max: max = val DavisBouldin += max return DavisBouldin/5 DavisBouldinIndex = DB(dev, centers) DavisBouldinIndex ###Output _____no_output_____ ###Markdown **Types of issues**: ###Code centers[["codeBlockerViolations", "codeInfoViolations", "codeMajorViolations", "codeBugs", "codeViolations", "codeVulnerabilities", "codeCodeSmells", "codeCriticalViolations", "codeMinorViolations", "inducedSZZIssues", "inducedSonarIssues", ]] ###Output _____no_output_____ ###Markdown **3 clusters:** ###Code from sklearn import cluster, decomposition, preprocessing, feature_selection import pandas as pd import numpy as np from scipy.spatial import distance centers3 = pd.read_csv('../../data/interim/Modelling/3clusterProfilesTSVD.csv').iloc[:,1:] centers3 centers3["refactoringExtractMethod"] ###Output _____no_output_____
docs/alignment-accuracy-mq-plots.ipynb
###Markdown Alignment report========= ###Code # From SO: https://stackoverflow.com/a/28073228/2512851 from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to show/hide raw code."></form>''') import json import matplotlib.pyplot as plt import bokeh import pandas as pd import numpy as np from bokeh.plotting import figure, show from bokeh.io import output_notebook, gridplot from bokeh.models import ColumnDataSource, HoverTool output_notebook() %matplotlib inline d = json.load(open('inputs.json')) fname = d['csvA'] df = pd.DataFrame.from_csv(fname, index_col=None, sep=',') ###Output _____no_output_____ ###Markdown Read distribution by MQ============ ###Code def aa_mq(df): correct_0 = df[df['derr']=='d = 0'][['MQ', 'count']].groupby('MQ').sum() correct_0.columns = ['correct_0'] correct_50 = df[(df['derr']=='0 < d <= 50') | (df['derr']=='d = 0')][['MQ', 'count']].groupby('MQ').sum() correct_50.columns = ['correct_50'] total = df[['MQ', 'count']].groupby('MQ').sum() total.columns = ['total'] data = pd.concat((correct_0, correct_50, total), axis=1) data['perr_0'] = 1 - data['correct_0'] / data['total'] data['perr_50'] = 1 - data['correct_50'] / data['total'] data['perr_ideal'] = 10 ** (-data.index / 10) return data def plot_aa_mq(data): max_y = 10 ** np.ceil(np.log10(data['perr_0'].max())) min_y = 10 ** np.floor(np.log10(data['perr_50'].min())) source = ColumnDataSource(data) hover = HoverTool(tooltips=[ ('perr 0', '@perr_0'), ('perr 50', '@perr_50'), ('perr ideal', '@perr_ideal'), ('Reads', '@total') ]) p = figure(plot_height=200, plot_width=500, x_axis_label='MQ', y_axis_label='p_err', tools=[hover, 'reset'], y_axis_type="log", y_range=[min_y, max_y]) h1 = p.circle(x='MQ', y='perr_0', size=2, source=source) h1 = p.circle(x='MQ', y='perr_0', size=10, alpha=0.5, color='yellow', source=source) h3 = p.line(x='MQ', y='perr_ideal', source=source) return p def plot_read_hist(data): max_y = 10 ** np.ceil(np.log10(data['total'].max())) min_y = 10 ** np.floor(np.log10(data['total'].min())) source = ColumnDataSource(data) hover = HoverTool(tooltips=[ ('Reads', '@total') ]) p = figure(plot_height=200, plot_width=500, x_axis_label='MQ', y_axis_label='Reads', tools=[hover, 'reset'], y_axis_type="log", y_range=[min_y, max_y]) h1 = p.vbar(x='MQ', bottom=min_y, top='total', width=0.7, source=source) return p data = aa_mq(df) s = [ [plot_aa_mq(data)], [plot_read_hist(data)] ] p = gridplot(s) show(p) # read_count_mq = df.groupby('MQ').sum() # max_y = 10 ** np.ceil(np.log10(read_count_mq['count'].max())) # min_y = 10 ** np.floor(np.log10(read_count_mq['count'].min())) # source = ColumnDataSource(read_count_mq) # tools = ["reset"] # p = figure(plot_height=200, plot_width=500, # x_axis_label='MQ', # y_axis_label='Reads', # tools=tools, # y_axis_type="log", y_range=[min_y, max_y]) # h1 = p.vbar(x='MQ', bottom=min_y, top='count', width=0.7, source=source) # p.add_tools(HoverTool(renderers=[h1], tooltips=[("reads", "@count")])) # show(p) ###Output _____no_output_____ ###Markdown Read distribution by alignment fate=================== ###Code read_count_by_fate = df.groupby('derr').sum() read_count_by_fate['y'] = read_count_by_fate.index max_x = 10 ** np.ceil(np.log10(read_count_by_fate['count'].max())) min_x = 10 ** np.floor(np.log10(read_count_by_fate['count'].min())) source = ColumnDataSource(read_count_by_fate) tools = ["reset"] p = figure(plot_height=200, plot_width=500, x_axis_label='Reads', y_axis_label='Read fate', tools=tools, y_range=read_count_by_fate.index.tolist(), x_axis_type="log", x_range=[min_x, max_x]) h1 = p.hbar(y='y', left=min_x, right='count', height=0.7, source=source) p.add_tools(HoverTool(renderers=[h1], tooltips=[("reads", "@count")])) show(p) ###Output _____no_output_____ ###Markdown Mapped rate and Alignment accuracy parametrized by MQ============================= ###Code # Matplotlib version of the plots def heng_li_plot(df, category, ax): sub_df = df[df['category']==category] #correct = sub_df[(sub_df['derr']=='0 < d <= 50') | (sub_df['derr']=='d = 0')][['MQ', 'count']].groupby('MQ').sum() correct = sub_df[sub_df['derr']=='d = 0'][['MQ', 'count']].groupby('MQ').sum() correct.columns = ['correct'] mapped = sub_df[sub_df['derr']!='unmapped'][['MQ', 'count']].groupby('MQ').sum() mapped.columns = ['mapped'] total = sub_df[['MQ', 'count']].groupby('MQ').sum() total.columns = ['total'] data = pd.concat((correct, mapped, total), axis=1) x = np.zeros(61, dtype=float) y = np.zeros(61, dtype=float) for mq in range(61): data_sub = data.iloc[mq:70] x[mq] = 100 * data_sub['mapped'].sum() / total.sum() y[mq] = 100 * data_sub['correct'].sum() / data_sub['mapped'].sum() ax.plot(x, y) ax.plot(x[0], y[0], 'ko') plt.setp(ax, xlim=(95, 101), xticks=range(96,101), ylim=(79, 101), yticks=range(80,101, 5), title=category) def plot_heng_li_panels(df): fig = plt.figure(figsize=(10, 20)) for n, cat in enumerate(['Ref', 'SNP', 'Multi', 'INS <= 10', 'INS 11-50', 'INS > 50', 'DEL <= 10', 'DEL 11-50', 'DEL > 50']): ax = plt.subplot(4, 3, n + 1) heng_li_plot(df, cat, ax) #plt.setp(ax, yscale='log') if n != 6: plt.setp(ax, xticklabels=[], yticklabels=[]) else: plt.setp(ax, xlabel='% Mapped', ylabel='% Correct') #plot_heng_li_panels(df) def heng_li_plot(df, category): sub_df = df[df['category']==category] #correct = sub_df[(sub_df['derr']=='0 < d <= 50') | (sub_df['derr']=='d = 0')][['MQ', 'count']].groupby('MQ').sum() correct = sub_df[sub_df['derr']=='d = 0'][['MQ', 'count']].groupby('MQ').sum() correct.columns = ['correct'] mapped = sub_df[sub_df['derr']!='unmapped'][['MQ', 'count']].groupby('MQ').sum() mapped.columns = ['mapped'] total = sub_df[['MQ', 'count']].groupby('MQ').sum() total.columns = ['total'] data = pd.concat((correct, mapped, total), axis=1) x = np.zeros(61, dtype=float) y = np.zeros(61, dtype=float) for mq in range(61): data_sub = data.iloc[mq:70] x[mq] = 100 * data_sub['mapped'].sum() / total.sum() y[mq] = 100 * data_sub['correct'].sum() / data_sub['mapped'].sum() source = ColumnDataSource(data=dict( mapped=x, correct=y, mq=range(61) )) hover = HoverTool(tooltips=[ ('MQ', '≥ @mq'), ('Map', '@mapped %'), ('Correct', '@correct %') ]) s1 = figure(width=250, plot_height=250, tools=[hover, 'pan', 'reset'], title=category) s1.circle(x[0], y[0], size=10) s1.line('mapped', 'correct', source=source) return s1 def plot_heng_li_panels(df): s = [] row_cnt = 3 row_s = [] for n, cat in enumerate(['Ref', 'SNP', 'Multi', 'INS <= 10', 'INS 11-50', 'INS > 50', 'DEL <= 10', 'DEL 11-50', 'DEL > 50']): if n % row_cnt == 0: if len(row_s): s.append(row_s) row_s = [] row_s.append(heng_li_plot(df, cat)) if len(row_s): s.append(row_s) p = gridplot(s) show(p) plot_heng_li_panels(df) ###Output _____no_output_____
uhecr_model/checks/random_seed/precomputation.ipynb
###Markdown Precomputing values for use in fits of Stan modelsBecause of the way Stan works, it is necessary to compute some values in advance which can then be passed into the fit an interpolated over. The precomputed values will be different for different sets of source distances, and therefore different catalogues. Here we show how to compute the values for the SBG catalogue, but it is exactly the same for all cases, just changing the input label.For ease, all the precomputed table files used are provided for use in this repository. ###Code import os import h5py from fancy import Data, Model, Analysis import numpy as np detector_type = "TA2015" '''set detector and detector properties''' if detector_type == "TA2015": from fancy.detector.TA2015 import detector_properties, Eth elif detector_type == "auger2014": from fancy.detector.auger2014 import detector_properties, Eth else: raise Exception("Undefined detector type!") # Define file containing catalogue information source_file = '../../data/sourcedata.h5' # Path to Stan files stan_path = '../../stan/' # make output directory if it doesnt exist if not os.path.isdir("output"): os.mkdir("output") # source_types = ["SBG_23", "2FHL_250Mpc"] source_types = ["SBG_23"] # exposure factor exp_factors = [1., 5.] # exp_factors = [1.] # store original total exposure and area to restore per iteration alpha_T_0 = detector_properties["alpha_T"] A_0 = detector_properties["A"] for source_type in source_types: for exp_factor in exp_factors: print("Current Source: {0}".format(source_type)) print("Current Exposure Factor: {0}".format(exp_factor)) # File in which to store precomputation # create new files with TA label table_file = "output/tables_{0}_{2}_epsx{1:.0f}.h5".format(source_type, exp_factor, detector_type) # modify exposure factor detector_properties["alpha_T"] *= exp_factor detector_properties["A"] *= exp_factor # check if we have the correct values for detector_properties if not np.allclose(detector_properties["alpha_T"] / exp_factor, alpha_T_0): raise Exception("Fix exposure factor for detector property!") if not np.allclose(detector_properties["A"] / exp_factor, A_0): raise Exception("Fix exposure factor for detector property!") data = Data() data.add_source(source_file, source_type) data.add_detector(detector_properties) # KW: add detector information model_name = 'joint_model.stan' model = Model(model_filename = model_name, include_paths = stan_path) model.input(Eth = Eth) # EeV summary = b'Precomputation of Exposure Integral and Energy' analysis = Analysis(data, model, analysis_type = 'joint', filename = table_file, summary = summary) analysis.build_tables(fit_only = True) analysis.tables.save(table_file) analysis.build_energy_table(table_file = table_file) # reset exposure factor to original detector_properties["alpha_T"] = alpha_T_0 detector_properties["A"] = A_0 ###Output Current Source: SBG_23 Current Exposure Factor: 1.0
00-1-age-and-year-of-deathofharold-shipmans-victims/00-1-shipman-confirmed-victims-x.ipynb
###Markdown Art of Statistics: 0-1 Age and Year of Shipman Victims for customizing the graph see: https://altair-viz.github.io/user_guide/customization.html ###Code import altair as alt import pandas as pd df = pd.read_csv("00-1-shipman-confirmed-victims-x.csv") df.head() ###Output _____no_output_____ ###Markdown Scatter plot ###Code x_scale = min(df["fractionalDeathYear"]) , max(df["fractionalDeathYear"]) y_scale = min(df["Age"]) , max(df["Age"]) gender_domain = ['Men', 'Women'] gender_range = ['blue', 'red'] scatter = alt.Chart(df).mark_circle().encode( alt.X('fractionalDeathYear', scale=alt.Scale(domain=x_scale), axis=alt.Axis(format='d'), title="Year"), alt.Y('Age', scale=alt.Scale(domain=(y_scale)), title="Age of victim"), color= alt.Color('gender2', scale=alt.Scale(domain=gender_domain, range=gender_range), title="") ) scatter ###Output _____no_output_____ ###Markdown Age histogram ###Code age_histogram = alt.Chart(df).mark_bar(color='grey').encode( alt.X('count()', axis=None, title=""), alt.Y("Age", bin=alt.Bin(maxbins=50), axis=None, title=""), ).properties(width=60) age_histogram ###Output _____no_output_____ ###Markdown Year histogram ###Code year_histogram = alt.Chart(df).mark_bar(color='grey').encode( alt.X('fractionalDeathYear', scale=alt.Scale(domain=x_scale), bin=alt.Bin(maxbins=50), axis=None, title=""), alt.Y('count()', axis=None, title=""), ).properties(height=60) year_histogram ###Output _____no_output_____ ###Markdown Final chart ###Code final_chart = (year_histogram & (scatter | age_histogram)).configure_concat( spacing=0 ) final_chart = final_chart.configure_axis( grid=False ).configure_view( strokeOpacity=0 ) final_chart ###Output _____no_output_____
pypinm-master/vprasanja za razmislek/Vaja 1 - polovica.ipynb
###Markdown Feb 2015, J. Slavič in L.Knez Vprašanje 1, 2, 3: Rešite sami doma. Vprašanje 4: Prikažite uporabo stilov, poudarjenega, poševnega teksta, seznamov, enačbe... Naslov 1 Naslov 2... Uporaba HTMLja za urejanje stilov v Pythonu Na hitro samo, naj si pogledajo sami. Opomba: html uporabljamo samo, če ne uspemo narediti v *markdown* načina; naslove npr zelo enostavno definiramo z \.Centriran naslovNavadno besediloNaslov 1 Naslov 2 Naslov 3Naslov 4 Naslov 5 Naslov 6 *posevno***poudarjeno**Primer seznamov:* glavni seznam - podseznam - podpodseznam* spet glavni seznamEnačba:$b(t)=\frac{r}{1-r^4}\,\sqrt{3}+c$Tabela:| Tabele | So | Zakon||--------------|:------------------:|------:|| Stolp 1 je | levo poravnan | 1600 || Stolp 2 je | sredinsko poravnan | 12 || Stolp 3 je | desno poravnan | 1 |*Napredno lahko tabele naredimo tudi z html kodo.*Slika (dve piki označujeta *parent* mapo):Primer povezave na [markdown stran](http://daringfireball.net/projects/markdown/) Vprašanje 5: Definirajte razliko med statičnim in dinamičnim definiranjem spremenljivk.* Statična spremenljivka je hkrati vezana in tip in na objekt (a = 9 in a = 'hiša' bi javilo napako). * Dinamična spremenljivka je vezana le na objekt, tip lahko poljubno spreminjamo. Spodnji primer lepo deluje, ker so v Pythonu dinamične spremenljivke. ###Code a = 9 a a = 'hiša' a ###Output _____no_output_____ ###Markdown Vprašanje 6: Poiščite pomoč poljubega ukaza (znotraj Pythona in na uradni domači strani). ###Code help(range) ###Output Help on class range in module builtins: class range(object) | range(stop) -> range object | range(start, stop[, step]) -> range object | | Return a virtual sequence of numbers from start to stop by step. | | Methods defined here: | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __reduce__(...) | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | Return a reverse iterator. | | count(...) | rangeobject.count(value) -> integer -- return number of occurrences of value | | index(...) | rangeobject.index(value, [start, [stop]]) -> integer -- return index of value. | Raise ValueError if the value is not present. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | start | | step | | stop ###Markdown Pythonova domača stran: https://docs.python.org/3/library/stdtypes.html?highlight=rangerange Vprašanje 7: Prikažite uporabo *niza*, *celega števila* in *števila z uporabo plavajoče vejice*.* Nizi. ###Code besedilo_1 = 'Tole je primer besedila.' besedilo_2 = "Tudi tole je primer besedila." besedilo = besedilo_1 + besedilo_2 besedilo ###Output _____no_output_____ ###Markdown * Cela števila in float števila ###Code a = 7 b = 1.7 a # Celo število type(a) b # Float število type(b) ###Output _____no_output_____ ###Markdown Vprašanje 8: Prikažite uporabo *terke* in njenih bistvenih lastnosti. ###Code terka_1 = (1, 3, 8) # Tipičen primer terke terka_2 =('Študenti', 4, 7.3) # Terka z različnimi tipi spremenljivk # Štetje se v Pythonu prične z 0... gre do len(terka_2) dolzina = len(terka_2) dolzina terka_2[0] terka_2[2] # Terkam ne moremo predpisovati nove vrednosti, so immutable terka_1[1]=9 ###Output _____no_output_____ ###Markdown Vprašanje 9: Prikažite uporabo *seznama* in njegovih bistvenih lastnosti. ###Code seznam_1 = [1, 8, 10] # Navaden seznam seznam_2 = [3, 11, 'list'] # Seznam z mešanimi tipi seznam_2 + seznam_1 # Sezname lahko spreminjamo seznam_2[1]=13 seznam_2 ###Output _____no_output_____ ###Markdown Vprašanje 10: Tipične operacije nad seznami.Več o operacijah najdete tu: https://docs.python.org/3.4/tutorial/datastructures.htmlmore-on-lists ###Code seznam_3 = seznam_2.copy() # Kopiramo seznam seznam_3.append(18) # Spremenimo le nov seznam seznam_3 seznam_2 # Preverimo, če smo spremenili tudi star seznam seznam_2.index('list') # Poglejmo na katerem mestu v seznamu se nahaja beseda 'list' # Se primer uporabe stevnika seznam_4 = [1, 2, 1, 3, 1, 4, 2, 2, 1] # Kolikokrat se število 1 pojavi v seznam_4 seznam_4.count(1) # Kolikokrat se število 2 pojavi v seznam_4 seznam_4.count(2) # Seznam lahko preuredimo tudi v obratni vrstni red seznam_4.reverse() seznam_4 # Lahko jih tudi uredimo seznam_4.sort() seznam_4 # In seznam seznamov je v resnici matrika seznam_5 = [3, 7, 7] matrika = [seznam_5, [1, 1, 1], [3, 6, 9]] matrika ###Output _____no_output_____
Lesson01/Exercise11.ipynb
###Markdown Tweaking plot parameters of a grouped bar plot ###Code #Import seaborn import seaborn as sns diamonds_df = sns.load_dataset('diamonds') ax = sns.barplot(x="cut", y="price", hue='color', data=diamonds_df) #Modifying legends ax = sns.barplot(x='cut', y='price', hue='color', data=diamonds_df) ax.legend(loc='upper right',ncol=4) #Modifying x and y-axis tick labels ax = sns.barplot(x='cut', y='price', hue='color', data=diamonds_df) ax.legend(loc='upper right', ncol=4) ax.set_xlabel('Cut', fontdict={'fontsize' : 15}) ax.set_ylabel('Price', fontdict={'fontsize' : 15}) #Modifying the font-size and rotation of x-axis ax = sns.barplot(x='cut', y='price', hue='color', data=diamonds_df) ax.legend(loc='upper right',ncol=4) # set fontsize and rotation of x-axis tick labels ax.set_xticklabels(ax.get_xticklabels(), fontsize=13, rotation=30) ###Output _____no_output_____
Finding Successful Projects/successful-project-hackerearth.ipynb
###Markdown Funding Successful Projects - Hackerearth ContestLink: [Funding Sucessful Projects](https://www.hackerearth.com/challenge/competitive/machine-learning-challenge-2/machine-learning/funding-successful-projects/)**Author: Sethu Iyer ** ###Code import pandas as pd import numpy as np import datetime from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction.text import CountVectorizer import xgboost as xgb pd.set_option('display.max_colwidth',100) train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') ###Output _____no_output_____ ###Markdown *Creating Features from datetime* ###Code #First, convert the timestamp to datetime object unix_cols = ['deadline','state_changed_at','launched_at','created_at'] for cols in unix_cols: train[cols] = train[cols].apply(lambda timestamp: datetime.datetime.fromtimestamp(int(timestamp))) test[cols] = test[cols].apply(lambda timestamp: datetime.datetime.fromtimestamp(int(timestamp))) #time difference between 1) launched_at and created_at 2) deadline and launched_at train['launch_create'] = train.apply(lambda row: np.log((row['launched_at'] - row['created_at']).total_seconds()),axis=1) test['launch_create'] = test.apply(lambda row: np.log((row['launched_at'] - row['created_at']).total_seconds()),axis=1) train['deadline_launch'] = train.apply(lambda row: np.log((row['deadline'] - row['launched_at']).total_seconds()),axis=1) test['deadline_launch'] = test.apply(lambda row: np.log((row['deadline'] - row['launched_at']).total_seconds()),axis=1) ###Output _____no_output_____ ###Markdown *Now, normalizing the currency* ###Code total_currency = train['currency'].append(test['currency']) print((pd.unique(total_currency))) conversion_factor={ 'USD': 1.00, 'GBP': 1.28, 'CAD' : 0.75, 'AUD': 0.76, 'NZD': 0.73, 'EUR': 1.12, 'SEK':0.11, 'NOK':0.12, 'DKK':0.15, 'CHF':1.03, 'HKD':0.13, 'SGD': 0.72, 'MXN':0.056} train['goal'] = train.apply(lambda row : row['goal'] * conversion_factor[row['currency']],axis=1) test['goal'] = test.apply((lambda row : row['goal'] * conversion_factor[row['currency']]),axis=1) ###Output _____no_output_____ ###Markdown *Now, Creating some text features* ###Code train['name_count'] = train['name'].str.split().str.len() train['desc_count'] = train['desc'].str.split().str.len() test['name_count'] = test['name'].str.split().str.len() test['desc_count'] = test['desc'].str.split().str.len() train['keywords_len'] = train['keywords'].str.len() train['keywords_count'] = train['keywords'].str.split('-').str.len() test['keywords_len'] = test['keywords'].str.len() test['keywords_count'] = test['keywords'].str.split('-').str.len() ###Output _____no_output_____ ###Markdown *Creating more complex text feature* ###Code import re def desc_clean(word): p1 = re.sub(pattern='(\W+)|(\d+)|(\s+)',repl=' ',string=word) p1 = p1.lower() return p1 kickdesc = pd.Series(train['desc'].tolist() + test['desc'].tolist()).astype(str) kickdesc=kickdesc.map(desc_clean) stop = set(stopwords.words('english')) kickdesc = [[x for x in x.split() if x not in stop] for x in kickdesc] stemmer = SnowballStemmer(language='english') kickdesc = [[stemmer.stem(x) for x in x] for x in kickdesc] kickdesc = [[x for x in x if len(x) > 2] for x in kickdesc] kickdesc = [' '.join(x) for x in kickdesc] cv = CountVectorizer(max_features=300) combine=pd.DataFrame(cv.fit_transform(kickdesc).todense()) combine.rename(columns= lambda x: 'variable_'+ str(x), inplace=True) train_text = combine[:train.shape[0]] test_text = combine[train.shape[0]:] test_text.reset_index(drop=True,inplace=True) ###Output _____no_output_____ ###Markdown *Creating some more text features* ###Code len_feats = ['name_len','desc_len'] cols_to_use=['name','desc'] for i in np.arange(2): train[len_feats[i]] = train[cols_to_use[i]].apply(str).apply(len) test[len_feats[i]] = test[cols_to_use[i]].apply(str).apply(len) ###Output _____no_output_____ ###Markdown *Finalize the training and testing data before training* ###Code cols_to_use = ['name_len','desc_len','keywords_len','name_count','desc_count','keywords_count','goal','launch_create','deadline_launch'] target = train['final_status'] train = train[cols_to_use] test = test[cols_to_use] X_train = pd.concat([train, train_text],axis=1) X_test = pd.concat([test, test_text],axis=1) ###Output _____no_output_____ ###Markdown *It's training time! * ###Code dtrain = xgb.DMatrix(data=X_train, label = target) dtest = xgb.DMatrix(data=X_test) params = { 'objective':'binary:logistic', 'eval_metric':'error', 'eta':0.025, 'max_depth':6, 'subsample':0.7, 'colsample_bytree':0.7, 'min_child_weight':5 } bst = xgb.cv(params, dtrain, num_boost_round=1000, early_stopping_rounds=40,nfold=5,verbose_eval=10) bst_train = xgb.train(params, dtrain, num_boost_round=900) p_test = bst_train.predict(dtest) sub = pd.DataFrame() test = pd.read_csv('test.csv') sub['project_id'] = test['project_id'] sub['final_status'] = p_test sub['final_status'] = [1 if x > 0.5 else 0 for x in sub['final_status']] sub.to_csv("xgb_with_python_feats.csv",index=False) #70.60 ###Output _____no_output_____
c5_seq_models/w2_Emojify.ipynb
###Markdown Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. So rather than writing:>"Congratulations on the promotion! Let's get coffee and talk. Love you!" The emojifier can automatically turn this into:>"Congratulations on the promotion! 👍 Let's get coffee and talk. ☕️ Love you! ❤️"* You will implement a model which inputs a sentence (such as "Let's go see the baseball game tonight!") and finds the most appropriate emoji to be used with this sentence (⚾️). Using word vectors to improve emoji lookups* In many emoji interfaces, you need to remember that ❤️ is the "heart" symbol rather than the "love" symbol. * In other words, you'll have to remember to type "heart" to find the desired emoji, and typing "love" won't bring up that symbol.* We can make a more flexible emoji interface by using word vectors!* When using word vectors, you'll see that even if your training set explicitly relates only a few words to a particular emoji, your algorithm will be able to generalize and associate additional words in the test set to the same emoji. * This works even if those additional words don't even appear in the training set. * This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set. What you'll build1. In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings.2. Then you will build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM. Updates If you were working on the notebook before this update...* The current notebook is version "2a".* You can find your original work saved in the notebook with the previous version name ("v2") * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. List of updates* sentence_to_avg * Updated instructions. * Use separate variables to store the total and the average (instead of just `avg`). * Additional hint about how to initialize the shape of `avg` vector.* sentences_to_indices * Updated preceding text and instructions, added additional hints.* pretrained_embedding_layer * Additional instructions to explain how to implement each step.* Emoify_V2 * Modifies instructions to specify which parameters are needed for each Keras layer. * Remind users of Keras syntax. * Explanation of how to use the layer object that is returned by `pretrained_embedding_layer`. * Provides sample Keras code.* Spelling, grammar and wording corrections. Let's get started! Run the following cell to load the package you are going to use. ###Code import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt %matplotlib inline ###Output _____no_output_____ ###Markdown 1 - Baseline model: Emojifier-V1 1.1 - Dataset EMOJISETLet's start by building a simple baseline classifier. You have a tiny dataset (X, Y) where:- X contains 127 sentences (strings).- Y contains an integer label between 0 and 4 corresponding to an emoji for each sentence. **Figure 1**: EMOJISET - a classification problem with 5 classes. A few examples of sentences are given here. Let's load the dataset using the code below. We split the dataset between training (127 examples) and testing (56 examples). ###Code X_train, Y_train = read_csv('data/train_emoji.csv') X_test, Y_test = read_csv('data/tesss.csv') maxLen = len(max(X_train, key=len).split()) ###Output _____no_output_____ ###Markdown Run the following cell to print sentences from X_train and corresponding labels from Y_train. * Change `idx` to see different examples. * Note that due to the font used by iPython notebook, the heart emoji may be colored black rather than red. ###Code for idx in range(10): print(X_train[idx], label_to_emoji(Y_train[idx])) ###Output never talk to me again 😞 I am proud of your achievements 😄 It is the worst day in my life 😞 Miss you so much ❤️ food is life 🍴 I love you mum ❤️ Stop saying bullshit 😞 congratulations on your acceptance 😄 The assignment is too long 😞 I want to go play ⚾ ###Markdown 1.2 - Overview of the Emojifier-V1In this part, you are going to implement a baseline model called "Emojifier-v1". **Figure 2**: Baseline model (Emojifier-V1). Inputs and outputs* The input of the model is a string corresponding to a sentence (e.g. "I love you). * The output will be a probability vector of shape (1,5), (there are 5 emojis to choose from).* The (1,5) probability vector is passed to an argmax layer, which extracts the index of the emoji with the highest probability. One-hot encoding* To get our labels into a format suitable for training a softmax classifier, lets convert $Y$ from its current shape $(m, 1)$ into a "one-hot representation" $(m, 5)$, * Each row is a one-hot vector giving the label of one example. * Here, `Y_oh` stands for "Y-one-hot" in the variable names `Y_oh_train` and `Y_oh_test`: ###Code Y_oh_train = convert_to_one_hot(Y_train, C = 5) Y_oh_test = convert_to_one_hot(Y_test, C = 5) ###Output _____no_output_____ ###Markdown Let's see what `convert_to_one_hot()` did. Feel free to change `index` to print out different values. ###Code idx = 50 print(f"Sentence '{X_train[50]}' has label index {Y_train[idx]}, which is emoji {label_to_emoji(Y_train[idx])}", ) print(f"Label index {Y_train[idx]} in one-hot encoding format is {Y_oh_train[idx]}") ###Output Sentence 'I missed you' has label index 0, which is emoji ❤️ Label index 0 in one-hot encoding format is [ 1. 0. 0. 0. 0.] ###Markdown All the data is now ready to be fed into the Emojify-V1 model. Let's implement the model! 1.3 - Implementing Emojifier-V1As shown in Figure 2 (above), the first step is to:* Convert each word in the input sentence into their word vector representations.* Then take an average of the word vectors. * Similar to the previous exercise, we will use pre-trained 50-dimensional GloVe embeddings. Run the following cell to load the `word_to_vec_map`, which contains all the vector representations. ###Code word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('../../readonly/glove.6B.50d.txt') ###Output _____no_output_____ ###Markdown You've loaded:- `word_to_index`: dictionary mapping from words to their indices in the vocabulary - (400,001 words, with the valid indices ranging from 0 to 400,000)- `index_to_word`: dictionary mapping from indices to their corresponding words in the vocabulary- `word_to_vec_map`: dictionary mapping words to their GloVe vector representation.Run the following cell to check if it works. ###Code word = "cucumber" idx = 289846 print("the index of", word, "in the vocabulary is", word_to_index[word]) print("the", str(idx) + "th word in the vocabulary is", index_to_word[idx]) ###Output the index of cucumber in the vocabulary is 113317 the 289846th word in the vocabulary is potatos ###Markdown **Exercise**: Implement `sentence_to_avg()`. You will need to carry out two steps:1. Convert every sentence to lower-case, then split the sentence into a list of words. * `X.lower()` and `X.split()` might be useful. 2. For each word in the sentence, access its GloVe representation. * Then take the average of all of these word vectors. * You might use `numpy.zeros()`. Additional Hints* When creating the `avg` array of zeros, you'll want it to be a vector of the same shape as the other word vectors in the `word_to_vec_map`. * You can choose a word that exists in the `word_to_vec_map` and access its `.shape` field. * Be careful not to hard code the word that you access. In other words, don't assume that if you see the word 'the' in the `word_to_vec_map` within this notebook, that this word will be in the `word_to_vec_map` when the function is being called by the automatic grader. * Hint: you can use any one of the word vectors that you retrieved from the input `sentence` to find the shape of a word vector. ###Code # GRADED FUNCTION: sentence_to_avg def sentence_to_avg(sentence, word_to_vec_map): """ Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: sentence -- string, one training example from X word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation Returns: avg -- average vector encoding information about the sentence, numpy-array of shape (50,) """ ### START CODE HERE ### # Step 1: Split sentence into list of lower case words (≈ 1 line) words = sentence.lower().split() # Initialize the average word vector, should have the same shape as your word vectors. avg = np.zeros((len(word_to_vec_map[words[0]]), 0)) # Step 2: average the word vectors. You can loop over the words in the list "words". total = 0 for w in words: total += word_to_vec_map[w] avg = total / len(words) ### END CODE HERE ### return avg avg = sentence_to_avg("Morrocan couscous is my favorite dish", word_to_vec_map) print("avg = \n", avg) ###Output avg = [-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.26037767 0.05820667 -0.01578167 -0.12078833 -0.02471267 0.4128455 0.5152061 0.38756167 -0.898661 -0.535145 0.33501167 0.68806933 -0.2156265 1.797155 0.10476933 -0.36775333 0.750785 0.10282583 0.348925 -0.27262833 0.66768 -0.10706167 -0.283635 0.59580117 0.28747333 -0.3366635 0.23393817 0.34349183 0.178405 0.1166155 -0.076433 0.1445417 0.09808667] ###Markdown **Expected Output**:```Pythonavg =[-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.26037767 0.05820667 -0.01578167 -0.12078833 -0.02471267 0.4128455 0.5152061 0.38756167 -0.898661 -0.535145 0.33501167 0.68806933 -0.2156265 1.797155 0.10476933 -0.36775333 0.750785 0.10282583 0.348925 -0.27262833 0.66768 -0.10706167 -0.283635 0.59580117 0.28747333 -0.3366635 0.23393817 0.34349183 0.178405 0.1166155 -0.076433 0.1445417 0.09808667]``` ModelYou now have all the pieces to finish implementing the `model()` function. After using `sentence_to_avg()` you need to:* Pass the average through forward propagation* Compute the cost* Backpropagate to update the softmax parameters**Exercise**: Implement the `model()` function described in Figure (2). * The equations you need to implement in the forward pass and to compute the cross-entropy cost are below:* The variable $Y_{oh}$ ("Y one hot") is the one-hot encoding of the output labels. $$ z^{(i)} = W . avg^{(i)} + b$$$$ a^{(i)} = softmax(z^{(i)})$$$$ \mathcal{L}^{(i)} = - \sum_{k = 0}^{n_y - 1} Y_{oh,k}^{(i)} * log(a^{(i)}_k)$$**Note** It is possible to come up with a more efficient vectorized implementation. For now, let's use nested for loops to better understand the algorithm, and for easier debugging.We provided the function `softmax()`, which was imported earlier. ###Code # GRADED FUNCTION: model def model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 400): """ Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation learning_rate -- learning_rate for the stochastic gradient descent algorithm num_iterations -- number of iterations Returns: pred -- vector of predictions, numpy-array of shape (m, 1) W -- weight matrix of the softmax layer, of shape (n_y, n_h) b -- bias of the softmax layer, of shape (n_y,) """ np.random.seed(1) # Define number of training examples m = Y.shape[0] # number of training examples n_y = 5 # number of classes n_h = 50 # dimensions of the GloVe vectors # Initialize parameters using Xavier initialization W = np.random.randn(n_y, n_h) / np.sqrt(n_h) b = np.zeros((n_y,)) # Convert Y to Y_onehot with n_y classes Y_oh = convert_to_one_hot(Y, C = n_y) # Optimization loop for t in range(num_iterations): # Loop over the number of iterations for i in range(m): # Loop over the training examples ### START CODE HERE ### (≈ 4 lines of code) # Average the word vectors of the words from the i'th training example avg = sentence_to_avg(X[i], word_to_vec_map) # Forward propagate the avg through the softmax layer z = np.dot(W, avg) + b a = softmax(z) # Compute cost using the i'th training label's one hot representation and "A" (the output of the softmax) cost = -1 * np.sum(Y[i] * np.log(a)) ### END CODE HERE ### # Compute gradients dz = a - Y_oh[i] dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h)) db = dz # Update parameters with Stochastic Gradient Descent W = W - learning_rate * dW b = b - learning_rate * db if t % 100 == 0: print("Epoch: " + str(t) + " --- cost = " + str(cost)) pred = predict(X, Y, W, b, word_to_vec_map) #predict is defined in emo_utils.py return pred, W, b print(X_train.shape) print(Y_train.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(X_train[0]) print(type(X_train)) Y = np.asarray([5,0,0,5, 4, 4, 4, 6, 6, 4, 1, 1, 5, 6, 6, 3, 6, 3, 4, 4]) print(Y.shape) X = np.asarray(['I am going to the bar tonight', 'I love you', 'miss you my dear', 'Lets go party and drinks','Congrats on the new job','Congratulations', 'I am so happy for you', 'Why are you feeling bad', 'What is wrong with you', 'You totally deserve this prize', 'Let us go play football', 'Are you down for football this afternoon', 'Work hard play harder', 'It is suprising how people can be dumb sometimes', 'I am very disappointed','It is the best day in my life', 'I think I will end up alone','My life is so boring','Good job', 'Great so awesome']) print(X.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(type(X_train)) ###Output (132,) (132,) (132, 5) never talk to me again <class 'numpy.ndarray'> (20,) (20,) (132, 5) <class 'numpy.ndarray'> ###Markdown Run the next cell to train your model and learn the softmax parameters (W,b). ###Code pred, W, b = model(X_train, Y_train, word_to_vec_map) # print(pred) ###Output Epoch: 0 --- cost = 16.77334679 Accuracy: 0.348484848485 Epoch: 100 --- cost = 35.335343384 Accuracy: 0.931818181818 Epoch: 200 --- cost = 40.8584548199 Accuracy: 0.954545454545 Epoch: 300 --- cost = 43.8109696861 Accuracy: 0.969696969697 ###Markdown **Expected Output** (on a subset of iterations): **Epoch: 0** cost = 1.95204988128 Accuracy: 0.348484848485 **Epoch: 100** cost = 0.0797181872601 Accuracy: 0.931818181818 **Epoch: 200** cost = 0.0445636924368 Accuracy: 0.954545454545 **Epoch: 300** cost = 0.0343226737879 Accuracy: 0.969696969697 Great! Your model has pretty high accuracy on the training set. Lets now see how it does on the test set. 1.4 - Examining test set performance * Note that the `predict` function used here is defined in emo_util.spy. ###Code print("Training set:") pred_train = predict(X_train, Y_train, W, b, word_to_vec_map) print('Test set:') pred_test = predict(X_test, Y_test, W, b, word_to_vec_map) ###Output Training set: Accuracy: 0.977272727273 Test set: Accuracy: 0.857142857143 ###Markdown **Expected Output**: **Train set accuracy** 97.7 **Test set accuracy** 85.7 * Random guessing would have had 20% accuracy given that there are 5 classes. (1/5 = 20%).* This is pretty good performance after training on only 127 examples. The model matches emojis to relevant wordsIn the training set, the algorithm saw the sentence >"*I love you*" with the label ❤️. * You can check that the word "adore" does not appear in the training set. * Nonetheless, lets see what happens if you write "*I adore you*." ###Code X_my_sentences = np.array(["i adore you", "i love you", "funny lol", "lets play with a ball", "food is ready", "not feeling happy"]) Y_my_labels = np.array([[0], [0], [2], [1], [4],[3]]) pred = predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map) print_predictions(X_my_sentences, pred) ###Output Accuracy: 0.833333333333 i adore you ❤️ i love you ❤️ funny lol 😄 lets play with a ball ⚾ food is ready 🍴 not feeling happy 😄 ###Markdown Amazing! * Because *adore* has a similar embedding as *love*, the algorithm has generalized correctly even to a word it has never seen before. * Words such as *heart*, *dear*, *beloved* or *adore* have embedding vectors similar to *love*. * Feel free to modify the inputs above and try out a variety of input sentences. * How well does it work? Word ordering isn't considered in this model* Note that the model doesn't get the following sentence correct:>"not feeling happy" * This algorithm ignores word ordering, so is not good at understanding phrases like "not happy." Confusion matrix* Printing the confusion matrix can also help understand which classes are more difficult for your model. * A confusion matrix shows how often an example whose label is one class ("actual" class) is mislabeled by the algorithm with a different class ("predicted" class). ###Code print(Y_test.shape) print(' '+ label_to_emoji(0)+ ' ' + label_to_emoji(1) + ' ' + label_to_emoji(2)+ ' ' + label_to_emoji(3)+' ' + label_to_emoji(4)) print(pd.crosstab(Y_test, pred_test.reshape(56,), rownames=['Actual'], colnames=['Predicted'], margins=True)) plot_confusion_matrix(Y_test, pred_test) ###Output (56,) ❤️ ⚾ 😄 😞 🍴 Predicted 0.0 1.0 2.0 3.0 4.0 All Actual 0 6 0 0 1 0 7 1 0 8 0 0 0 8 2 2 0 16 0 0 18 3 1 1 2 12 0 16 4 0 0 1 0 6 7 All 9 9 19 13 6 56 ###Markdown What you should remember from this section- Even with a 127 training examples, you can get a reasonably good model for Emojifying. - This is due to the generalization power word vectors gives you. - Emojify-V1 will perform poorly on sentences such as *"This movie is not good and not enjoyable"* - It doesn't understand combinations of words. - It just averages all the words' embedding vectors together, without considering the ordering of words. **You will build a better algorithm in the next section!** 2 - Emojifier-V2: Using LSTMs in Keras: Let's build an LSTM model that takes word **sequences** as input!* This model will be able to account for the word ordering. * Emojifier-V2 will continue to use pre-trained word embeddings to represent words.* We will feed word embeddings into an LSTM.* The LSTM will learn to predict the most appropriate emoji. Run the following cell to load the Keras packages. ###Code import numpy as np np.random.seed(0) from keras.models import Model from keras.layers import Dense, Input, Dropout, LSTM, Activation from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from keras.initializers import glorot_uniform np.random.seed(1) ###Output Using TensorFlow backend. ###Markdown 2.1 - Overview of the modelHere is the Emojifier-v2 you will implement: **Figure 3**: Emojifier-V2. A 2-layer LSTM sequence classifier. 2.2 Keras and mini-batching * In this exercise, we want to train Keras using mini-batches. * However, most deep learning frameworks require that all sequences in the same mini-batch have the **same length**. * This is what allows vectorization to work: If you had a 3-word sentence and a 4-word sentence, then the computations needed for them are different (one takes 3 steps of an LSTM, one takes 4 steps) so it's just not possible to do them both at the same time. Padding handles sequences of varying length* The common solution to handling sequences of **different length** is to use padding. Specifically: * Set a maximum sequence length * Pad all sequences to have the same length. Example of padding* Given a maximum sequence length of 20, we could pad every sentence with "0"s so that each input sentence is of length 20. * Thus, the sentence "I love you" would be represented as $(e_{I}, e_{love}, e_{you}, \vec{0}, \vec{0}, \ldots, \vec{0})$. * In this example, any sentences longer than 20 words would have to be truncated. * One way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set. 2.3 - The Embedding layer* In Keras, the embedding matrix is represented as a "layer".* The embedding matrix maps word indices to embedding vectors. * The word indices are positive integers. * The embedding vectors are dense vectors of fixed size. * When we say a vector is "dense", in this context, it means that most of the values are non-zero. As a counter-example, a one-hot encoded vector is not "dense."* The embedding matrix can be derived in two ways: * Training a model to derive the embeddings from scratch. * Using a pretrained embedding Using and updating pre-trained embeddings* In this part, you will learn how to create an [Embedding()](https://keras.io/layers/embeddings/) layer in Keras* You will initialize the Embedding layer with the GloVe 50-dimensional vectors. * In the code below, we'll show you how Keras allows you to either train or leave fixed this layer. * Because our training set is quite small, we will leave the GloVe embeddings fixed instead of updating them. Inputs and outputs to the embedding layer* The `Embedding()` layer's input is an integer matrix of size **(batch size, max input length)**. * This input corresponds to sentences converted into lists of indices (integers). * The largest integer (the highest word index) in the input should be no larger than the vocabulary size.* The embedding layer outputs an array of shape (batch size, max input length, dimension of word vectors).* The figure shows the propagation of two example sentences through the embedding layer. * Both examples have been zero-padded to a length of `max_len=5`. * The word embeddings are 50 units in length. * The final dimension of the representation is `(2,max_len,50)`. **Figure 4**: Embedding layer Prepare the input sentences**Exercise**: * Implement `sentences_to_indices`, which processes an array of sentences (X) and returns inputs to the embedding layer: * Convert each training sentences into a list of indices (the indices correspond to each word in the sentence) * Zero-pad all these lists so that their length is the length of the longest sentence. Additional Hints* Note that you may have considered using the `enumerate()` function in the for loop, but for the purposes of passing the autograder, please follow the starter code by initializing and incrementing `j` explicitly. ###Code for idx, val in enumerate(["I", "like", "learning"]): print(idx,val) # GRADED FUNCTION: sentences_to_indices def sentences_to_indices(X, word_to_index, max_len): """ Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). Arguments: X -- array of sentences (strings), of shape (m, 1) word_to_index -- a dictionary containing the each word mapped to its index max_len -- maximum number of words in a sentence. You can assume every sentence in X is no longer than this. Returns: X_indices -- array of indices corresponding to words in the sentences from X, of shape (m, max_len) """ m = X.shape[0] # number of training examples ### START CODE HERE ### # Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line) X_indices = np.zeros((m, max_len)) for i in range(m): # loop over training examples # Convert the ith training sentence in lower case and split is into words. You should get a list of words. sentence_words = X[i].lower().split() # Initialize j to 0 j = 0 # Loop over the words of sentence_words for w in sentence_words: # Set the (i,j)th entry of X_indices to the index of the correct word. X_indices[i, j] = word_to_index[w] # Increment j to j + 1 j = j + 1 ### END CODE HERE ### return X_indices ###Output _____no_output_____ ###Markdown Run the following cell to check what `sentences_to_indices()` does, and check your results. ###Code X1 = np.array(["funny lol", "lets play baseball", "food is ready for you"]) X1_indices = sentences_to_indices(X1,word_to_index, max_len = 5) print("X1 =", X1) print("X1_indices =\n", X1_indices) ###Output X1 = ['funny lol' 'lets play baseball' 'food is ready for you'] X1_indices = [[ 155345. 225122. 0. 0. 0.] [ 220930. 286375. 69714. 0. 0.] [ 151204. 192973. 302254. 151349. 394475.]] ###Markdown **Expected Output**:```PythonX1 = ['funny lol' 'lets play baseball' 'food is ready for you']X1_indices = [[ 155345. 225122. 0. 0. 0.] [ 220930. 286375. 69714. 0. 0.] [ 151204. 192973. 302254. 151349. 394475.]]``` Build embedding layer* Let's build the `Embedding()` layer in Keras, using pre-trained word vectors. * The embedding layer takes as input a list of word indices. * `sentences_to_indices()` creates these word indices.* The embedding layer will return the word embeddings for a sentence. **Exercise**: Implement `pretrained_embedding_layer()` with these steps:1. Initialize the embedding matrix as a numpy array of zeros. * The embedding matrix has a row for each unique word in the vocabulary. * There is one additional row to handle "unknown" words. * So vocab_len is the number of unique words plus one. * Each row will store the vector representation of one word. * For example, one row may be 50 positions long if using GloVe word vectors. * In the code below, `emb_dim` represents the length of a word embedding.2. Fill in each row of the embedding matrix with the vector representation of a word * Each word in `word_to_index` is a string. * word_to_vec_map is a dictionary where the keys are strings and the values are the word vectors.3. Define the Keras embedding layer. * Use [Embedding()](https://keras.io/layers/embeddings/). * The input dimension is equal to the vocabulary length (number of unique words plus one). * The output dimension is equal to the number of positions in a word embedding. * Make this layer's embeddings fixed. * If you were to set `trainable = True`, then it will allow the optimization algorithm to modify the values of the word embeddings. * In this case, we don't want the model to modify the word embeddings.4. Set the embedding weights to be equal to the embedding matrix. * Note that this is part of the code is already completed for you and does not need to be modified. ###Code # GRADED FUNCTION: pretrained_embedding_layer def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: embedding_layer -- pretrained layer Keras instance """ vocab_len = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement) emb_dim = word_to_vec_map["cucumber"].shape[0] # define dimensionality of your GloVe word vectors (= 50) ### START CODE HERE ### # Step 1 # Initialize the embedding matrix as a numpy array of zeros. # See instructions above to choose the correct shape. emb_matrix = np.zeros((vocab_len, emb_dim)) # Step 2 # Set each row "idx" of the embedding matrix to be # the word vector representation of the idx'th word of the vocabulary for word, idx in word_to_index.items(): emb_matrix[idx, :] = word_to_vec_map[word] # Step 3 # Define Keras embedding layer with the correct input and output sizes # Make it non-trainable. embedding_layer = Embedding(vocab_len, emb_dim, trainable = False) ### END CODE HERE ### # Step 4 (already done for you; please do not modify) # Build the embedding layer, it is required before setting the weights of the embedding layer. embedding_layer.build((None,)) # Do not modify the "None". This line of code is complete as-is. # Set the weights of the embedding layer to the embedding matrix. Your layer is now pretrained. embedding_layer.set_weights([emb_matrix]) return embedding_layer embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) print("weights[0][1][3] =", embedding_layer.get_weights()[0][1][3]) ###Output weights[0][1][3] = -0.3403 ###Markdown **Expected Output**:```Pythonweights[0][1][3] = -0.3403``` 2.3 Building the Emojifier-V2Lets now build the Emojifier-V2 model. * You feed the embedding layer's output to an LSTM network. **Figure 3**: Emojifier-v2. A 2-layer LSTM sequence classifier. **Exercise:** Implement `Emojify_V2()`, which builds a Keras graph of the architecture shown in Figure 3. * The model takes as input an array of sentences of shape (`m`, `max_len`, ) defined by `input_shape`. * The model outputs a softmax probability vector of shape (`m`, `C = 5`). * You may need to use the following Keras layers: * [Input()](https://keras.io/layers/core/input) * Set the `shape` and `dtype` parameters. * The inputs are integers, so you can specify the data type as a string, 'int32'. * [LSTM()](https://keras.io/layers/recurrent/lstm) * Set the `units` and `return_sequences` parameters. * [Dropout()](https://keras.io/layers/core/dropout) * Set the `rate` parameter. * [Dense()](https://keras.io/layers/core/dense) * Set the `units`, * Note that `Dense()` has an `activation` parameter. For the purposes of passing the autograder, please do not set the activation within `Dense()`. Use the separate `Activation` layer to do so. * [Activation()](https://keras.io/activations/). * You can pass in the activation of your choice as a lowercase string. * [Model](https://keras.io/models/model/) Set `inputs` and `outputs`. Additional Hints* Remember that these Keras layers return an object, and you will feed in the outputs of the previous layer as the input arguments to that object. The returned object can be created and called in the same line.```Python How to use Keras layers in two lines of codedense_object = Dense(units = ...)X = dense_object(inputs) How to use Keras layers in one line of codeX = Dense(units = ...)(inputs)```* The `embedding_layer` that is returned by `pretrained_embedding_layer` is a layer object that can be called as a function, passing in a single argument (sentence indices).* Here is some sample code in case you're stuck```Pythonraw_inputs = Input(shape=(maxLen,), dtype='int32')preprocessed_inputs = ... some pre-processingX = LSTM(units = ..., return_sequences= ...)(processed_inputs)X = Dropout(rate = ..., )(X)...X = Dense(units = ...)(X)X = Activation(...)(X)model = Model(inputs=..., outputs=...)...``` ###Code # GRADED FUNCTION: Emojify_V2 def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: model -- a model instance in Keras """ ### START CODE HERE ### # Define sentence_indices as the input of the graph. # It should be of shape input_shape and dtype 'int32' (as it contains indices, which are integers). sentence_indices = Input(shape=input_shape, dtype='int32') # Create the embedding layer pretrained with GloVe Vectors (≈1 line) embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) # Propagate sentence_indices through your embedding layer # (See additional hints in the instructions). embeddings = embedding_layer(sentence_indices) # Propagate the embeddings through an LSTM layer with 128-dimensional hidden state # The returned output should be a batch of sequences. X = LSTM(units=128, return_sequences=True)(embeddings) # Add dropout with a probability of 0.5 X = Dropout(rate=0.5)(X) # Propagate X trough another LSTM layer with 128-dimensional hidden state # The returned output should be a single hidden state, not a batch of sequences. X = LSTM(units=128)(X) # Add dropout with a probability of 0.5 X = Dropout(rate=0.5)(X) # Propagate X through a Dense layer with 5 units X = Dense(units=5)(X) # Add a softmax activation X = Activation('softmax')(X) # Create Model instance which converts sentence_indices into X. model = Model(inputs=sentence_indices, outputs=X) ### END CODE HERE ### return model ###Output _____no_output_____ ###Markdown Run the following cell to create your model and check its summary. Because all sentences in the dataset are less than 10 words, we chose `max_len = 10`. You should see your architecture, it uses "20,223,927" parameters, of which 20,000,050 (the word embeddings) are non-trainable, and the remaining 223,877 are. Because our vocabulary size has 400,001 words (with valid indices from 0 to 400,000) there are 400,001\*50 = 20,000,050 non-trainable parameters. ###Code model = Emojify_V2((maxLen,), word_to_vec_map, word_to_index) model.summary() ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_3 (InputLayer) (None, 10) 0 _________________________________________________________________ embedding_4 (Embedding) (None, 10, 50) 20000050 _________________________________________________________________ lstm_5 (LSTM) (None, 10, 128) 91648 _________________________________________________________________ dropout_5 (Dropout) (None, 10, 128) 0 _________________________________________________________________ lstm_6 (LSTM) (None, 128) 131584 _________________________________________________________________ dropout_6 (Dropout) (None, 128) 0 _________________________________________________________________ dense_3 (Dense) (None, 5) 645 _________________________________________________________________ activation_3 (Activation) (None, 5) 0 ================================================================= Total params: 20,223,927 Trainable params: 223,877 Non-trainable params: 20,000,050 _________________________________________________________________ ###Markdown As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using `categorical_crossentropy` loss, `adam` optimizer and `['accuracy']` metrics: ###Code model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ###Output _____no_output_____ ###Markdown It's time to train your model. Your Emojifier-V2 `model` takes as input an array of shape (`m`, `max_len`) and outputs probability vectors of shape (`m`, `number of classes`). We thus have to convert X_train (array of sentences as strings) to X_train_indices (array of sentences as list of word indices), and Y_train (labels as indices) to Y_train_oh (labels as one-hot vectors). ###Code X_train_indices = sentences_to_indices(X_train, word_to_index, maxLen) Y_train_oh = convert_to_one_hot(Y_train, C = 5) ###Output _____no_output_____ ###Markdown Fit the Keras model on `X_train_indices` and `Y_train_oh`. We will use `epochs = 50` and `batch_size = 32`. ###Code model.fit(X_train_indices, Y_train_oh, epochs = 50, batch_size = 32, shuffle=True) ###Output Epoch 1/50 132/132 [==============================] - 0s - loss: 1.5911 - acc: 0.2576 Epoch 2/50 132/132 [==============================] - 0s - loss: 1.5229 - acc: 0.3409 Epoch 3/50 132/132 [==============================] - 0s - loss: 1.4845 - acc: 0.3182 Epoch 4/50 132/132 [==============================] - 0s - loss: 1.4285 - acc: 0.4697 Epoch 5/50 132/132 [==============================] - 0s - loss: 1.3204 - acc: 0.4697 Epoch 6/50 132/132 [==============================] - 0s - loss: 1.1865 - acc: 0.5227 Epoch 7/50 132/132 [==============================] - 0s - loss: 1.1207 - acc: 0.6136 Epoch 8/50 132/132 [==============================] - 0s - loss: 1.0312 - acc: 0.6136 Epoch 9/50 132/132 [==============================] - 0s - loss: 0.9393 - acc: 0.6742 Epoch 10/50 132/132 [==============================] - 0s - loss: 0.8509 - acc: 0.6894 Epoch 11/50 132/132 [==============================] - 0s - loss: 0.7477 - acc: 0.7500 Epoch 12/50 132/132 [==============================] - 0s - loss: 0.6353 - acc: 0.7652 Epoch 13/50 132/132 [==============================] - 0s - loss: 0.5840 - acc: 0.7727 Epoch 14/50 132/132 [==============================] - 0s - loss: 0.4955 - acc: 0.8258 Epoch 15/50 132/132 [==============================] - 0s - loss: 0.4601 - acc: 0.8409 Epoch 16/50 132/132 [==============================] - 0s - loss: 0.3729 - acc: 0.8561 Epoch 17/50 132/132 [==============================] - 0s - loss: 0.3043 - acc: 0.9015 Epoch 18/50 132/132 [==============================] - 0s - loss: 0.3138 - acc: 0.8864 Epoch 19/50 132/132 [==============================] - 0s - loss: 0.3505 - acc: 0.8712 Epoch 20/50 132/132 [==============================] - 0s - loss: 0.3015 - acc: 0.8788 Epoch 21/50 132/132 [==============================] - 0s - loss: 0.2650 - acc: 0.9091 Epoch 22/50 132/132 [==============================] - 0s - loss: 0.3097 - acc: 0.9015 Epoch 23/50 132/132 [==============================] - 0s - loss: 0.3113 - acc: 0.9015 Epoch 24/50 132/132 [==============================] - 0s - loss: 0.2442 - acc: 0.9091 Epoch 25/50 132/132 [==============================] - 0s - loss: 0.2151 - acc: 0.9394 Epoch 26/50 132/132 [==============================] - 0s - loss: 0.1895 - acc: 0.9318 Epoch 27/50 132/132 [==============================] - 0s - loss: 0.2505 - acc: 0.9015 Epoch 28/50 132/132 [==============================] - 0s - loss: 0.1776 - acc: 0.9318 Epoch 29/50 132/132 [==============================] - 0s - loss: 0.1854 - acc: 0.9242 Epoch 30/50 132/132 [==============================] - 0s - loss: 0.1339 - acc: 0.9394 Epoch 31/50 132/132 [==============================] - 0s - loss: 0.1603 - acc: 0.9318 Epoch 32/50 132/132 [==============================] - 0s - loss: 0.1437 - acc: 0.9545 Epoch 33/50 132/132 [==============================] - 0s - loss: 0.3910 - acc: 0.8712 - ETA: 0s - loss: 0.2413 - acc: 0.8 Epoch 34/50 132/132 [==============================] - 0s - loss: 0.2827 - acc: 0.9015 Epoch 35/50 132/132 [==============================] - 0s - loss: 0.1808 - acc: 0.9545 Epoch 36/50 132/132 [==============================] - 0s - loss: 0.1121 - acc: 0.9773 Epoch 37/50 132/132 [==============================] - 0s - loss: 0.1905 - acc: 0.9394 Epoch 38/50 132/132 [==============================] - 0s - loss: 0.2198 - acc: 0.9394 Epoch 39/50 132/132 [==============================] - 0s - loss: 0.1585 - acc: 0.9621 Epoch 40/50 132/132 [==============================] - 0s - loss: 0.1507 - acc: 0.9470 Epoch 41/50 132/132 [==============================] - 0s - loss: 0.1299 - acc: 0.9394 Epoch 42/50 132/132 [==============================] - 0s - loss: 0.0872 - acc: 0.9697 Epoch 43/50 132/132 [==============================] - 0s - loss: 0.0820 - acc: 0.9773 Epoch 44/50 132/132 [==============================] - 0s - loss: 0.0537 - acc: 0.9924 Epoch 45/50 132/132 [==============================] - 0s - loss: 0.0527 - acc: 0.9697 Epoch 46/50 132/132 [==============================] - 0s - loss: 0.0378 - acc: 0.9848 Epoch 47/50 132/132 [==============================] - 0s - loss: 0.0257 - acc: 1.0000 Epoch 48/50 132/132 [==============================] - 0s - loss: 0.0204 - acc: 0.9924 Epoch 49/50 132/132 [==============================] - 0s - loss: 0.0418 - acc: 0.9773 Epoch 50/50 132/132 [==============================] - 0s - loss: 0.0298 - acc: 0.9924 ###Markdown Your model should perform around **90% to 100% accuracy** on the training set. The exact accuracy you get may be a little different. Run the following cell to evaluate your model on the test set. ###Code X_test_indices = sentences_to_indices(X_test, word_to_index, max_len = maxLen) Y_test_oh = convert_to_one_hot(Y_test, C = 5) loss, acc = model.evaluate(X_test_indices, Y_test_oh) print() print("Test accuracy = ", acc) ###Output 32/56 [================>.............] - ETA: 0s Test accuracy = 0.875 ###Markdown You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples. ###Code # This code allows you to see the mislabelled examples C = 5 y_test_oh = np.eye(C)[Y_test.reshape(-1)] X_test_indices = sentences_to_indices(X_test, word_to_index, maxLen) pred = model.predict(X_test_indices) for i in range(len(X_test)): x = X_test_indices num = np.argmax(pred[i]) if(num != Y_test[i]): print('Expected emoji:'+ label_to_emoji(Y_test[i]) + ' prediction: '+ X_test[i] + label_to_emoji(num).strip()) ###Output Expected emoji:😄 prediction: she got me a nice present ❤️ Expected emoji:🍴 prediction: any suggestions for dinner 😄 Expected emoji:❤️ prediction: I love taking breaks 😞 Expected emoji:😄 prediction: you brighten my day ❤️ Expected emoji:😄 prediction: will you be my valentine ❤️ Expected emoji:😄 prediction: What you did was awesome 😞 Expected emoji:❤️ prediction: family is all I have 😞 ###Markdown Now you can try it on your own example. Write your own sentence below. ###Code # Change the sentence below to see your prediction. Make sure all the words are in the Glove embeddings. x_test = np.array(['not feeling good']) X_test_indices = sentences_to_indices(x_test, word_to_index, maxLen) print(x_test[0] +' '+ label_to_emoji(np.argmax(model.predict(X_test_indices)))) ###Output not feeling good 😞
Coursera/IBM Data Science Professional Certificate/Machine Learning with Python/Week 3/ML0101EN-Clas-Logistic-Reg-churn-py-v1.ipynb
###Markdown Logistic Regression with PythonEstimated time needed: **25** minutes ObjectivesAfter completing this lab you will be able to:- Use scikit Logistic Regression to classify- Understand confusion matrix In this notebook, you will learn Logistic Regression, and then, you'll create a model for a telecommunication company, to predict when its customers will leave for a competitor, so that they can take some action to retain the customers. Table of contents About the dataset Data pre-processing and selection Modeling (Logistic Regression with Scikit-learn) Evaluation Practice What is the difference between Linear and Logistic Regression?While Linear Regression is suited for estimating continuous values (e.g. estimating house price), it is not the best tool for predicting the class of an observed data point. In order to estimate the class of a data point, we need some sort of guidance on what would be the most probable class for that data point. For this, we use Logistic Regression.Recall linear regression: As you know, Linear regression finds a function that relates a continuous dependent variable, y, to some predictors (independent variables $x_1$, $x_2$, etc.). For example, Simple linear regression assumes a function of the form:$$y = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \cdots$$and finds the values of parameters $\theta_0, \theta_1, \theta_2$, etc, where the term $\theta_0$ is the "intercept". It can be generally shown as:$$ℎ_\theta(𝑥) = \theta^TX$$Logistic Regression is a variation of Linear Regression, useful when the observed dependent variable, y, is categorical. It produces a formula that predicts the probability of the class label as a function of the independent variables.Logistic regression fits a special s-shaped curve by taking the linear regression and transforming the numeric estimate into a probability with the following function, which is called sigmoid function 𝜎:$$ℎ_\theta(𝑥) = \sigma({\theta^TX}) = \frac {e^{(\theta_0 + \theta_1 x_1 + \theta_2 x_2 +...)}}{1 + e^{(\theta_0 + \theta_1 x_1 + \theta_2 x_2 +\cdots)}}$$Or:$$ProbabilityOfaClass_1 = P(Y=1|X) = \sigma({\theta^TX}) = \frac{e^{\theta^TX}}{1+e^{\theta^TX}} $$In this equation, ${\theta^TX}$ is the regression result (the sum of the variables weighted by the coefficients), `exp` is the exponential function and $\sigma(\theta^TX)$ is the sigmoid or [logistic function](http://en.wikipedia.org/wiki/Logistic_function?cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork-20718538&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork-20718538&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork-20718538&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork-20718538&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ), also called logistic curve. It is a common "S" shape (sigmoid curve).So, briefly, Logistic Regression passes the input through the logistic/sigmoid but then treats the result as a probability:<imgsrc="https://ibm.box.com/shared/static/kgv9alcghmjcv97op4d6onkyxevk23b1.png" width="400" align="center">The objective of **Logistic Regression** algorithm, is to find the best parameters θ, for $ℎ_\theta(𝑥)$ = $\sigma({\theta^TX})$, in such a way that the model best predicts the class of each case. Customer churn with Logistic RegressionA telecommunications company is concerned about the number of customers leaving their land-line business for cable competitors. They need to understand who is leaving. Imagine that you are an analyst at this company and you have to find out who is leaving and why. ###Code !pip install scikit-learn==0.23.1 ###Output Collecting scikit-learn==0.23.1 [?25l Downloading https://files.pythonhosted.org/packages/d9/3a/eb8d7bbe28f4787d140bb9df685b7d5bf6115c0e2a969def4027144e98b6/scikit_learn-0.23.1-cp36-cp36m-manylinux1_x86_64.whl (6.8MB)  |████████████████████████████████| 6.9MB 3.0MB/s eta 0:00:01 |█████████▌ | 2.0MB 5.0MB/s eta 0:00:01 |█████████████ | 2.8MB 5.0MB/s eta 0:00:01 [?25hCollecting threadpoolctl>=2.0.0 (from scikit-learn==0.23.1) Downloading https://files.pythonhosted.org/packages/f7/12/ec3f2e203afa394a149911729357aa48affc59c20e2c1c8297a60f33f133/threadpoolctl-2.1.0-py3-none-any.whl Requirement already satisfied: scipy>=0.19.1 in /home/jupyterlab/conda/envs/python/lib/python3.6/site-packages (from scikit-learn==0.23.1) (1.5.4) Requirement already satisfied: numpy>=1.13.3 in /home/jupyterlab/conda/envs/python/lib/python3.6/site-packages (from scikit-learn==0.23.1) (1.19.4) Collecting joblib>=0.11 (from scikit-learn==0.23.1) [?25l Downloading https://files.pythonhosted.org/packages/34/5b/bd0f0fb5564183884d8e35b81d06d7ec06a20d1a0c8b4c407f1554691dce/joblib-1.0.0-py3-none-any.whl (302kB)  |████████████████████████████████| 307kB 19.8MB/s eta 0:00:01 [?25hInstalling collected packages: threadpoolctl, joblib, scikit-learn Found existing installation: scikit-learn 0.20.1 Uninstalling scikit-learn-0.20.1: Successfully uninstalled scikit-learn-0.20.1 Successfully installed joblib-1.0.0 scikit-learn-0.23.1 threadpoolctl-2.1.0 ###Markdown Lets first import required libraries: ###Code import pandas as pd import pylab as pl import numpy as np import scipy.optimize as opt from sklearn import preprocessing %matplotlib inline import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown About the datasetWe will use a telecommunications dataset for predicting customer churn. This is a historical customer dataset where each row represents one customer. The data is relatively easy to understand, and you may uncover insights you can use immediately. Typically it is less expensive to keep customers than acquire new ones, so the focus of this analysis is to predict the customers who will stay with the company. This data set provides information to help you predict what behavior will help you to retain customers. You can analyze all relevant customer data and develop focused customer retention programs.The dataset includes information about:- Customers who left within the last month – the column is called Churn- Services that each customer has signed up for – phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies- Customer account information – how long they had been a customer, contract, payment method, paperless billing, monthly charges, and total charges- Demographic info about customers – gender, age range, and if they have partners and dependents Load the Telco Churn dataTelco Churn is a hypothetical data file that concerns a telecommunications company's efforts to reduce turnover in its customer base. Each case corresponds to a separate customer and it records various demographic and service usage information. Before you can work with the data, you must use the URL to get the ChurnData.csv.To download the data, we will use `!wget` to download it from IBM Object Storage. ###Code #Click here and press Shift+Enter !wget -O ChurnData.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/ChurnData.csv ###Output --2021-02-08 09:40:52-- https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/ChurnData.csv Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.63.118.104 Connecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|169.63.118.104|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 35943 (35K) [text/csv] Saving to: ‘ChurnData.csv’ ChurnData.csv 100%[===================>] 35.10K --.-KB/s in 0.02s 2021-02-08 09:40:52 (1.89 MB/s) - ‘ChurnData.csv’ saved [35943/35943] ###Markdown **Did you know?** When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) Load Data From CSV File ###Code churn_df = pd.read_csv("ChurnData.csv") churn_df.head() ###Output _____no_output_____ ###Markdown Data pre-processing and selection Lets select some features for the modeling. Also we change the target data type to be integer, as it is a requirement by the skitlearn algorithm: ###Code churn_df = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless','churn']] churn_df['churn'] = churn_df['churn'].astype('int') churn_df.head() ###Output _____no_output_____ ###Markdown PracticeHow many rows and columns are in this dataset in total? What are the name of columns? ###Code # write your code here print(churn_df.shape) churn_df.columns ###Output (200, 10) ###Markdown Click here for the solution```pythonchurn_df.shape``` Lets define X, and y for our dataset: ###Code X = np.asarray(churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']]) X[0:5] y = np.asarray(churn_df['churn']) y [0:5] ###Output _____no_output_____ ###Markdown Also, we normalize the dataset: ###Code from sklearn import preprocessing X = preprocessing.StandardScaler().fit(X).transform(X) X[0:5] ###Output _____no_output_____ ###Markdown Train/Test dataset Okay, we split our dataset into train and test set: ###Code from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape) ###Output Train set: (160, 7) (160,) Test set: (40, 7) (40,) ###Markdown Modeling (Logistic Regression with Scikit-learn) Lets build our model using **LogisticRegression** from Scikit-learn package. This function implements logistic regression and can use different numerical optimizers to find parameters, including ‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’ solvers. You can find extensive information about the pros and cons of these optimizers if you search it in internet.The version of Logistic Regression in Scikit-learn, support regularization. Regularization is a technique used to solve the overfitting problem in machine learning models.**C** parameter indicates **inverse of regularization strength** which must be a positive float. Smaller values specify stronger regularization. Now lets fit our model with train set: ###Code from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train) LR ###Output _____no_output_____ ###Markdown Now we can predict using our test set: ###Code yhat = LR.predict(X_test) yhat ###Output _____no_output_____ ###Markdown **predict_proba** returns estimates for all classes, ordered by the label of classes. So, the first column is the probability of class 1, P(Y=1|X), and second column is probability of class 0, P(Y=0|X): ###Code yhat_prob = LR.predict_proba(X_test) yhat_prob ###Output _____no_output_____ ###Markdown Evaluation jaccard indexLets try jaccard index for accuracy evaluation. we can define jaccard as the size of the intersection divided by the size of the union of two label sets. If the entire set of predicted labels for a sample strictly match with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0. ###Code from sklearn.metrics import jaccard_score jaccard_score(y_test, yhat,pos_label=0) ###Output _____no_output_____ ###Markdown confusion matrixAnother way of looking at accuracy of classifier is to look at **confusion matrix**. ###Code from sklearn.metrics import classification_report, confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') print(confusion_matrix(y_test, yhat, labels=[1,0])) # Compute confusion matrix cnf_matrix = confusion_matrix(y_test, yhat, labels=[1,0]) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plt.figure() plot_confusion_matrix(cnf_matrix, classes=['churn=1','churn=0'],normalize= False, title='Confusion matrix') ###Output Confusion matrix, without normalization [[ 6 9] [ 1 24]] ###Markdown Look at first row. The first row is for customers whose actual churn value in test set is 1.As you can calculate, out of 40 customers, the churn value of 15 of them is 1. And out of these 15, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. It means, for 6 customers, the actual churn value were 1 in test set, and classifier also correctly predicted those as 1. However, while the actual label of 9 customers were 1, the classifier predicted those as 0, which is not very good. We can consider it as error of the model for first row.What about the customers with churn value 0? Lets look at the second row.It looks like there were 25 customers whom their churn value were 0. The classifier correctly predicted 24 of them as 0, and one of them wrongly as 1. So, it has done a good job in predicting the customers with churn value 0. A good thing about confusion matrix is that shows the model’s ability to correctly predict or separate the classes. In specific case of binary classifier, such as this example, we can interpret these numbers as the count of true positives, false positives, true negatives, and false negatives. ###Code print (classification_report(y_test, yhat)) ###Output precision recall f1-score support 0 0.73 0.96 0.83 25 1 0.86 0.40 0.55 15 accuracy 0.75 40 macro avg 0.79 0.68 0.69 40 weighted avg 0.78 0.75 0.72 40 ###Markdown Based on the count of each section, we can calculate precision and recall of each label:- **Precision** is a measure of the accuracy provided that a class label has been predicted. It is defined by: precision = TP / (TP + FP)- **Recall** is true positive rate. It is defined as: Recall =  TP / (TP + FN)So, we can calculate precision and recall of each class.**F1 score:**Now we are in the position to calculate the F1 scores for each label based on the precision and recall of that label. The F1 score is the harmonic average of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0. It is a good way to show that a classifer has a good value for both recall and precision.And finally, we can tell the average accuracy for this classifier is the average of the F1-score for both labels, which is 0.72 in our case. log lossNow, lets try **log loss** for evaluation. In logistic regression, the output can be the probability of customer churn is yes (or equals to 1). This probability is a value between 0 and 1.Log loss( Logarithmic loss) measures the performance of a classifier where the predicted output is a probability value between 0 and 1. ###Code from sklearn.metrics import log_loss log_loss(y_test, yhat_prob) ###Output _____no_output_____ ###Markdown PracticeTry to build Logistic Regression model again for the same dataset, but this time, use different __solver__ and __regularization__ values? What is new __logLoss__ value? ###Code # write your code here ###Output _____no_output_____
notebooks/1.0-tom-ca-data-exploration.ipynb
###Markdown Integrating and Exploring the Combined MSI Dataset for California Capstone - Fall 2020 TP Goter - September 20, 2020This notebook is used to integrate the individual, serialized dataframes. First we explore the metadata to get some descriptive statistics about our model. Then we process that actual data into a TensorFlow data object for future use in training neural networks. ###Code import pandas as pd import tensorflow as tf from glob import glob import os from matplotlib import pyplot as plt %matplotlib inline import numpy as np from tqdm import tqdm from google.colab import drive import seaborn as sns from matplotlib.cm import get_cmap import folium print(pd.__version__) print(tf.__version__) sns.set() ###Output 1.0.5 2.3.0 ###Markdown Mount Google DriveAuthentication Required ###Code drive.mount('/content/gdrive') ###Output Mounted at /content/gdrive ###Markdown Set Paths to DataData is actually kept in a folder shared with me. In order to access it from Colab, I added a shortcut to the Shared Folder to my 'My Drive' folder on Google Drive. A link is created that allows me to create the path below to get to the actual data without having to copy it back to my personal drive. ###Code base_path = '/content/gdrive/My Drive/Capstone Project' sentinel_path = os.path.join(base_path, 'Sentinel_CA/Level1C') ###Output _____no_output_____ ###Markdown Gather Serialzed DataFramesGet a list of all the pkl files we need to process ###Code pkl_dfs = [pdf for pdf in os.listdir(sentinel_path) if '.pkl' == pdf[-4:]] print(len(pkl_dfs)) pkl_dfs ###Output 60 ###Markdown Read MetadataFirst we will explore some metadata. We cannot read the totality of our dataframes in at once because we are RAM limited. So we will do it in steps. The data is still uploading to Google Drive, so let's just get the infrastructure in place first. ###Code # Make sure the dataframe is deleted before trying to read in each of the individual dataframes if 'total_df' in locals(): del total_df # Instantiate a list to contain individual dataframes dfs = [] # Loop over our pickle files for pdf in tqdm(pkl_dfs): # Read in each pickle file but drop the MSI data and the predictions to fit within memory limitations dfs.append(pd.read_pickle(os.path.join(sentinel_path, pdf)).drop(['msi', 'predictions'], axis=1)) # Concatenate the dataframes togethers total_df = pd.concat(dfs).reset_index(drop=True) # Delete the list of dataframes to save memory del dfs # High Level Statistics total_df.describe() ###Output _____no_output_____ ###Markdown Function for Summarizing Key Statistics- Land area of California from [Brittanica](https://www.britannica.com/place/California-state)- Cropland area from [California Department of Food and Agriculture](https://www.cdfa.ca.gov/statistics/PDFs/2018-2019AgReportnass.pdf)- 2013 Estimate of Irrigated Cropland in CA from [Federation of American Scientists](https://fas.org/sgp/crs/misc/R44093.pdf) ###Code def summarize_metadata(df): ''' ''' MONTHS = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'} CMAP = get_cmap('tab20').colors CALIFORNIA_AREA = 423967 # square kms CALIFORNIA_CROPLAND = 6.75e7 / 640 * 2.59 # acres to sq miles to sq kms CALIFORNIA_IRRIGATED_AREA = 7.9e6 / 640 * 2.59 # acres to sq miles to sq kms # Number of images - each image exists for 11 or 12 months of 2018 num_imgs = len(df) # Each image is 100 x 100 pixels # Each base image is 1164 x 929 pixels # There are 99 small images per base image # Thus, we use 0.9155 of the base image # At our latitude and longitude the 0.25 x 0.25 degree region # is about 616.55 km2 # June present for all images unique_area = 616.55*0.9155 / 99 * len(df[df.month==6]) # Calculate percent of land in sample that is irrigated irrigated_area = df.tot_irr_locs.sum() / (num_imgs * 100 * 100) print(10*'*' + 'SUMMARY' + 10*'*') print(f'Number of 100x100 10-channel "images" to process:\t{num_imgs}') print(f'Total Land Area in California:\t\t\t\t{CALIFORNIA_AREA} sq. km') print(f'Total Cropland Area in California:\t\t\t{CALIFORNIA_CROPLAND:.0f} sq. km') print(f'Area Covered in Images:\t\t\t\t\t{unique_area} sq. km') print(f'Fraction of California Area Covered in Images:\t\t{unique_area / CALIFORNIA_AREA:.3f} ') print(f'Fraction of Sample Irrigated:\t\t\t\t{irrigated_area:.3f} ') print(f'Estimated Irrigated Fraction of Land In California:\t{CALIFORNIA_IRRIGATED_AREA/CALIFORNIA_AREA:.3f}') print(2*'\n') # Generate Plot of Irrigated Land Fraction by Month avg_irr_by_month = total_df.groupby(['month']).tot_irr_locs.mean() fig, ax = plt.subplots(1,1, figsize=(10,5)) ax.bar(x=[MONTHS[m] for m in avg_irr_by_month.index], height=avg_irr_by_month.values/10000, color=CMAP, edgecolor='black') ax.set_xticklabels([MONTHS[m] for m in avg_irr_by_month.index], rotation=45, fontsize=11,fontweight='bold') ax.set_yticklabels([f'{n:.2f}' for n in np.arange(0.0,0.18,0.02)], fontsize=11,fontweight='bold') ax.set_title('Mean Fraction of Land Irrigated by Month',fontsize=16,fontweight='bold') print(2*'\n') # Histogram of Irrigated Locations by Month irr_by_month = total_df.groupby(['month']).tot_irr_locs fig, axes = plt.subplots(2,6,figsize=(20,10), sharex=True, sharey=True) axes = axes.flatten() for g, group in irr_by_month: group = group / 10000 group.hist(ax=axes[g-1], bins=20, color='tab:green', ec='black') axes[g-1].set_title(f'{MONTHS[g]}', fontweight='bold', fontsize=11) plt.tight_layout() plt.suptitle('Distribution of Irrigated Fraction by Month', y=1.02, fontsize=16, fontweight='bold') ###Output _____no_output_____ ###Markdown Top Level Summary ###Code summarize_metadata(total_df) # Create interactive map with default basemap map_osm = folium.Map( location=[total_df.lat.median(), total_df.lon.median()], zoom_start=8, tiles='Stamen Terrain' ) centers = total_df.groupby(['lat']).lon.unique() month_counts = total_df.groupby(['lat']).month.unique() for l, lat in enumerate(centers.index): for lon in centers[l]: folium.Rectangle( bounds=[(float(lat)-0.125, float(lon)-0.125), (float(lat)+0.125, float(lon)+0.125)], popup=f'{lat}, {lon}\n{len(month_counts[l])} months', color='#708090', fill=True, fill_color='#708090' ).add_to(map_osm) map_osm ###Output _____no_output_____
video_notebooks/05_pytorch_going_modular_cell_mode_video.ipynb
###Markdown 05. Going Modular: Part 1 (cell mode)This notebook is part 1/2 of section [05. Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).For reference, the two parts are: 1. [**05. Going Modular: Part 1 (cell mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_cell_mode.ipynb) - this notebook is run as a traditional Jupyter Notebook/Google Colab notebook and is a condensed version of [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/).2. [**05. Going Modular: Part 2 (script mode)**](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/05_pytorch_going_modular_script_mode.ipynb) - this notebook is the same as number 1 but with added functionality to turn each of the major sections into Python scripts, such as, `data_setup.py` and `train.py`. Why two parts?Because sometimes the best way to learn something is to see how it *differs* from something else.If you run each notebook side-by-side you'll see how they differ and that's where the key learnings are. What is cell mode?A cell mode notebook is a regular notebook run exactly how we've been running them through the course.Some cells contain text and others contain code. What's the difference between this notebook (Part 1) and the script mode notebook (Part 2)?This notebook, 05. PyTorch Going Modular: Part 1 (cell mode), runs a cleaned up version of the most useful code from section [04. PyTorch Custom Datasets](https://www.learnpytorch.io/04_pytorch_custom_datasets/).Running this notebook end-to-end will result in recreating the image classification model we built in notebook 04 (TinyVGG) trained on images of pizza, steak and sushi.The main difference between this notebook (Part 1) and Part 2 is that each section in Part 2 (script mode) has an extra subsection (e.g. 2.1, 3.1, 4.1) for turning cell code into script code. Where can you get help?You can find the book version of this section [05. PyTorch Going Modular on learnpytorch.io](https://www.learnpytorch.io/05_pytorch_going_modular/).The rest of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. 0. Running a notebook in cell modeAs discussed, we're going to be running this notebook normally.One cell at a time.The code is from notebook 04, however, it has been condensed down to its core functionality. 1. Get dataWe're going to start by downloading the same data we used in [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/1-get-data), the `pizza_steak_sushi` dataset with images of pizza, steak and sushi. ###Code import os import zipfile from pathlib import Path import requests # Setup path to data folder data_path = Path("data/") image_path = data_path / "pizza_steak_sushi" # If the image folder doesn't exist, download it and prepare it... if image_path.is_dir(): print(f"{image_path} directory exists.") else: print(f"Did not find {image_path} directory, creating one...") image_path.mkdir(parents=True, exist_ok=True) # Download pizza, steak, sushi data with open(data_path / "pizza_steak_sushi.zip", "wb") as f: request = requests.get("https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip") print("Downloading pizza, steak, sushi data...") f.write(request.content) # Unzip pizza, steak, sushi data with zipfile.ZipFile(data_path / "pizza_steak_sushi.zip", "r") as zip_ref: print("Unzipping pizza, steak, sushi data...") zip_ref.extractall(image_path) # Remove zip file os.remove(data_path / "pizza_steak_sushi.zip") # Setup train and testing paths train_dir = image_path / "train" test_dir = image_path / "test" train_dir, test_dir ###Output _____no_output_____ ###Markdown 2. Create Datasets and DataLoadersNow we'll turn the image dataset into PyTorch `Dataset`'s and `DataLoader`'s. ###Code from torchvision import datasets, transforms # Create simple transform data_transform = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), ]) # Use ImageFolder to create dataset(s) train_data = datasets.ImageFolder(root=train_dir, # target folder of images transform=data_transform, # transforms to perform on data (images) target_transform=None) # transforms to perform on labels (if necessary) test_data = datasets.ImageFolder(root=test_dir, transform=data_transform) print(f"Train data:\n{train_data}\nTest data:\n{test_data}") # Get class names as a list class_names = train_data.classes class_names # Can also get class names as a dict class_dict = train_data.class_to_idx class_dict # Check the lengths len(train_data), len(test_data) # Turn train and test Datasets into DataLoaders from torch.utils.data import DataLoader train_dataloader = DataLoader(dataset=train_data, batch_size=1, # how many samples per batch? num_workers=1, # how many subprocesses to use for data loading? (higher = more) shuffle=True) # shuffle the data? test_dataloader = DataLoader(dataset=test_data, batch_size=1, num_workers=1, shuffle=False) # don't usually need to shuffle testing data train_dataloader, test_dataloader # Check out single image size/shape img, label = next(iter(train_dataloader)) # Batch size will now be 1, try changing the batch_size parameter above and see what happens print(f"Image shape: {img.shape} -> [batch_size, color_channels, height, width]") print(f"Label shape: {label.shape}") ###Output Image shape: torch.Size([1, 3, 64, 64]) -> [batch_size, color_channels, height, width] Label shape: torch.Size([1]) ###Markdown 2.1 Create Datasets and DataLoaders (script mode) Let's use the Jupyter magic function to create a `.py` file for creating DataLoaders. We can save a code cell's contents to a file using the Jupyter magic `%%writefile filename` - https://ipython.readthedocs.io/en/stable/interactive/magics.htmlcellmagic-writefile ###Code # Create a directory going_modular scripts import os os.makedirs("going_modular") %%writefile going_modular/data_setup.py """ Contains functionality for creating PyTorch DataLoader's for image classification data. """ import os from torchvision import datasets, transforms from torch.utils.data import DataLoader NUM_WORKERS = os.cpu_count() def create_dataloaders( train_dir: str, test_dir: str, transform: transforms.Compose, batch_size: int, num_workers: int=NUM_WORKERS ): """Creates training and testing DataLoaders. Takes in a training directory and testing directroy path and turns them into PyTorch Datasets and then into PyTorch DataLoaders. Args: train_dir: Path to training directory. test_dir: Path to testing directory. transform: torchvision transforms to perform on training and testing data. batch_size: Number of samples per batch in each of the DataLoaders. num_workers: An integer for number of workers per DataLoader. Returns: A tuple of (train_dataloader, test_dataloader, class_names). Where class_names is a list of the target classes. Example usage: train_dataloader, test_dataloader, class_names = create_dataloaders(train_dir=path/to/train_dir, test_dir=path/to/test_dir, transform=some_transform, batch_size=32, num_workers=4) """ # Use ImageFolder to create datasets(s) train_data = datasets.ImageFolder(train_dir, transform=transform) test_data = datasets.ImageFolder(test_dir, transform=transform) # Get class names class_names = train_data.classes # Turn images into DataLoaders train_dataloader = DataLoader( train_data, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True # for more on pin memory, see the PyTorch docs: https://pytorch.org/docs/stable/data.html ) test_dataloader = DataLoader( test_data, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True ) return train_dataloader, test_dataloader, class_names from going_modular import data_setup train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir, test_dir=test_dir, transform=data_transform, batch_size=32) train_dataloader, test_dataloader, class_names ###Output _____no_output_____ ###Markdown 3. Making a model (TinyVGG)We're going to use the same model we used in notebook 04: TinyVGG from the CNN Explainer website.The only change here from notebook 04 is that a docstring has been added using [Google's Style Guide for Python](https://google.github.io/styleguide/pyguide.html384-classes). ###Code import torch from torch import nn class TinyVGG(nn.Module): """Creates the TinyVGG architecture. Replicates the TinyVGG architecture from the CNN explainer website in PyTorch. See the original architecture here: https://poloclub.github.io/cnn-explainer/ Args: input_shape: An integer indicating number of input channels. hidden_units: An integer indicating number of hidden units between layers. output_shape: An integer indicating number of output units. """ def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None: super().__init__() self.conv_block_1 = nn.Sequential( nn.Conv2d(in_channels=input_shape, out_channels=hidden_units, kernel_size=3, # how big is the square that's going over the image? stride=1, # default padding=0), # options = "valid" (no padding) or "same" (output has same shape as input) or int for specific number nn.ReLU(), nn.Conv2d(in_channels=hidden_units, out_channels=hidden_units, kernel_size=3, stride=1, padding=0), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) # default stride value is same as kernel_size ) self.conv_block_2 = nn.Sequential( nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0), nn.ReLU(), nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0), nn.ReLU(), nn.MaxPool2d(2) ) self.classifier = nn.Sequential( nn.Flatten(), # Where did this in_features shape come from? # It's because each layer of our network compresses and changes the shape of our inputs data. nn.Linear(in_features=hidden_units*13*13, out_features=output_shape) ) def forward(self, x: torch.Tensor): x = self.conv_block_1(x) x = self.conv_block_2(x) x = self.classifier(x) return x # return self.classifier(self.block_2(self.block_1(x))) # <- leverage the benefits of operator fusion import torch device = "cuda" if torch.cuda.is_available() else "cpu" # Instantiate an instance of the model torch.manual_seed(42) model_0 = TinyVGG(input_shape=3, # number of color channels (3 for RGB) hidden_units=10, output_shape=len(train_data.classes)).to(device) model_0 ###Output _____no_output_____ ###Markdown To test our model let's do a single forward pass (pass a sample batch from the training set through our model). ###Code # 1. Get a batch of images and labels from the DataLoader img_batch, label_batch = next(iter(train_dataloader)) # 2. Get a single image from the batch and unsqueeze the image so its shape fits the model img_single, label_single = img_batch[0].unsqueeze(dim=0), label_batch[0] print(f"Single image shape: {img_single.shape}\n") # 3. Perform a forward pass on a single image model_0.eval() with torch.inference_mode(): pred = model_0(img_single.to(device)) # 4. Print out what's happening and convert model logits -> pred probs -> pred label print(f"Output logits:\n{pred}\n") print(f"Output prediction probabilities:\n{torch.softmax(pred, dim=1)}\n") print(f"Output prediction label:\n{torch.argmax(torch.softmax(pred, dim=1), dim=1)}\n") print(f"Actual label:\n{label_single}") ###Output Single image shape: torch.Size([1, 3, 64, 64]) Output logits: tensor([[ 0.0208, -0.0019, 0.0095]], device='cuda:0') Output prediction probabilities: tensor([[0.3371, 0.3295, 0.3333]], device='cuda:0') Output prediction label: tensor([0], device='cuda:0') Actual label: 0 ###Markdown 3.1. Making a model (TinyVGG) with a script (`model_builder.py`)Let's turn our model building code into a Python script we can import. ###Code %%writefile going_modular/model_builder.py """ Contains PyTorch model code to instantiate a TinyVGG model from the CNN Explainer website. """ import torch from torch import nn class TinyVGG(nn.Module): """Creates the TinyVGG architecture. Replicates the TinyVGG architecture from the CNN explainer website in PyTorch. See the original architecture here: https://poloclub.github.io/cnn-explainer/ Args: input_shape: An integer indicating number of input channels. hidden_units: An integer indicating number of hidden units between layers. output_shape: An integer indicating number of output units. """ def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None: super().__init__() self.conv_block_1 = nn.Sequential( nn.Conv2d(in_channels=input_shape, out_channels=hidden_units, kernel_size=3, # how big is the square that's going over the image? stride=1, # default padding=0), # options = "valid" (no padding) or "same" (output has same shape as input) or int for specific number nn.ReLU(), nn.Conv2d(in_channels=hidden_units, out_channels=hidden_units, kernel_size=3, stride=1, padding=0), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) # default stride value is same as kernel_size ) self.conv_block_2 = nn.Sequential( nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0), nn.ReLU(), nn.Conv2d(hidden_units, hidden_units, kernel_size=3, padding=0), nn.ReLU(), nn.MaxPool2d(2) ) self.classifier = nn.Sequential( nn.Flatten(), # Where did this in_features shape come from? # It's because each layer of our network compresses and changes the shape of our inputs data. nn.Linear(in_features=hidden_units*13*13, out_features=output_shape) ) def forward(self, x: torch.Tensor): x = self.conv_block_1(x) x = self.conv_block_2(x) x = self.classifier(x) return x # return self.classifier(self.block_2(self.block_1(x))) # <- leverage the benefits of operator fusion from going_modular import model_builder import torch from going_modular import model_builder device = "cuda" if torch.cuda.is_available() else "cpu" # Instantiate a model from the model_builder.py script torch.manual_seed(42) model_1 = model_builder.TinyVGG(input_shape=3, hidden_units=10, output_shape=len(class_names)).to(device) model_1 # 1. Get a batch of images and labels from the DataLoader img_batch, label_batch = next(iter(train_dataloader)) # 2. Get a single image from the batch and unsqueeze the image so its shape fits the model img_single, label_single = img_batch[0].unsqueeze(dim=0), label_batch[0] print(f"Single image shape: {img_single.shape}\n") # 3. Perform a forward pass on a single image model_1.eval() with torch.inference_mode(): pred = model_1(img_single.to(device)) # 4. Print out what's happening and convert model logits -> pred probs -> pred label print(f"Output logits:\n{pred}\n") print(f"Output prediction probabilities:\n{torch.softmax(pred, dim=1)}\n") print(f"Output prediction label:\n{torch.argmax(torch.softmax(pred, dim=1), dim=1)}\n") print(f"Actual label:\n{label_single}") ###Output Single image shape: torch.Size([1, 3, 64, 64]) Output logits: tensor([[ 0.0208, -0.0019, 0.0095]], device='cuda:0') Output prediction probabilities: tensor([[0.3371, 0.3295, 0.3333]], device='cuda:0') Output prediction label: tensor([0], device='cuda:0') Actual label: 0 ###Markdown 4. Creating `train_step()` and `test_step()` functions and `train()` to combine them Rather than writing them again, we can reuse the `train_step()` and `test_step()` functions from [notebook 04](https://www.learnpytorch.io/04_pytorch_custom_datasets/75-create-train-test-loop-functions).The same goes for the `train()` function we created.The only difference here is that these functions have had docstrings added to them in [Google's Python Functions and Methods Style Guide](https://google.github.io/styleguide/pyguide.html383-functions-and-methods).Let's start by making `train_step()`. ###Code from typing import Tuple def train_step(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, loss_fn: torch.nn.Module, optimizer: torch.optim.Optimizer, device: torch.device) -> Tuple[float, float]: """Trains a PyTorch model for a single epoch. Turns a target PyTorch model to training mode and then runs through all of the required training steps (forward pass, loss calculation, optimizer step). Args: model: A PyTorch model to be trained. dataloader: A DataLoader instance for the model to be trained on. loss_fn: A PyTorch loss function to minimize. optimizer: A PyTorch optimizer to help minimize the loss function. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A tuple of training loss and training accuracy metrics. In the form (train_loss, train_accuracy). For example: (0.1112, 0.8743) """ # Put model in train mode model.train() # Setup train loss and train accuracy values train_loss, train_acc = 0, 0 # Loop through data loader data batches for batch, (X, y) in enumerate(dataloader): # Send data to target device X, y = X.to(device), y.to(device) # 1. Forward pass y_pred = model(X) # 2. Calculate and accumulate loss loss = loss_fn(y_pred, y) train_loss += loss.item() # 3. Optimizer zero grad optimizer.zero_grad() # 4. Loss backward loss.backward() # 5. Optimizer step optimizer.step() # Calculate and accumulate accuracy metric across all batches y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1) train_acc += (y_pred_class == y).sum().item()/len(y_pred) # Adjust metrics to get average loss and accuracy per batch train_loss = train_loss / len(dataloader) train_acc = train_acc / len(dataloader) return train_loss, train_acc ###Output _____no_output_____ ###Markdown Now we'll do `test_step()`. ###Code def test_step(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, loss_fn: torch.nn.Module, device: torch.device) -> Tuple[float, float]: """Tests a PyTorch model for a single epoch. Turns a target PyTorch model to "eval" mode and then performs a forward pass on a testing dataset. Args: model: A PyTorch model to be tested. dataloader: A DataLoader instance for the model to be tested on. loss_fn: A PyTorch loss function to calculate loss on the test data. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A tuple of testing loss and testing accuracy metrics. In the form (test_loss, test_accuracy). For example: (0.0223, 0.8985) """ # Put model in eval mode model.eval() # Setup test loss and test accuracy values test_loss, test_acc = 0, 0 # Turn on inference context manager with torch.inference_mode(): # Loop through DataLoader batches for batch, (X, y) in enumerate(dataloader): # Send data to target device X, y = X.to(device), y.to(device) # 1. Forward pass test_pred_logits = model(X) # 2. Calculate and accumulate loss loss = loss_fn(test_pred_logits, y) test_loss += loss.item() # Calculate and accumulate accuracy test_pred_labels = test_pred_logits.argmax(dim=1) test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels)) # Adjust metrics to get average loss and accuracy per batch test_loss = test_loss / len(dataloader) test_acc = test_acc / len(dataloader) return test_loss, test_acc ###Output _____no_output_____ ###Markdown And we'll combine `train_step()` and `test_step()` into `train()`. ###Code from typing import Dict, List from tqdm.auto import tqdm def train(model: torch.nn.Module, train_dataloader: torch.utils.data.DataLoader, test_dataloader: torch.utils.data.DataLoader, optimizer: torch.optim.Optimizer, loss_fn: torch.nn.Module, epochs: int, device: torch.device) -> Dict[str, List[float]]: """Trains and tests a PyTorch model. Passes a target PyTorch models through train_step() and test_step() functions for a number of epochs, training and testing the model in the same epoch loop. Calculates, prints and stores evaluation metrics throughout. Args: model: A PyTorch model to be trained and tested. train_dataloader: A DataLoader instance for the model to be trained on. test_dataloader: A DataLoader instance for the model to be tested on. optimizer: A PyTorch optimizer to help minimize the loss function. loss_fn: A PyTorch loss function to calculate loss on both datasets. epochs: An integer indicating how many epochs to train for. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A dictionary of training and testing loss as well as training and testing accuracy metrics. Each metric has a value in a list for each epoch. In the form: {train_loss: [...], train_acc: [...], test_loss: [...], test_acc: [...]} For example if training for epochs=2: {train_loss: [2.0616, 1.0537], train_acc: [0.3945, 0.3945], test_loss: [1.2641, 1.5706], test_acc: [0.3400, 0.2973]} """ # Create empty results dictionary results = {"train_loss": [], "train_acc": [], "test_loss": [], "test_acc": [] } # Loop through training and testing steps for a number of epochs for epoch in tqdm(range(epochs)): train_loss, train_acc = train_step(model=model, dataloader=train_dataloader, loss_fn=loss_fn, optimizer=optimizer, device=device) test_loss, test_acc = test_step(model=model, dataloader=test_dataloader, loss_fn=loss_fn, device=device) # Print out what's happening print( f"Epoch: {epoch+1} | " f"train_loss: {train_loss:.4f} | " f"train_acc: {train_acc:.4f} | " f"test_loss: {test_loss:.4f} | " f"test_acc: {test_acc:.4f}" ) # Update results dictionary results["train_loss"].append(train_loss) results["train_acc"].append(train_acc) results["test_loss"].append(test_loss) results["test_acc"].append(test_acc) # Return the filled results at the end of the epochs return results ###Output _____no_output_____ ###Markdown 4.1 Turn training functions into a script (`engine.py`) ###Code %%writefile going_modular/engine.py """ Contains functions for training and testing a PyTorch model. """ from typing import Dict, List, Tuple import torch from tqdm.auto import tqdm def train_step(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, loss_fn: torch.nn.Module, optimizer: torch.optim.Optimizer, device: torch.device) -> Tuple[float, float]: """Trains a PyTorch model for a single epoch. Turns a target PyTorch model to training mode and then runs through all of the required training steps (forward pass, loss calculation, optimizer step). Args: model: A PyTorch model to be trained. dataloader: A DataLoader instance for the model to be trained on. loss_fn: A PyTorch loss function to minimize. optimizer: A PyTorch optimizer to help minimize the loss function. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A tuple of training loss and training accuracy metrics. In the form (train_loss, train_accuracy). For example: (0.1112, 0.8743) """ # Put model in train mode model.train() # Setup train loss and train accuracy values train_loss, train_acc = 0, 0 # Loop through data loader data batches for batch, (X, y) in enumerate(dataloader): # Send data to target device X, y = X.to(device), y.to(device) # 1. Forward pass y_pred = model(X) # 2. Calculate and accumulate loss loss = loss_fn(y_pred, y) train_loss += loss.item() # 3. Optimizer zero grad optimizer.zero_grad() # 4. Loss backward loss.backward() # 5. Optimizer step optimizer.step() # Calculate and accumulate accuracy metric across all batches y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1) train_acc += (y_pred_class == y).sum().item()/len(y_pred) # Adjust metrics to get average loss and accuracy per batch train_loss = train_loss / len(dataloader) train_acc = train_acc / len(dataloader) return train_loss, train_acc def test_step(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, loss_fn: torch.nn.Module, device: torch.device) -> Tuple[float, float]: """Tests a PyTorch model for a single epoch. Turns a target PyTorch model to "eval" mode and then performs a forward pass on a testing dataset. Args: model: A PyTorch model to be tested. dataloader: A DataLoader instance for the model to be tested on. loss_fn: A PyTorch loss function to calculate loss on the test data. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A tuple of testing loss and testing accuracy metrics. In the form (test_loss, test_accuracy). For example: (0.0223, 0.8985) """ # Put model in eval mode model.eval() # Setup test loss and test accuracy values test_loss, test_acc = 0, 0 # Turn on inference context manager with torch.inference_mode(): # Loop through DataLoader batches for batch, (X, y) in enumerate(dataloader): # Send data to target device X, y = X.to(device), y.to(device) # 1. Forward pass test_pred_logits = model(X) # 2. Calculate and accumulate loss loss = loss_fn(test_pred_logits, y) test_loss += loss.item() # Calculate and accumulate accuracy test_pred_labels = test_pred_logits.argmax(dim=1) test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels)) # Adjust metrics to get average loss and accuracy per batch test_loss = test_loss / len(dataloader) test_acc = test_acc / len(dataloader) return test_loss, test_acc def train(model: torch.nn.Module, train_dataloader: torch.utils.data.DataLoader, test_dataloader: torch.utils.data.DataLoader, optimizer: torch.optim.Optimizer, loss_fn: torch.nn.Module, epochs: int, device: torch.device) -> Dict[str, List[float]]: """Trains and tests a PyTorch model. Passes a target PyTorch models through train_step() and test_step() functions for a number of epochs, training and testing the model in the same epoch loop. Calculates, prints and stores evaluation metrics throughout. Args: model: A PyTorch model to be trained and tested. train_dataloader: A DataLoader instance for the model to be trained on. test_dataloader: A DataLoader instance for the model to be tested on. optimizer: A PyTorch optimizer to help minimize the loss function. loss_fn: A PyTorch loss function to calculate loss on both datasets. epochs: An integer indicating how many epochs to train for. device: A target device to compute on (e.g. "cuda" or "cpu"). Returns: A dictionary of training and testing loss as well as training and testing accuracy metrics. Each metric has a value in a list for each epoch. In the form: {train_loss: [...], train_acc: [...], test_loss: [...], test_acc: [...]} For example if training for epochs=2: {train_loss: [2.0616, 1.0537], train_acc: [0.3945, 0.3945], test_loss: [1.2641, 1.5706], test_acc: [0.3400, 0.2973]} """ # Create empty results dictionary results = {"train_loss": [], "train_acc": [], "test_loss": [], "test_acc": [] } # Loop through training and testing steps for a number of epochs for epoch in tqdm(range(epochs)): train_loss, train_acc = train_step(model=model, dataloader=train_dataloader, loss_fn=loss_fn, optimizer=optimizer, device=device) test_loss, test_acc = test_step(model=model, dataloader=test_dataloader, loss_fn=loss_fn, device=device) # Print out what's happening print( f"Epoch: {epoch+1} | " f"train_loss: {train_loss:.4f} | " f"train_acc: {train_acc:.4f} | " f"test_loss: {test_loss:.4f} | " f"test_acc: {test_acc:.4f}" ) # Update results dictionary results["train_loss"].append(train_loss) results["train_acc"].append(train_acc) results["test_loss"].append(test_loss) results["test_acc"].append(test_acc) # Return the filled results at the end of the epochs return results from going_modular import engine # engine.train() ###Output _____no_output_____ ###Markdown 5. Creating a function to save the modelLet's setup a function to save our model to a directory. ###Code from pathlib import Path def save_model(model: torch.nn.Module, target_dir: str, model_name: str): """Saves a PyTorch model to a target directory. Args: model: A target PyTorch model to save. target_dir: A directory for saving the model to. model_name: A filename for the saved model. Should include either ".pth" or ".pt" as the file extension. Example usage: save_model(model=model_0, target_dir="models", model_name="05_going_modular_tingvgg_model.pth") """ # Create target directory target_dir_path = Path(target_dir) target_dir_path.mkdir(parents=True, exist_ok=True) # Create model save path assert model_name.endswith(".pth") or model_name.endswith(".pt"), "model_name should end with '.pt' or '.pth'" model_save_path = target_dir_path / model_name # Save the model state_dict() print(f"[INFO] Saving model to: {model_save_path}") torch.save(obj=model.state_dict(), f=model_save_path) ###Output _____no_output_____ ###Markdown 5.1 Create a file called `utils.py` with utility functions"utils" in Python is generally reserved for various utility functions.Right now we only have one utility function (`save_model()`) but... as our code grows we'll likely have more... ###Code %%writefile going_modular/utils.py """ File containing various utility functions for PyTorch model training. """ import torch from pathlib import Path def save_model(model: torch.nn.Module, target_dir: str, model_name: str): """Saves a PyTorch model to a target directory. Args: model: A target PyTorch model to save. target_dir: A directory for saving the model to. model_name: A filename for the saved model. Should include either ".pth" or ".pt" as the file extension. Example usage: save_model(model=model_0, target_dir="models", model_name="05_going_modular_tingvgg_model.pth") """ # Create target directory target_dir_path = Path(target_dir) target_dir_path.mkdir(parents=True, exist_ok=True) # Create model save path assert model_name.endswith(".pth") or model_name.endswith(".pt"), "model_name should end with '.pt' or '.pth'" model_save_path = target_dir_path / model_name # Save the model state_dict() print(f"[INFO] Saving model to: {model_save_path}") torch.save(obj=model.state_dict(), f=model_save_path) ###Output Overwriting going_modular/utils.py ###Markdown 6. Train, evaluate and save the modelLet's leverage the functions we've got above to train, test and save a model to file. ###Code # Set random seeds torch.manual_seed(42) torch.cuda.manual_seed(42) # Set number of epochs NUM_EPOCHS = 5 # Recreate an instance of TinyVGG model_0 = TinyVGG(input_shape=3, # number of color channels (3 for RGB) hidden_units=10, output_shape=len(train_data.classes)).to(device) # Setup loss function and optimizer loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(params=model_0.parameters(), lr=0.001) # Start the timer from timeit import default_timer as timer start_time = timer() # Train model_0 model_0_results = train(model=model_0, train_dataloader=train_dataloader, test_dataloader=test_dataloader, optimizer=optimizer, loss_fn=loss_fn, epochs=NUM_EPOCHS, device=device) # End the timer and print out how long it took end_time = timer() print(f"[INFO] Total training time: {end_time-start_time:.3f} seconds") # Save the model save_model(model=model_0, target_dir="models", model_name="05_going_modular_cell_mode_tinyvgg_model.pth") ###Output _____no_output_____ ###Markdown 6.1 Train, evaluate and save the model (script mode) -> `train.py`Let's create a file called `train.py` to leverage all of our other code scripts to train a PyTorch model.Essentially we want to replicate the functionality of notebook 04 in one line... ###Code %%writefile going_modular/train.py """ Trains a PyTorch image classification model using device-agnostic code. """ import os import torch from torchvision import transforms from timeit import default_timer as timer import data_setup, engine, model_builder, utils # Setup hyperparameters NUM_EPOCHS = 5 BATCH_SIZE = 32 HIDDEN_UNITS = 10 LEARNING_RATE = 0.001 # Setup directories train_dir = "data/pizza_steak_sushi/train" test_dir = "data/pizza_steak_sushi/test" # Setup device agnostic code device = "cuda" if torch.cuda.is_available() else "cpu" # Create transforms data_transform = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor() ]) # Create DataLoader's and get class_names train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir, test_dir=test_dir, transform=data_transform, batch_size=BATCH_SIZE) # Create model model = model_builder.TinyVGG(input_shape=3, hidden_units=HIDDEN_UNITS, output_shape=len(class_names)).to(device) # Setup loss and optimizer loss_fn = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE) # Start the timer start_time = timer() # Start training with help from engine.py engine.train(model=model, train_dataloader=train_dataloader, test_dataloader=test_dataloader, loss_fn=loss_fn, optimizer=optimizer, epochs=NUM_EPOCHS, device=device) # End the timer and print out how long it took end_time = timer() print(f"[INFO] Total training time: {end_time-start_time:.3f} seconds") # Save the model to file utils.save_model(model=model, target_dir="models", model_name="05_going_modular_script_mode_tinyvgg_model.pth") !python going_modular/train.py ###Output 0% 0/5 [00:00<?, ?it/s]Epoch: 1 | train_loss: 1.1019 | train_acc: 0.3203 | test_loss: 1.1089 | test_acc: 0.1979 20% 1/5 [00:01<00:06, 1.51s/it]Epoch: 2 | train_loss: 1.1055 | train_acc: 0.2930 | test_loss: 1.1385 | test_acc: 0.1979 40% 2/5 [00:02<00:04, 1.47s/it]Epoch: 3 | train_loss: 1.1128 | train_acc: 0.2930 | test_loss: 1.1272 | test_acc: 0.1979 60% 3/5 [00:04<00:02, 1.45s/it]Epoch: 4 | train_loss: 1.0973 | train_acc: 0.3906 | test_loss: 1.0982 | test_acc: 0.3021 80% 4/5 [00:05<00:01, 1.45s/it]Epoch: 5 | train_loss: 1.0959 | train_acc: 0.4141 | test_loss: 1.1004 | test_acc: 0.3125 100% 5/5 [00:07<00:00, 1.43s/it] [INFO] Total training time: 7.133 seconds [INFO] Saving model to: models/05_going_modular_script_mode_tinyvgg_model.pth
scripts/RegressaoImoveis.ipynb
###Markdown Modelo para cálculo de imóveis na cidade de São PauloO objetivo deste projeto é construir um modelo preditivo capaz de calcular o preço de um imóvel no bairro Paraíso na cidade de São Paulo. Para completar este projeto cada aluno deverá seguir as orientações que estão neste notebook e preencher as células vazias. Aquisição, pré-processamento e análise descritiva ###Code import pandas as pd import io import requests url="https://raw.githubusercontent.com/fbarth/ds-saint-paul/master/data/20140917_imoveis_filtrados_final.csv_shaped.csv" s=requests.get(url).content df = pd.read_csv(io.StringIO(s.decode('utf-8')), sep=",") df.head() %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt plt.subplots(figsize=(10, 8)) cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) ax = sns.scatterplot(x="area", y="preco", hue="suites", size="vagas", palette=cmap, sizes=(10, 200), data=df) ###Output _____no_output_____ ###Markdown * Listar a quantidade de imóveis por bairro existente no dataset ###Code # TODO: completar com o nome da variavel correta df['<PREENCHER>'].value_counts() ###Output _____no_output_____ ###Markdown * Considere apenas os imóveis do bairo paraiso ###Code # TODO: preencher com o nome do bairro correto df = df[df['bairro'] == '<PREENCHER>'] ###Output _____no_output_____ ###Markdown * Depois de considerar apenas os imóveis do bairro paraiso o tamanho do dataset precisa ser exatamente igual a (809,7) ###Code df.shape %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt plt.subplots(figsize=(10, 8)) cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) ax = sns.scatterplot(x="area", y="preco", hue="suites", size="vagas", palette=cmap, sizes=(10, 200), data=df) df.head() ###Output _____no_output_____ ###Markdown * A quantidade suites não pode ser maior que a quantidade de dormitórios e a quantidade de suites também não pode ser maior que a quantidade de banheiros. Exclua todos os exemplos que não satisfazem esta restrição. Estes exemplos provavelmente são erros de coleta de dados. ###Code # TODO: completar a regra df = df['COMPLETAR' <= df['dormitorios']] df = df['COMPLETAR' <= df['banheiros']] ###Output _____no_output_____ ###Markdown * Depois deste filtro o dataset precisa ter o tamanho (786, 7). ###Code df.shape %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt plt.subplots(figsize=(10, 8)) cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) ax = sns.scatterplot(x="area", y="preco", hue="suites", size="vagas", palette=cmap, sizes=(10, 200), data=df) ###Output _____no_output_____ ###Markdown * Visto que agora a variável bairro tem apenas um valor, você deve remover a mesma ###Code # TODO remover o atributo bairro df = df.drop(columns=['<PREENCHER>']) ###Output _____no_output_____ ###Markdown * Depois deste filtro o dataset precisa ter a seguinte estrutura: ###Code df.head() ###Output _____no_output_____ ###Markdown * Qual é o valor mínimo e máximo dos preços dos imóveis? ###Code # TODO completar com o nome correto do atributo x = df['<PREENCHER>'].describe() x df['preco'].plot(kind='hist', color='gray', title='Preço dos imóveis', rot=90) import seaborn as sns sns.pairplot(df) df.corr() ###Output _____no_output_____ ###Markdown * Qual é a informação que a tabela acima nos fornece? Divisão dos datasets ###Code df.head() ###Output _____no_output_____ ###Markdown * dividindo o dataset em 80% para treino e 20% para teste ###Code # neste código você precisa informar o percentual de exemplos que serão utilizados no teste percentual = #<PREENCHER> from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(df.iloc[:,1:6], df['preco'], test_size=percentual, random_state=4) x_train.head() ###Output _____no_output_____ ###Markdown Criação e avaliação do modelo preditivoCrie um modelo de regressão utilizando os algoritmos e transformações nos atributos que você considera mais adequados.Valide o modelo desenvolvido considerando os datasets X_test e y_test. Espera-se que o erro médio absoluto seja inferior a duzentos mil reais (R$ 200.000,00). Descreva nas células abaixo todas as etapas necessárias para o desenvolvimento e validação do modelo. Regressão Linear ###Code print(x_train.shape) print(y_train.shape) print(x_test.shape) from sklearn.linear_model import LinearRegression model = LinearRegression().fit(x_train, y_train) ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de treinamento ###Code predicted = model.predict(x_train) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_train, predicted) r2 = r2_score(y_train, predicted) mae = mean_absolute_error(y_train, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) ###Output rmse = % 150142973325.56418 r2 = % 0.8223876116718476 mae = % 265630.1450275685 ###Markdown * O erro médio absoluto está próximo do objetivo? ###Code resultado = pd.DataFrame({'real': y_train, 'predicted': predicted, 'diff': (y_train - predicted)}) resultado = pd.concat([x_train, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown * Qual é o significado do eixo Y deste gráfico? * Qual é o comportamento do erro no dataset de treinamento? Validação do modelo no conjunto de teste ###Code predicted = model.predict(x_test) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_test, predicted) r2 = r2_score(y_test, predicted) mae = mean_absolute_error(y_test, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) ###Output rmse = % 96552254398.05544 r2 = % 0.8343976815354153 mae = % 241653.09231124964 ###Markdown * O erro médio absoluto no conjunto de teste é similar ao erro médio absoluto no conjunto de treinamento? ###Code resultado = pd.DataFrame({'real': y_test, 'predicted': predicted, 'diff': (y_test - predicted)}) resultado = pd.concat([x_test, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Regressão Linear com transformação polinomial **Testar com degree igual a 2, 3, 4 e 8. Analisar possível overfitting** ###Code #Generate a new feature matrix consisting of all polynomial combinations #of the features with degree less than or equal to the specified degree. #For example, if an input sample is two dimensional and of the form [a, b], #the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. grau='<PREENCHER>' from sklearn.preprocessing import PolynomialFeatures transformer = PolynomialFeatures(degree=grau, include_bias=False) transformer.fit(x_train) train_ = transformer.transform(x_train) print(x_train.shape) print(train_.shape) ###Output (628, 5) (628, 1286) ###Markdown * Por que este dataset tem dimensões diferentes? ###Code from sklearn.linear_model import LinearRegression model = LinearRegression().fit(train_, y_train) ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de treinamento ###Code predicted = model.predict(train_) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_train, predicted) r2 = r2_score(y_train, predicted) mae = mean_absolute_error(y_train, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_train, 'predicted': predicted, 'diff': (y_train - predicted)}) resultado = pd.concat([x_train, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de teste * antes de usar a função predict, você precisa aplicar a mesma transformação feita sobre o dataset x_train no dataset x_test. Preste atenção que o nome da variável esperada é test_ ###Code transformer.fit(x_test) test_ = transformer.transform(x_test) predicted = model.predict(test_) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_test, predicted) r2 = r2_score(y_test, predicted) mae = mean_absolute_error(y_test, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) ###Output rmse = % 41182864009546.375 r2 = % -69.63509602661267 mae = % 1135967.8869046264 ###Markdown * A diferença do erro do conjunto de treinamento com o conjunto de testes foi muito diferente? O que aconteceu? ###Code resultado = pd.DataFrame({'real': y_test, 'predicted': predicted, 'diff': (y_test - predicted)}) resultado = pd.concat([x_test, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Random Forest sem modificação adicional de atributos e modificando apenas a quantidade de árvores ###Code from sklearn.ensemble import RandomForestRegressor results = pd.DataFrame(columns=['estimators','r2']) for i in range(100, 5000, 100): clf = RandomForestRegressor(n_estimators=i, max_depth=None, random_state=4, oob_score=True) clf.fit(x_train, y_train) results = results.append({'estimators':i, 'r2': clf.oob_score_}, ignore_index=True) ax = results.plot(x='estimators', y='r2') ax.set_title('Relação R2 com a quantidade de árvores utilizadas no modelo RandomForest') ###Output _____no_output_____ ###Markdown * o modelo com 4900 árvores é o modelo com melhor $R^{2}$ ###Code clf = RandomForestRegressor(n_estimators=4900, max_depth=None, random_state=4, oob_score=True) ###Output _____no_output_____ ###Markdown * crie o modelo usando a função fit é os datasets x_train e y_train ###Code clf.fit(x_train, y_train) ###Output _____no_output_____ ###Markdown * Nível de importância dos atributos para o modelo preditivo: ###Code print(clf.oob_score_) print(clf.feature_importances_) print(x_train.columns) ###Output 0.8978754005039717 [0.33587576 0.18957595 0.01128215 0.01847831 0.44478783] Index(['area', 'suites', 'dormitorios', 'banheiros', 'vagas'], dtype='object') ###Markdown * Quais são os atributos que têm maior importância no modelo? Validação do modelo no conjunto de treinamento ###Code predicted = clf.predict(x_train) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_train, predicted) r2 = r2_score(y_train, predicted) mae = mean_absolute_error(y_train, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_train, 'predicted': predicted, 'diff': (y_train - predicted)}) resultado = pd.concat([x_train, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de teste * utilize a função predict para calcular os valores preditos considerando o dataset x_test ###Code predicted = clf.predict(x_test) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_test, predicted) r2 = r2_score(y_test, predicted) mae = mean_absolute_error(y_test, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_test, 'predicted': predicted, 'diff': (y_test - predicted)}) resultado = pd.concat([x_test, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Random Forest sem modificação adicional de atributos e com GridSearch ###Code from sklearn.model_selection import GridSearchCV param_grid = { 'n_estimators': [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000], 'max_features': ['sqrt', 'log2', 3, 4, 5], 'max_depth' : [2, 10, 20, 100, None] } rfc=RandomForestRegressor(random_state=4) CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 3, verbose=1, n_jobs=-1) CV_rfc.fit(x_train, y_train) CV_rfc.best_params_ clf2 = RandomForestRegressor(n_estimators=1000, max_features = 'sqrt', max_depth=10, random_state=4, oob_score=True) clf2.fit(x_train, y_train) print(clf2.oob_score_) print(clf2.feature_importances_) print(x_train.columns) ###Output 0.9042640694388276 [0.33767208 0.21645386 0.02002816 0.08581751 0.34002839] Index(['area', 'suites', 'dormitorios', 'banheiros', 'vagas'], dtype='object') ###Markdown Validação do modelo no conjunto de treinamento ###Code predicted = clf2.predict(x_train) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_train, predicted) r2 = r2_score(y_train, predicted) mae = mean_absolute_error(y_train, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_train, 'predicted': predicted, 'diff': (y_train - predicted)}) resultado = pd.concat([x_train, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de teste ###Code predicted = clf2.predict(x_test) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_test, predicted) r2 = r2_score(y_test, predicted) mae = mean_absolute_error(y_test, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_test, 'predicted': predicted, 'diff': (y_test - predicted)}) resultado = pd.concat([x_test, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Random Forest com transformacao polinomial ###Code from sklearn.preprocessing import PolynomialFeatures transformer = PolynomialFeatures(degree=3, include_bias=False) transformer.fit(x_train) train_ = transformer.transform(x_train) from sklearn.model_selection import GridSearchCV param_grid = { 'n_estimators': [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000], 'max_features': ['sqrt', 'log2', 3, 4, 5, 6], 'max_depth' : [2, 10, 20, 100, None] } rfc=RandomForestRegressor(random_state=4) CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 3, verbose=1, n_jobs=-1) CV_rfc.fit(train_, y_train) CV_rfc.best_params_ clf3 = RandomForestRegressor(n_estimators=100, max_features = 'sqrt', max_depth=20, random_state=4, oob_score=True) clf3.fit(train_, y_train) print(clf3.oob_score_) ###Output 0.895218562969256 ###Markdown Validação do modelo no dataset de treinamento ###Code predicted = clf3.predict(train_) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_train, predicted) r2 = r2_score(y_train, predicted) mae = mean_absolute_error(y_train, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_train, 'predicted': predicted, 'diff': (y_train - predicted)}) resultado = pd.concat([x_train, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Validação do modelo no conjunto de teste ###Code transformer.fit(x_test) test_ = transformer.transform(x_test) predicted = clf3.predict(test_) from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error rmse = mean_squared_error(y_test, predicted) r2 = r2_score(y_test, predicted) mae = mean_absolute_error(y_test, predicted) print('rmse = %', rmse) print('r2 = %', r2) print('mae = %', mae) resultado = pd.DataFrame({'real': y_test, 'predicted': predicted, 'diff': (y_test - predicted)}) resultado = pd.concat([x_test, resultado], axis=1) ax = resultado.plot(x='area', y='diff', kind='scatter') ax.set_title('Análise dos erros') ###Output _____no_output_____ ###Markdown Analisando os dois imóveis com erros altos no conjunto de teste ###Code temp = resultado[resultado['diff'] < -1000000] temp ###Output _____no_output_____
Notebooks/RepeticionTareas_Bucles.ipynb
###Markdown Repetición de tareas. Los buclesCon frecuencia es necesario repetir operaciones un número determinado de veces. Para eso en programaión se usan los bucles. En python se utilizan básicamente dos tipos de bucles: *for* y *while*. Bucles forSe utiliza el bucle for cuando sabemos de antemano cuántas veces hay que repetir un trozo de código. ###Code for i in range(10): x=i**3 print('Esta es la repetición nº', i, 'x=', x) ###Output Esta es la repetición nº 0 x= 0 Esta es la repetición nº 1 x= 1 Esta es la repetición nº 2 x= 8 Esta es la repetición nº 3 x= 27 Esta es la repetición nº 4 x= 64 Esta es la repetición nº 5 x= 125 Esta es la repetición nº 6 x= 216 Esta es la repetición nº 7 x= 343 Esta es la repetición nº 8 x= 512 Esta es la repetición nº 9 x= 729 ###Markdown En la función *range()* podemos especificar de qué número a qué número queremos que vaya. ###Code for i in range(12,23,3): print('Esta es la repetición nº', i) ###Output Esta es la repetición nº 12 Esta es la repetición nº 15 Esta es la repetición nº 18 Esta es la repetición nº 21 ###Markdown Podemos hacer iteraciones por los elementos de una lista teniendo en cuenta su posición en la lista. ###Code nombres=['sujeto1', 'sujeto2', 'sujeto3', 'sujeto4', 'sujeto5', 'sujeto6', 'sujeto7'] len(nombres) nombres=['sujeto1', 'sujeto2', 'sujeto3', 'sujeto4', 'sujeto5'] for i in range(len(nombres)): print(nombres[i]) ###Output sujeto1 sujeto2 sujeto3 sujeto4 sujeto5 ###Markdown Pero también podemos hacer iteraciones directamente sobre los elementos de la lista. ###Code nombres=['sujeto1', 'sujeto2', 'sujeto3', 'sujeto4', 'sujeto5'] for nom in nombres: print(nom) ###Output sujeto1 sujeto2 sujeto3 sujeto4 sujeto5 ###Markdown Por ejemplo, tenemos unos datos que corresponden a tiempos de vuelo y queremos calcular la altura en cada salto. Tenemos que repetir la misma ecuación en cada dato de la lista de tiempos de vuelo. Un bucle for nos simplifica la tarea. ###Code tv=[0.476, 0.381, 0.534, 0.486, 0.397] h=[] hh=[] g=9.8 for t in tv: h1=g*t**2/8 h.append(h1) #añade a la lista h un nuevo valor, el resultado de la operación hh.append(h[-1]*2) print(h) print(hh) ###Output [0.2775556, 0.17782222500000003, 0.3493161000000001, 0.2893401, 0.19307102500000003] [0.5551112, 0.35564445000000006, 0.6986322000000001, 0.5786802, 0.38614205000000007] ###Markdown También se pueden anidar bucles for: ###Code cols=3 filas=5 for h in range(cols): for i in range(filas): print('Columna ', h, ', fila ', i) ###Output Columna 0 , fila 0 Columna 0 , fila 1 Columna 0 , fila 2 Columna 0 , fila 3 Columna 0 , fila 4 Columna 1 , fila 0 Columna 1 , fila 1 Columna 1 , fila 2 Columna 1 , fila 3 Columna 1 , fila 4 Columna 2 , fila 0 Columna 2 , fila 1 Columna 2 , fila 2 Columna 2 , fila 3 Columna 2 , fila 4 ###Markdown Se pueden juntar bucles con condicionales. En este ejemplo se crean números aleatorios entre 0 y 1. Se comprueba si cada número es mayor o menor que 0.5, y en función de eso se redondea a 0 o a 1. ###Code import numpy as np numTiradas=5 for i in range(numTiradas): x=np.random.rand() if x>=0.8: resultado=1.0 elif x>=0.3 and x<0.8: resultado=0.5 else: resultado=0.0 print('Aleatorio= {:.3f}, redondeado= {:.0f}'.format(x, resultado)) #de esta forma podemos controlar el nº de decimales de la cadena de texto ###Output Aleatorio= 0.619, redondeado= 0 Aleatorio= 0.760, redondeado= 0 Aleatorio= 0.700, redondeado= 0 Aleatorio= 0.751, redondeado= 0 Aleatorio= 0.821, redondeado= 1 ###Markdown Bucles WhileEl bucle while puede funcionar parecido al for, pero es más adecuado cuando no sabemos a priori cuántas veces hay que repetir un proceso. ###Code maximo=input('Introduce un número del 1 al 10:') maximo =int(maximo) x=0 while x<maximo: print(x) x=x+1 ###Output Introduce un número del 1 al 10:6 0 1 2 3 4 5 ###Markdown Ejemplo conociendo de antemano un listado.Queremos que busque de principio a final de la lista y se pare cuando encuentre un nº 7 dentro del listado. ###Code aleatorio=[3,5,6,5,4,7,6,8,7,6,5,6,7,9,2,3,2,6] contador=0 #variable de ayuda para contar cuántas veces repite el bucle while while aleatorio[contador]!=7: print(aleatorio[contador]) contador+=1 print('He encontrado un 7 en la posición ', contador) ###Output 3 5 6 5 4 He encontrado un 7 en la posición 5 ###Markdown EJERCICIOIntenta hacer lo mismo que en el ejemplo anterior, pero creando números aleatorios entre 0 y 100 y que pare cuando el número sea **>90** SOLUCIÓN ###Code import numpy as np #ejemplo para crear un nº entero aleatorio entre o y 100 np.random.randint(0,100) contador=0 x=np.random.randint(0,100) #ejemplo para crear un nº aleatorio entro 0 y 100 while x<=90: print(x) contador+=1 x=np.random.randint(0,100) print('Ha encontrado un nº > 90 en el intento ', contador+1) ###Output 4 Ha encontrado un nº > 90 en el intento 2 ###Markdown EJERCICIOIntenta recrear los primeros números de la secuencia de Fibonacci. La secuencia empieza con los números 0 y 1, y después va añadiendo números sumando los dos anteriores: 0, 1, 1, 2, 3, 5, 8,...Primero hazlo con los 10 primeros números, después deja que sea el usuario el que introduza cuántos primeros números.Intenta después incluir en el bucle que calcule el número áureo, que resulta de dividir dos números consecutivos de la secuencia. ###Code import numpy as np #La secuencia empieza con estos dos números en la lista secuencia=[0,1] ###Output _____no_output_____ ###Markdown SOLUCIÓN ###Code #SOLUCIÓN con bucle for import numpy as np secuencia=[0,1] for i in range(10): secuencia.append(secuencia[-2] + secuencia[-1]) print(secuencia) #SOLUCIÓN con bucle for calculando nº áureo import numpy as np iteraciones=input('Introduce el número de iteraciones:') iteraciones=int(iteraciones) secuencia=[0,1] numAureo=[] for i in range(iteraciones-1): secuencia.append(secuencia[-1]+secuencia[-2]) numAureo.append(secuencia[-1]/secuencia[-2]) print(secuencia) print(u'Número áureo calculado:', numAureo[-1]) print(u'Número teórico (1+raiz5)/2:', (1+np.sqrt(5))/2) #SOLUCIÓN con bucle while import numpy as np #La secuencia empieza con estos dos números en la lista secuencia=[0,1] iteraciones=10 numAureo=[] while len(secuencia)<iteraciones: secuencia.append(secuencia[-1]+secuencia[-2]) numAureo.append(secuencia[-1]/secuencia[-2]) print(secuencia) print(u'Número áureo calculado:', numAureo[-1]) print(u'Número teórico (1+raiz5)/2:', (1+np.sqrt(5))/2) ###Output [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Número áureo calculado: 1.619047619047619 Número teórico (1+raiz5)/2: 1.618033988749895 ###Markdown Para detener los bucles en cualquier momentoDentro de los bucles *for*, en cualquier momento se puede terminar el bucle y salirse de él completamente (con la instrucción *break*) o pasar a la siguiente iteración (*continue*) sin salirse del bucle. ###Code import numpy as np for i in range(30): x=np.random.rand() #crea un nº aleatorio de 0 a 1 if x>0.9: print('Encontrado un > 0.9 ',x,'al intento nº', i+1) break #probar quitar el break print('Nº de iteraciones totales hechas: ', i+1) ###Output Encontrado un > 0.9 0.9858699295178558 al intento nº 2 Nº de iteraciones totales hechas: 2 ###Markdown EJERCICIOBusca una letra concreta en las palabras de un texto. Con que esté una vez en una palabra ya la cuenta:Que guarde en una variable las palabras que tienen la 'a' y otra que las cuente. ###Code texto='En un lugar de la Mancha de cuyo nombre no quiero acordarme ...' texto=texto.split() #esto descompone el texto en palabras print(texto) aciertos=0 palabras_con_a=[] ###Output ['En', 'un', 'lugar', 'de', 'la', 'Mancha', 'de', 'cuyo', 'nombre', 'no', 'quiero', 'acordarme', '...'] ###Markdown SOLUCIÓN ###Code texto='En un lugar de la Mancha de cuyo nombre no quiero acordarme ...' texto=texto.split() #esto descompone el texto en palabras print(texto) aciertos=0 palabras_con_a=[] for palabra in texto: if 'a' in palabra: aciertos+=1 palabras_con_a.append(palabra) continue#con break se saldría al encontrar la primera palabra con 'a' print('Hay', aciertos, 'palabras que contienen la letra a') print('Las palabras con a son:', palabras_con_a) ###Output ['En', 'un', 'lugar', 'de', 'la', 'Mancha', 'de', 'cuyo', 'nombre', 'no', 'quiero', 'acordarme', '...'] Hay 4 palabras que contienen la letra a Las palabras con a son: ['lugar', 'la', 'Mancha', 'acordarme'] ###Markdown EJERCICIOTenemos unos datos de índice de masa corporal (BMI) y queremos que automáticamente decida la categoría en la que se encuentra. Hay que unir bucles y condicionales.Asumimos que bajo peso es un BMI 30 ###Code resultsBMI=[16.4, 25.3, 54.8, 29.5, 19.7, 23.6, 31.6, 18.1] nBajoPeso=0 #guardan cuántos ha encontrado de cada categoría nNormal=0 nObeso=0 ###Output _____no_output_____ ###Markdown SOLUCIÓN ###Code resultsBMI=[16.4, 25.3, 54.8, 29.5, 19.7, 23.6, 31.6, 18.1, 24.5, 12.5, 36,2] nBajoPeso=0 #guardan cuántos ha encontrado de cada categoría nNormal=0 nObeso=0 for bmi in resultsBMI: if bmi<18.5: nBajoPeso+=1 elif bmi>=30: nObeso+=1 else: nNormal+=1 print('Bajo peso=',nBajoPeso, 'Normal=', nNormal, 'Obeso=', nObeso) ###Output Bajo peso= 4 Normal= 5 Obeso= 3 ###Markdown EJERCICIOVamos a crear unos datos de altura en una población. Queremos sacar muestras aleatorias de esa población y comprobar cuánto se aleja la media de las muestras de la media de la población. ###Code import numpy as np import matplotlib.pyplot as plt #Crea una población np.random.seed(10) #fija la aleatoriedad por reproducibilidad, para que nos salgan a todos los mismos datos altura_poblacion = np.random.normal(170, 20, 150000) plt.hist(altura_poblacion) n=10 diferencia=[] #crea una muestra aleatoria de n sujetos cogidos de la población altura_muestra = np.random.choice(a= altura_poblacion, size=n) ###Output _____no_output_____ ###Markdown SOLUCIÓN ###Code import numpy as np import matplotlib.pyplot as plt #Crea una población np.random.seed(10) #fija la aleatoriedad por reproducibilidad altura_poblacion = np.random.normal(170, 20, 150000) n=15 #nº de sujetos por muestra n_muestras = 5 #probaremos con este nº de muestras diferencia=[] #crea una muestra aleatoria de n suJetos altura_muestra = np.random.choice(a= altura_poblacion, size=n) for i in range(n_muestras): altura_muestra = np.random.choice(a= altura_poblacion, size=n) #Presenta el histograma de la población plt.hist(altura_poblacion, color='b') plt.show() #Presenta el histograma de la muestra plt.hist(altura_muestra, color='r') plt.show() diferencia.append(altura_poblacion.mean()-altura_muestra.mean()) print('Media población= ', altura_poblacion.mean()) print('Media muestra=', altura_muestra.mean()) print('Diferencia medias=', altura_poblacion.mean()-altura_muestra.mean()) print('Todas las diferencias:',diferencia) ###Output _____no_output_____
notebooks/2.1.1-acmiyaguchi-graph-blocking.ipynb
###Markdown Spark Preprocessing ###Code from src.data.snap_import_user_projection import UnimodalUserProjection from pyspark.sql import SparkSession, functions as F spark = SparkSession.builder.getOrCreate() input_path = "data/processed/enwiki-meta-compact" model = UnimodalUserProjection(spark).extract(input_path).transform() spark.table("bipartite").cache() spark.table("bipartite").count() contribution_df = spark.sql(""" select *, n_users*(n_users-1)/2 as clique_edges from ( select article_id, edit_date, approx_count_distinct(user_id) as n_users from bipartite group by 1, 2 order by 3 desc ) """) contribution_df.cache() # number of article-block contribution_df.count() ( contribution_df .groupBy("n_users") .agg(F.expr("count(distinct article_id, edit_date) as n_cliques")) .orderBy(F.desc("n_users")) ).show() contribution_df.selectExpr("sum(clique_edges)").show() ( contribution_df .selectExpr( "min(n_users)", "max(n_users)", "percentile(n_users, 0.25)", "percentile(n_users, 0.5)", "percentile(n_users, 0.9)", "percentile(n_users, 0.99)", "percentile(n_users, 0.999)", "percentile(n_users, 0.9999)", "percentile(n_users, 0.99999)", "percentile(n_users, 0.999999)", ) ).show(truncate=False, vertical=True) ( contribution_df .selectExpr( "min(clique_edges)", "max(clique_edges)", "percentile(clique_edges, 0.25)", "percentile(clique_edges, 0.5)", "percentile(clique_edges, 0.75)", "percentile(clique_edges, 0.9)", "percentile(clique_edges, 0.99)", "percentile(clique_edges, 0.999)", "percentile(clique_edges, 0.9999)", "percentile(clique_edges, 0.99999)", "percentile(clique_edges, 0.999999)", ) ).show(truncate=False, vertical=True) # based on the degree distribution, how contribution_df.where("clique_edges <= 6").selectExpr("sum(clique_edges)").show() (10e6 * 12) / 1e9 # GB of edge space items = ( contribution_df .groupBy("n_users") .agg(F.expr("count(distinct article_id, edit_date) as n_cliques")) ).collect() import matplotlib.pyplot as plt import numpy as np n_users, n_cliques = zip(*[(r.n_users, r.n_cliques) for r in items]) plt.scatter(n_users, n_cliques) plt.xscale('log') plt.yscale('log') plt.xlabel("cliques of size k") plt.ylabel("number of cliques") plt.show() contribution_df.groupby().agg(F.expr('sum(n_users)')).show() import pandas as pd from scipy.stats import powerlaw import pyspark.sql.types as T schema = T.StructType([ T.StructField("a", T.DoubleType(), False), T.StructField("loc", T.DoubleType(), False), T.StructField("scale", T.DoubleType(), False), ]) @F.pandas_udf(schema, F.PandasUDFType.GROUPED_MAP) def powerlaw_fit(df): a, loc, scale = powerlaw.fit(df.n_users) return pd.DataFrame([(a, loc, scale)], columns=schema.names) ( contribution_df .select("n_users") .sample(0.1) .groupby() .apply(powerlaw_fit) .show() ) plt.scatter(n_users, n_cliques) plt.xscale('log') plt.yscale('log') plt.xlabel("cliques of size k") plt.ylabel("number of cliques") plt.show() ###Output _____no_output_____ ###Markdown Testing the structure of the blocking method ###Code spark.table("bipartite").printSchema() user_stats = spark.sql(""" select user_id, approx_count_distinct(article_id) as n_articles, approx_count_distinct(edit_date) as n_edits, sum(word_count) as contribution from bipartite group by 1 """) data = user_stats.collect() import numpy as np import matplotlib.pyplot as plt x, y, z = map(np.array, zip(*( (r.contribution, r.n_articles, r.n_edits) for r in data if r.contribution and r.n_articles and r.n_edits ))) from scipy.stats import linregress xx, yy, zz = map(np.log, [x+1, y+1, z+1]) m, b, r, _, _ = linregress(xx, yy) print(r**2) plt.hexbin(xx, yy, gridsize=50, bins='log', cmap='jet') ax = plt.gca() ax.set_autoscale_on(False) x_vals = np.linspace(1, max(xx)) plt.plot(x_vals, x_vals*m+b, 'r') plt.title("number of distinct articles vs contribution") plt.xlabel("log of distinct articles") plt.ylabel("contribution (log sum of log textdata)") plt.show() m, b, r, _, _ = linregress(xx, zz) print(r**2) plt.hexbin(xx, zz, gridsize=50, bins='log', cmap='jet') ax = plt.gca() ax.set_autoscale_on(False) x_vals = np.linspace(1, max(xx)) plt.plot(x_vals, x_vals*m+b, 'r') plt.title("number of distinct articles vs contribution") plt.xlabel("log of distinct articles") plt.ylabel("contribution (log sum of log textdata)") plt.show() ###Output 0.7623663138446564 ###Markdown Statistics on the projection ###Code admins_df = spark.read.csv("data/processed/admins.csv").toDF("username") admins_df.createOrReplaceTempView("admins") spark.sql("select count(*) from admins").show() spark.sql("select * from projection limit 10").show() spark.table("projection").cache() spark.table("projection").count() spark.table("projection").printSchema() spark.sql( """ select count(distinct user_id) from ( select distinct e1 as user_id from projection union select distinct e2 as user_id from projection ) """ ).show() user_degrees = spark.sql( """ select e1 as user_id, count(distinct e2) as degree from ( select e1, e2 from projection union select e2 as e1, e1 as e2 from projection ) group by 1 """ ) user_degrees.cache() user_degrees.count() x, y = zip(*[(r.degree, r.n_users) for r in ( user_degrees .groupby("degree") .agg(F.expr("count(distinct user_id) as n_users")) .collect() )]) plt.scatter(x,y) plt.xscale("log") plt.yscale("log") plt.show() mapping = spark.sql(""" with ids as ( select distinct user_id, username from enwiki ) select ids.user_id, ids.username from ids inner join admins on ids.username = admins.username """) mapping.cache() mapping.count() import shutil import glob name = "admin_mapping" interim_path = "data/interim/{}".format(name) mapping.repartition(1).write.csv(interim_path, mode="overwrite") interim_file = glob.glob("{}/*.csv".format(interim_path))[0] processed_file = "data/processed/{}.csv".format(name) shutil.copy(interim_file, processed_file) shutil.rmtree(interim_path) ( user_degrees .join(mapping, on="user_id", how="inner") .selectExpr( "avg(degree) as avg_deg", "stddev_pop(degree) as stddev_deg", "percentile(degree, 0.5) as median", "count(*) as n_samples" ) .withColumn("error_bound", F.expr("stddev_deg*1.96/sqrt(n_samples)")) ).show(vertical=True) ( user_degrees .sample(0.1) .selectExpr( "avg(degree) as avg_deg", "stddev_pop(degree) as stddev_deg", "percentile(degree, 0.5) as median", "count(*) as n_samples" ) .withColumn("error_bound", F.expr("stddev_deg*1.96/sqrt(n_samples)")) ).show(vertical=True) x_deg, y_contrib = zip(*[(r.degree, r.contribution) for r in user_stats.join(user_degrees, on="user_id", how="inner").collect()]) x_deg, y_contrib = map(np.array, [x_deg, y_contrib]) m, b, r, p, _ = linregress(x_deg, y_contrib) print(r**2) plt.hexbin(x_deg+1, y_contrib+1, gridsize=50, bins='log', cmap='jet', xscale='log', yscale='log') plt.xlabel("degree of user") plt.ylabel("contribution (sum(log(textdata))") plt.title("degree vs contribution") ax = plt.gca() ax.set_autoscale_on(False) x_vals = np.linspace(0, max(x_deg)) plt.plot(x_vals, x_vals*m+b, 'r') plt.show() ! ls data/processed ###Output 2007-1-enwiki-projection-user-dev.csv all_article_features.csv 2007-1-enwiki-projection-user-roles.csv all_user_features.csv 2007-1-enwiki-projection-user.csv base_features_reg.csv 2007Q1-user-network-v1.csv community_norm_features.csv 2007Q1-user-network-v2.csv enwiki-meta-compact 2007Q1-user-roles-v2.txt enwiki-projection-user-dev.csv admins.csv kcore-2007-1.csv
.ipynb_checkpoints/Phosphorylation Sequence Tests -MLP -dbptm+ELM-filterBenchmark-checkpoint.ipynb
###Markdown Template for test ###Code from pred import Predictor from pred import sequence_vector from pred import chemical_vector ###Output /Users/mark/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20. "This module will be removed in 0.20.", DeprecationWarning) ###Markdown Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation.Included is N Phosphorylation however no benchmarks are available, yet. Training data is from phospho.elm and benchmarks are from dbptm. ###Code par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/clean_s_filtered.csv") y.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i) y.supervised_training("mlp_adam") y.benchmark("Data/Benchmarks/phos.csv", "S") del y print("x", i) x = Predictor() x.load_data(file="Data/Training/clean_s_filtered.csv") x.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i, random_data="Data/Benchmarks/phos.csv") x.supervised_training("mlp_adam") x.benchmark("Data/Benchmarks/phos.csv", "S") del x ###Output y pass Loading Data Loaded Data Working on Data Finished working with Data Training Data Points: 200363 Test Data Points: 50091 Starting Training Done training Test Results Sensitivity: 0.9317468902109248 Specificity : 0.9979434950790775 Accuracy: 0.9857259787187319 ROC 0.964845192645 TP 8614 FP 84 TN 40762 FN 631 None Cross: Validation: [ 0.9849477 0.985167 0.98564612 0.98560591 0.98612498] Number of data points in benchmark 65895 Benchmark Results Failed TP 0 FP 0 TN 62517 FN 3378 None x pass Loading Data Loaded Data Working on Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 450817 Test Data Points: 50091 Starting Training Done training Test Results Sensitivity: 0.9301850258175559 Specificity : 0.998038975364628 Accuracy: 0.9854464873929448 ROC 0.964112000591 TP 8647 FP 80 TN 40715 FN 649 None Cross: Validation: [ 0.98470814 0.98550638 0.98590565 0.98582551 0.98608505] Number of data points in benchmark 65895 Benchmark Results Failed TP 0 FP 0 TN 62517 FN 3378 None y ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 325126 Test Data Points: 81282 Starting Training Done training Test Results Sensitivity: 0.919632918594009 Specificity : 0.9874923509974299 Accuracy: 0.9537412957358332 ROC 0.953562634796 TP 37178 FP 511 TN 40344 FN 3249 None Cross: Validation: [ 0.96086513 0.94573214 0.94356615 0.94237276 0.93972761] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.015097690941385435 Specificity : 0.9897627845226098 Accuracy: 0.9397981637453524 ROC 0.502430237732 TP 51 FP 640 TN 61877 FN 3327 None x ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 575580 Test Data Points: 81282 Starting Training Done training Test Results Sensitivity: 0.9141626652145933 Specificity : 0.9909491193737769 Accuracy: 0.9527816736792893 ROC 0.952555892294 TP 36934 FP 370 TN 40510 FN 3468 None Cross: Validation: [ 0.95908123 0.93987599 0.94055191 0.93956767 0.94566996] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.003256364712847839 Specificity : 0.9958891181598605 Accuracy: 0.945003414523105 ROC 0.499572741436 TP 11 FP 257 TN 62260 FN 3367 None y SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 323685 Test Data Points: 80922 Starting Training Done training Test Results Sensitivity: 0.940358598614619 Specificity : 0.9964576258764323 Accuracy: 0.9687353253750525 ROC 0.968408112246 TP 37604 FP 145 TN 40788 FN 2385 None Cross: Validation: [ 0.97055225 0.96788226 0.96914274 0.96765982 0.9685125 ] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.011841326228537596 Specificity : 0.9970887918486172 Accuracy: 0.9465816829804993 ROC 0.504465059039 TP 40 FP 182 TN 62335 FN 3338 None x SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 547928 Test Data Points: 74369 Starting Training Done training Test Results Sensitivity: 0.9402696552230406 Specificity : 0.9917019879410185 Accuracy: 0.9634390673533327 ROC 0.965985821582 TP 38426 FP 278 TN 33224 FN 2441 None Cross: Validation: [ 0.95721393 0.96407105 0.96452775 0.9663296 0.96507907] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.02605091770278271 Specificity : 0.988707071676504 Accuracy: 0.9393580696562713 ROC 0.50737899469 TP 88 FP 706 TN 61811 FN 3290 None y random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 73804 Test Data Points: 18452 Starting Training Done training Test Results Sensitivity: 0.9289687633718442 Specificity : 0.9947275922671354 Accuracy: 0.9614133969217429 ROC 0.961848177819 TP 8684 FP 48 TN 9056 FN 664 None Cross: Validation: [ 0.96412313 0.96347279 0.96184695 0.96303523 0.96097561] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.012729425695677915 Specificity : 0.998448422029208 Accuracy: 0.9479171409059868 ROC 0.505588923862 TP 43 FP 97 TN 62420 FN 3335 None x random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 324258 Test Data Points: 18452 Starting Training Done training Test Results Sensitivity: 0.9320710312366282 Specificity : 0.9958260105448155 Accuracy: 0.9635269889442879 ROC 0.963948520891 TP 8713 FP 38 TN 9066 FN 635 None Cross: Validation: [ 0.96190115 0.96396055 0.96352699 0.96314363 0.96298103] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.0002960331557134399 Specificity : 0.9999840043508166 Accuracy: 0.9487366264511723 ROC 0.500140018753 TP 1 FP 1 TN 62516 FN 3377 None y ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 187411 Test Data Points: 46853 Starting Training Done training Test Results Sensitivity: 0.9313493768801031 Specificity : 0.9993074976694634 Accuracy: 0.9858066719313597 ROC 0.965328437275 TP 8669 FP 26 TN 37519 FN 639 None Cross: Validation: [ 0.9849746 0.98608414 0.98638294 0.98595578 0.9855289 ] Number of data points in benchmark 65895 Benchmark Results Failed TP 0 FP 0 TN 62517 FN 3378 None x ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 437922 Test Data Points: 46867 Starting Training Done training Test Results Sensitivity: 0.9298302170642596 Specificity : 0.9991746758606 Accuracy: 0.9854055092069046 ROC 0.964502446462 TP 8653 FP 31 TN 37530 FN 653 None Cross: Validation: [ 0.98598191 0.98632329 0.98455203 0.9854052 0.98610933] Number of data points in benchmark 65895 Benchmark Results Failed TP 0 FP 1 TN 62516 FN 3378 None y near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 73804 Test Data Points: 18452 Starting Training Done training Test Results Sensitivity: 0.9519683354728284 Specificity : 0.983853251318102 Accuracy: 0.9676999783221331 ROC 0.967910793395 TP 8899 FP 147 TN 8957 FN 449 None Cross: Validation: [ 0.96303924 0.96818773 0.96325602 0.96195122 0.90612466] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.3019538188277087 Specificity : 0.6897643840875282 Accuracy: 0.6698839062144321 ROC 0.495859101458 TP 1020 FP 19395 TN 43122 FN 2358 None x near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 250454 Filtering Random Data Random Data Added: 250454 Finished with Random Data Training Data Points: 324258 Test Data Points: 18452 Starting Training Done training Test Results Sensitivity: 0.9542148053059478 Specificity : 0.9860500878734623 Accuracy: 0.9699219596791676 ROC 0.97013244659 TP 8920 FP 127 TN 8977 FN 428 None Cross: Validation: [ 0.96704964 0.96883807 0.97214394 0.9500271 0.9501355 ] Number of data points in benchmark 65895 Benchmark Results Sensitivity: 0.27767910005920665 Specificity : 0.6791912599772861 Accuracy: 0.658608392139009 ROC 0.478435180018 TP 938 FP 20056 TN 42461 FN 2440 None ###Markdown Y Phosphorylation ###Code par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/clean_Y_filtered.csv") y.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i) y.supervised_training("mlp_adam") y.benchmark("Data/Benchmarks/phos.csv", "Y") del y print("x", i) x = Predictor() x.load_data(file="Data/Training/clean_Y_filtered.csv") x.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i, random_data="Data/Benchmarks/phos.csv") x.supervised_training("mlp_adam") x.benchmark("Data/Benchmarks/phos.csv", "Y") del x ###Output y pass Loading Data Loaded Data Working on Data Finished working with Data Training Data Points: 10099 Test Data Points: 2525 Starting Training Done training Test Results Sensitivity: 0.06542056074766354 Specificity : 0.9884201819685691 Accuracy: 0.9493069306930693 ROC 0.526920371358 TP 7 FP 28 TN 2390 FN 100 None Cross: Validation: [ 0.95091053 0.95247525 0.95207921 0.95245642 0.95126783] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 242 TN 23272 FN 41 None x pass Loading Data Loaded Data Working on Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 22723 Test Data Points: 2525 Starting Training Done training Test Results Sensitivity: 0.050505050505050504 Specificity : 0.9954657873042044 Accuracy: 0.9584158415841584 ROC 0.522985418905 TP 5 FP 11 TN 2415 FN 94 None Cross: Validation: [ 0.95130641 0.95287129 0.95128713 0.95285261 0.95047544] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 120 TN 23394 FN 41 None y ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 19375 Test Data Points: 4844 Starting Training Done training Test Results Sensitivity: 0.908256880733945 Specificity : 0.8462796402289452 Accuracy: 0.8769611890999174 ROC 0.877268260481 TP 2178 FP 376 TN 2070 FN 220 None Cross: Validation: [ 0.6873065 0.76899257 0.72440132 0.70803221 0.72785464] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 1.0 Specificity : 0.8665475886705792 Accuracy: 0.8667798768838888 ROC 0.933273794335 TP 41 FP 3138 TN 20376 FN 0 None x ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 31999 Test Data Points: 4844 Starting Training Done training Test Results Sensitivity: 0.8381551362683438 Specificity : 0.8910126067507117 Accuracy: 0.8649876135425268 ROC 0.86458387151 TP 1999 FP 268 TN 2191 FN 386 None Cross: Validation: [ 0.75417957 0.75165153 0.71738233 0.75180673 0.68573198] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 2446 TN 21068 FN 41 None y SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 19248 Test Data Points: 4812 Starting Training Done training Test Results Sensitivity: 0.9393305439330544 Specificity : 0.7877786952931461 Accuracy: 0.8630507065669161 ROC 0.863554619613 TP 2245 FP 514 TN 1908 FN 145 None Cross: Validation: [ 0.84957407 0.9017245 0.88528678 0.88380794 0.8989815 ] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 4040 TN 19474 FN 41 None x SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 31872 Test Data Points: 4813 Starting Training Done training Test Results Sensitivity: 0.8748957464553795 Specificity : 0.8877846790890269 Accuracy: 0.8813629752752961 ROC 0.881340212772 TP 2098 FP 271 TN 2144 FN 300 None Cross: Validation: [ 0.85476834 0.86328693 0.89632246 0.88921222 0.89690293] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 0.975609756097561 Specificity : 0.9151994556434464 Accuracy: 0.9153046062407132 ROC 0.945404605871 TP 40 FP 1994 TN 21520 FN 1 None y random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 945 Test Data Points: 237 Starting Training Done training Test Results Sensitivity: 0.559322033898305 Specificity : 0.5210084033613446 Accuracy: 0.540084388185654 ROC 0.54016521863 TP 66 FP 57 TN 62 FN 52 None Cross: Validation: [ 0.57563025 0.58898305 0.48728814 0.5720339 0.58474576] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 0.975609756097561 Specificity : 0.5510759547503615 Accuracy: 0.5518149012948419 ROC 0.763342855424 TP 40 FP 10556 TN 12958 FN 1 None x random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 13569 Test Data Points: 237 Starting Training Done training Test Results Sensitivity: 0.5 Specificity : 0.5126050420168067 Accuracy: 0.5063291139240507 ROC 0.506302521008 TP 59 FP 58 TN 61 FN 59 None Cross: Validation: [ 0.57563025 0.58474576 0.52118644 0.53389831 0.58474576] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 1.0 Specificity : 0.5826316237135324 Accuracy: 0.5833580980683507 ROC 0.791315811857 TP 41 FP 9814 TN 13700 FN 0 None y ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 9229 Test Data Points: 2308 Starting Training Done training Test Results Sensitivity: 0.02608695652173913 Specificity : 0.9981760145918832 Accuracy: 0.949740034662045 ROC 0.512131485557 TP 3 FP 4 TN 2189 FN 112 None Cross: Validation: [ 0.9462971 0.94971825 0.94928479 0.94885132 0.94928479] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 0 TN 23514 FN 41 None x ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 21854 Test Data Points: 2308 Starting Training Done training Test Results Sensitivity: 0.008695652173913044 Specificity : 0.9977200182398541 Accuracy: 0.9484402079722704 ROC 0.503207835207 TP 1 FP 5 TN 2188 FN 114 None Cross: Validation: [ 0.94759636 0.94757366 0.94841786 0.94928479 0.95058518] Number of data points in benchmark 23555 Benchmark Results Failed TP 0 FP 40 TN 23474 FN 41 None y near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 945 Test Data Points: 237 Starting Training Done training Test Results Sensitivity: 0.7627118644067796 Specificity : 0.5462184873949579 Accuracy: 0.6540084388185654 ROC 0.654465175901 TP 90 FP 54 TN 65 FN 28 None Cross: Validation: [ 0.68067227 0.66949153 0.69915254 0.6440678 0.58898305] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 0.975609756097561 Specificity : 0.41685804201752147 Accuracy: 0.41783060921248144 ROC 0.696233899058 TP 40 FP 13712 TN 9802 FN 1 None x near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 12624 Filtering Random Data Random Data Added: 12624 Finished with Random Data Training Data Points: 13569 Test Data Points: 237 Starting Training Done training Test Results Sensitivity: 0.7288135593220338 Specificity : 0.7142857142857143 Accuracy: 0.7215189873417721 ROC 0.721549636804 TP 86 FP 34 TN 85 FN 32 None Cross: Validation: [ 0.62184874 0.65677966 0.71610169 0.63983051 0.62288136] Number of data points in benchmark 23555 Benchmark Results Sensitivity: 1.0 Specificity : 0.35697882112783874 Accuracy: 0.35809806835066865 ROC 0.678489410564 TP 41 FP 15120 TN 8394 FN 0 None ###Markdown T Phosphorylation ###Code par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/clean_t_filtered.csv") y.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i) y.supervised_training("mlp_adam") y.benchmark("Data/Benchmarks/phos.csv", "T") del y print("x", i) x = Predictor() x.load_data(file="Data/Training/clean_t_filtered.csv") x.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i, random_data="Data/Benchmarks/phos.csv") x.supervised_training("mlp_adam") x.benchmark("Data/Benchmarks/phos.csv", "T") del x ###Output y pass Loading Data Loaded Data Working on Data Finished working with Data Training Data Points: 66323 Test Data Points: 16581 Starting Training Done training Test Results Sensitivity: 0.8927526811829705 Specificity : 0.9969638625592417 Accuracy: 0.9776249924612508 ROC 0.944858271871 TP 2747 FP 41 TN 13463 FN 330 None Cross: Validation: [ 0.98015921 0.98015921 0.98100121 0.98148372 0.98082027] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.0008110300081103001 Specificity : 0.999010688861647 Accuracy: 0.9732243871778755 ROC 0.499910859435 TP 1 FP 46 TN 46451 FN 1232 None x pass Loading Data Loaded Data Working on Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 149227 Test Data Points: 16581 Starting Training Done training Test Results Sensitivity: 0.8998022412656559 Specificity : 0.9990403779434561 Accuracy: 0.9808817321030094 ROC 0.949421309605 TP 2730 FP 13 TN 13534 FN 304 None Cross: Validation: [ 0.98160656 0.9800386 0.98262967 0.98027744 0.97925211] Number of data points in benchmark 47730 Benchmark Results Failed TP 0 FP 0 TN 46497 FN 1233 None y ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 109538 Test Data Points: 27385 Starting Training Done training Test Results Sensitivity: 0.8497222422624631 Specificity : 0.9096421177166519 Accuracy: 0.8793134927880226 ROC 0.87968217999 TP 11778 FP 1222 TN 12302 FN 2083 None Cross: Validation: [ 0.92561893 0.85320431 0.85706982 0.85246859 0.84388694] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.3122465531224655 Specificity : 0.9292857603716369 Accuracy: 0.9133459040435785 ROC 0.620766156747 TP 385 FP 3288 TN 43209 FN 848 None x ADASYN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 192442 Test Data Points: 27385 Starting Training Done training Test Results Sensitivity: 0.9209369369369369 Specificity : 0.9076239822353812 Accuracy: 0.9143691802081432 ROC 0.914280459586 TP 12778 FP 1248 TN 12262 FN 1097 None Cross: Validation: [ 0.94314613 0.86404966 0.8568142 0.84837862 0.83647385] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.2773722627737226 Specificity : 0.9308987676624298 Accuracy: 0.9140163419233187 ROC 0.604135515218 TP 342 FP 3213 TN 43284 FN 891 None y SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 107670 Test Data Points: 26918 Starting Training Done training Test Results Sensitivity: 0.9517972627462776 Specificity : 0.9502202643171807 Accuracy: 0.9509993313024742 ROC 0.951008763532 TP 12657 FP 678 TN 12942 FN 641 None Cross: Validation: [ 0.95765073 0.9587265 0.9566445 0.958242 0.95489839] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.10867802108678021 Specificity : 0.9657827386713121 Accuracy: 0.943641315734339 ROC 0.537230379879 TP 134 FP 1591 TN 44906 FN 1099 None x SMOTEENN Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 190588 Test Data Points: 26922 Starting Training Done training Test Results Sensitivity: 0.9532969089140034 Specificity : 0.9606223729813436 Accuracy: 0.9569868509026075 ROC 0.956959640948 TP 12737 FP 534 TN 13027 FN 624 None Cross: Validation: [ 0.95238095 0.96032984 0.95947402 0.95876825 0.95434621] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.008110300081103 Specificity : 0.9664709551153838 Accuracy: 0.9417138068300859 ROC 0.487290627598 TP 10 FP 1559 TN 44938 FN 1223 None y random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 24059 Test Data Points: 6015 Starting Training Done training Test Results Sensitivity: 0.8967105263157895 Specificity : 0.9942857142857143 Accuracy: 0.9449709060681629 ROC 0.945498120301 TP 2726 FP 17 TN 2958 FN 314 None Cross: Validation: [ 0.93783245 0.94431516 0.94546059 0.94313269 0.94562687] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.0016220600162206002 Specificity : 0.9990321956255243 Accuracy: 0.9732662895453593 ROC 0.500327127821 TP 2 FP 45 TN 46452 FN 1231 None x random_under_sample Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 106963 Test Data Points: 6015 Starting Training Done training Test Results Sensitivity: 0.9049342105263158 Specificity : 0.9828571428571429 Accuracy: 0.943474646716542 ROC 0.943895676692 TP 2751 FP 51 TN 2924 FN 289 None Cross: Validation: [ 0.94547872 0.94148936 0.94712338 0.94945128 0.94978384] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.0373073803730738 Specificity : 0.9903004494913651 Accuracy: 0.9656819610307983 ROC 0.513803914932 TP 46 FP 451 TN 46046 FN 1187 None y ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 62452 Test Data Points: 15613 Starting Training Done training Test Results Sensitivity: 0.9116936874784408 Specificity : 0.9997640396413403 Accuracy: 0.983411259847563 ROC 0.95572886356 TP 2643 FP 3 TN 12711 FN 256 None Cross: Validation: [ 0.98161906 0.97944153 0.980465 0.97867025 0.98097617] Number of data points in benchmark 47730 Benchmark Results Failed TP 0 FP 1 TN 46496 FN 1233 None x ncl Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 145339 Test Data Points: 15609 Starting Training Done training Test Results Sensitivity: 0.8965160400137978 Specificity : 0.9985051140833989 Accuracy: 0.9795630725863284 ROC 0.947510577049 TP 2599 FP 19 TN 12691 FN 300 None Cross: Validation: [ 0.97905189 0.98026906 0.98122758 0.9803306 0.98045874] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.0008110300081103001 Specificity : 0.999913972944491 Accuracy: 0.9741043368950346 ROC 0.500362501476 TP 1 FP 4 TN 46493 FN 1232 None y near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Training Data Points: 24059 Test Data Points: 6015 Starting Training Done training Test Results Sensitivity: 0.9203947368421053 Specificity : 0.986218487394958 Accuracy: 0.9529509559434747 ROC 0.953306612119 TP 2798 FP 41 TN 2934 FN 242 None Cross: Validation: [ 0.83327793 0.95246011 0.94861989 0.94812105 0.94679082] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.17761557177615572 Specificity : 0.8321397079381465 Accuracy: 0.8152315105803478 ROC 0.504877639857 TP 219 FP 7805 TN 38692 FN 1014 None x near_miss Loading Data Loaded Data Working on Data Balancing Data Balanced Data Finished working with Data Random Sequences Generated 82904 Filtering Random Data Random Data Added: 82904 Finished with Random Data Training Data Points: 106963 Test Data Points: 6015 Starting Training Done training Test Results Sensitivity: 0.9115131578947369 Specificity : 0.9895798319327731 Accuracy: 0.9501246882793017 ROC 0.950546494914 TP 2771 FP 31 TN 2944 FN 269 None Cross: Validation: [ 0.82347074 0.9559508 0.95128035 0.95044895 0.949285 ] Number of data points in benchmark 47730 Benchmark Results Sensitivity: 0.14517437145174372 Specificity : 0.8424629545992215 Accuracy: 0.8244500314267756 ROC 0.493818663025 TP 179 FP 7325 TN 39172 FN 1054 None
golden_years_final.ipynb
###Markdown Golden Years Retirement PlannerAmericans struggle to save enough money to live comfortably during retirement. Recent market data and analysis of surveys gauging retirement confidence have shown that Americans need to save more. In order to help Americans save more and make better financial decisions, our product aims to analyze the amount it takes to retire comfortably, make suggestions on where to invest, and forecast savings over time. ###Code #Import libraries and dependances import csv from pathlib import Path import sys import os import requests import json import pandas as pd import hvplot.pandas import plotly.express as px import alpaca_trade_api as tradeapi from datetime import datetime from dotenv import load_dotenv from MCForecastTools import MCSimulation %matplotlib inline from data.retire import retirement_plan from data.comfort import comfort_buffer from data.americanstates import fifty_states ###Output _____no_output_____ ###Markdown Part 1: Analysis of Current Retirement Trends in the USA**Completed By: Robert Giannini** ###Code #Data was obtained from Retirement Confidence Survey by T. Rowe Price and was used to create a dataframe #The CSV file is us_retiree_basic_expenses_covered_confidence.csv file and index was set to confidence_rating retiree_confidence_df = pd.read_csv( Path("./Resources/us_retiree_basic_expenses_covered_confidence.csv", index_col="confidence_rating")) retiree_confidence_df.set_index("confidence_rating", inplace=True) retiree_confidence_df["percentage"] = (retiree_confidence_df['outcome'] / retiree_confidence_df['outcome'].sum()) * 100 display(retiree_confidence_df) #bar graph retiree_confidence_df.hvplot.bar(figsize=(20,14), x='confidence_rating', y='outcome', title='Retirement Confidence Rating (USA)') ###Output _____no_output_____ ###Markdown AnalysisData gathered from a Retirement Confidence Survey by T. Rowe Price indicates that Americans’ confidence in their ability to live comfortably in retirement remains high overall. This data shows that over 62% of Americans' are either **Very Confident** or **Somewhat Confident** that they will have enough money for a comfortable retirement. However, this still leaves over 37% of either **Not Too Confident** or **Not Confident At All** Americans' that feel they will not be able to have enough money to retire comfortably. While the majority of Americans' on the T. Rowe Price Retirement Confidence Survey feel they are on track for a comfortable retirement, Golden Years plans to put this to the test. 1.1: How Are Americans' Saving For Retirement?Loading Popular Retirement Accounts in the USA from popular_retirement_accounts_usa_survey.csv file, setting index to account_responses, and displaying DataFrame. ###Code #Converting CSV information into dataframe popular_retirement_accounts_usa_survey_df = pd.read_csv( Path("./Resources/popular_retirement_accounts_usa_survey.csv", index_col="account_responses")) popular_retirement_accounts_usa_survey_df.set_index("account_responses", inplace=True) popular_retirement_accounts_usa_survey_df["percentage"] = (popular_retirement_accounts_usa_survey_df['amount'] / popular_retirement_accounts_usa_survey_df['amount'].sum()) * 100 display(popular_retirement_accounts_usa_survey_df) #A pie chart showing popular retirement accounts in USA explode = (0.06, 0, 0, 0, 0, 0, 0, 0) popular_retirement_accounts_usa_survey_df.plot.pie(figsize=(20,16), y='percentage', autopct='%1.1f%%', explode=explode, #hoverinfo='account_response+amount', #legend = 'Accounts', title='Popular Retirement Accounts (USA)') ###Output _____no_output_____ ###Markdown 1.2 Analysis of Comfortable Retirement in the USA using MAPBOX ###Code #Loading `.env` file to Read MapBox API Key and Printing type to confirm API access. load_dotenv() # Reading in the MAPBOX_API_KEY. mapbox_api_access_token = os.getenv("MAPBOX_API_ACCESS_TOKEN") # Confirming the availability of the Mapbox API access token by checking its type. print(type(mapbox_api_access_token)) # Setting Mapbox API access token. px.set_mapbox_access_token(mapbox_api_access_token) #State Coordinates Data from coordinates.csv file #using .head() and .tail() functions to display First and Last Five rows of DataFrame. #Loading state coordinates data. state_coordinates_df = pd.read_csv(Path("./Resources/coordinates.csv", index_col="States")) state_coordinates_df.set_index('States', inplace=True) # Reviewing the DataFrame. display(state_coordinates_df.head()) display(state_coordinates_df.tail()) #Loading US Retirement Data from us_retirement_data.csv file #using .head() and .tail() functions to display First and Last Five rows of DataFrame. #Using the read_csv function, Path module, and creating a DataFrame # by importing the us_retirement_data.csv file from the Resources folder. us_retirement_data_df = pd.read_csv(Path("./Resources/us_retirement_data.csv")) # Reviewing the first and last five rows of the DataFrame. display(us_retirement_data_df.head()) display(us_retirement_data_df.tail()) #Grouping data. retirement_by_state = us_retirement_data_df.groupby(["States"])[["cost_of_living","comfort_buffer","comfortable_retirement"]].mean() # Reviewing the DataFrame. retirement_by_state.head() # Using the Pandas `concat` function to join the # state_coordinates_df and retirement_by_state DataFrames # The axis of the concatenation is "columns". # The concat function will automatially combine columns with # identical information, while keeping the additional columns. all_states_retirement_df = pd.concat( [state_coordinates_df, retirement_by_state], axis="columns", sort=False ) # Reviewing the resulting DataFrame. display(all_states_retirement_df.head()) display(all_states_retirement_df.tail()) # Creating a scatter mapbox to analyze retirement info of all states. mapbox = px.scatter_mapbox( all_states_retirement_df, lat="Lat", lon="Lon", size="cost_of_living", color="comfortable_retirement", size_max=15, zoom=1.65 ) mapbox ###Output _____no_output_____ ###Markdown Part 2: User Input***Completed by Doreen Ngo***User inputs information regarding the state they want to live in and their investment choices. Please run this portion from user_input.py. Part 3: Financial Forecast and Simulations***Completed by Kevin Mau***Analysis of stocks and crypto currency based on the amount the user can save. ###Code # Load the environment variables from the .env file #by calling the load_dotenv function load_dotenv() ###Output _____no_output_____ ###Markdown Cryptocurrency Analysis Review the endpoint URLs for the API calls to Free Crypto API in order to get the current pricing information for both BTC and ETH. ###Code # The Free Crypto API Call endpoint URLs for the held cryptocurrency assets btc_url = "https://api.alternative.me/v2/ticker/Bitcoin/?convert=USD" eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=USD" ###Output _____no_output_____ ###Markdown Use the Requests library to get the current price (in US dollars) of Bitcoin (BTC) and Ethereum (ETH) by using the API endpoints that the starter code supplied. ###Code # Using the Python requests library, make an API call to access the current price of BTC btc_response = requests.get(btc_url).json() # Use the json.dumps function to review the response data from the API call # Use the indent and sort_keys parameters to make the response object readable print(json.dumps(btc_response, indent=4, sort_keys=True)) # Using the Python requests library, make an API call to access the current price ETH eth_response = requests.get(eth_url).json() # Use the json.dumps function to review the response data from the API call # Use the indent and sort_keys parameters to make the response object readable print(json.dumps(eth_response, indent=4, sort_keys=True)) ###Output { "data": { "1027": { "circulating_supply": 117208141, "id": 1027, "last_updated": 1629626371, "max_supply": 0, "name": "Ethereum", "quotes": { "USD": { "market_cap": 382835869228, "percent_change_1h": 0.477871248339957, "percent_change_24h": -0.37915803634404, "percent_change_7d": 0.0144878491381817, "percentage_change_1h": 0.477871248339957, "percentage_change_24h": -0.37915803634404, "percentage_change_7d": 0.0144878491381817, "price": 3269.02, "volume_24h": 17665084256 } }, "rank": 2, "symbol": "ETH", "total_supply": 117208141, "website_slug": "ethereum" } }, "metadata": { "error": null, "num_cryptocurrencies": 3105, "timestamp": 1629626371 } } ###Markdown Navigate the JSON response object to access the current price of each coin, and store each in a variable. ###Code #Navigate the BTC response object to access the current price of BTC btc_price = btc_response['data']['1']['quotes']['USD']['price'] # Print the current price of BTC print(f"The price for Bitcoin is ${btc_price:,.2f}") # Navigate the BTC response object to access the current price of ETH eth_price = eth_response['data']['1027']['quotes']['USD']['price'] # Print the current price of ETH print(f"The price for Ethereum is ${eth_price:,.2f}") ###Output The price for Ethereum is $3,269.02 ###Markdown Calculate the amount of coins the retiree can afford to purchase. Take amount able to invest divide by 2, equals "half the amount". Take "half the amount" divide by BTC price equals the amount of BTC to purchase. Take "half the amount" divide by ETH price equals the amount of ETH to purchase. ###Code #user input savings amount and press enter savings_amount= int(input("Enter savings account information:")) #buying both bitcoin and etherum half_savings = savings_amount / 2 btc_coins = half_savings / btc_price eth_coins = half_savings / eth_price # Print current holding in BTC #since savings is low, threshold 1000 print(f"You now are holding {btc_coins} Bitcoin") # Print current holding in ETH #based on savings print(f"The now are holding {eth_coins} Ethereum") # Read in the CSV file called "Bitcoin Historical Data.csv" using the Path module. # The CSV file is located in the Resources folder. # Set the index to the column "Date" # Set the parse_dates and infer_datetime_format parameters btc_df = pd.read_csv( Path('./Resources/Bitcoin Historical Data.csv'), index_col="Date", parse_dates=True, infer_datetime_format=True) btc_df.loc[:,"Price"]=btc_df.loc[:,"Price"].str.replace(",","") btc_df.loc[:,"Price"]=btc_df.loc[:,"Price"].astype("float") btc_df.loc[:,"Open"]=btc_df.loc[:,"Open"].str.replace(",","") btc_df.loc[:,"Open"]=btc_df.loc[:,"Open"].astype("float") btc_df.loc[:,"High"]=btc_df.loc[:,"High"].str.replace(",","") btc_df.loc[:,"High"]=btc_df.loc[:,"High"].astype("float") btc_df.loc[:,"Low"]=btc_df.loc[:,"Low"].str.replace(",","") btc_df.loc[:,"Low"]=btc_df.loc[:,"Low"].astype("float") btc_df = btc_df.drop(columns=["Change %"]) # This function converts the string values into a floating point number def clean_currency(price_string): price = price_string if type(price_string) == str: price_string = price_string.replace('$', '') price_string = price_string.replace('-', '0') if price_string[-1] == 'K': thousand = 1000 price_string = price_string.replace('K', '') price = float(price_string) price = price * thousand elif price_string[-1] == 'M': million = 1000000 price_string = price_string.replace('M', '') price = float(price_string) price = price * million else: billion = 1000000000 price_string = price_string.replace('B', '') price = float(price_string) price = price * billion return price btc_df['Vol.'] = btc_df['Vol.'].apply(clean_currency) list(btc_df.columns) btc_df2 = btc_df[['Open', 'High', 'Low', 'Price', 'Vol.']] columns = ["open", "high"," low", "close", "volume"] btc_df2.columns = columns btc_df2.keys() # Read in the CSV file called "Bitcoin Historical Data.csv" using the Path module. # The CSV file is located in the Resources folder. # Set the index to the column "Date" # Set the parse_dates and infer_datetime_format parameters eth_df = pd.read_csv( Path('./Resources/Ethereum Historical Data.csv'), index_col="Date", parse_dates=True, infer_datetime_format=True) eth_df = eth_df.drop(columns=["Change %"]) eth_df['Vol.'] = eth_df['Vol.'].apply(clean_currency) eth_df.loc[:,"Price"]=eth_df.loc[:,"Price"].str.replace(",","") eth_df.loc[:,"Price"]=eth_df.loc[:,"Price"].astype("float") eth_df.loc[:,"Open"]=eth_df.loc[:,"Open"].str.replace(",","") eth_df.loc[:,"Open"]=eth_df.loc[:,"Open"].astype("float") eth_df.loc[:,"High"]=eth_df.loc[:,"High"].str.replace(",","") eth_df.loc[:,"High"]=eth_df.loc[:,"High"].astype("float") eth_df.loc[:,"Low"]=eth_df.loc[:,"Low"].str.replace(",","") eth_df.loc[:,"Low"]=eth_df.loc[:,"Low"].astype("float") eth_df2 = eth_df[['Open', 'High', 'Low', 'Price', 'Vol.']] columns = ["open", "high"," low", "close", "volume"] eth_df2.columns = columns eth_df2.head() # Create a dictionary of the two dataframes to_merge_dict = {'BTC': btc_df2 , 'ETH': eth_df2} # Use concat to create a merged dataframe from the dictionary merged_df = pd.concat(to_merge_dict.values(), axis=1, keys=to_merge_dict.keys()) merged_df.head() # Configure the Monte Carlo simulation to forecast 5 years cumulative returns # Run 500 samples. MC_crypto = MCSimulation( portfolio_data = merged_df, weights = [.5, .5], num_simulation = 500, num_trading_days = 252*5 ) # Review the simulation input data display(MC_crypto.portfolio_data.head()) #Run the Monte Carlo simulation to forecast 5 years cumulative returns MC_crypto.calc_cumulative_return() # Visualize the probability distribution of the 5-year Monte Carlo simulation # by plotting a histogram MC_sim_dist_plot = MC_crypto.plot_distribution() # Generate summary statistics from the 5-year Monte Carlo simulation results # Save the results as a variable MC_summary_statistics = MC_crypto.summarize_cumulative_return() # Review the 5-year Monte Carlo summary statistics print(MC_summary_statistics) # Print the current balance of the stock and bond portion of the members portfolio print(f"The current balance of cryptocurrency is ${savings_amount:,.2f}") # Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount # Print the result of your calculations print(f"There is a 95% chance that your investment over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.") ###Output There is a 95% chance that your investment over the next 5 years will end within in the range of $7.35 and $1,317.53. ###Markdown Part 4: Analysis of FAANG Stocks***Completed by Kevin Mau*** Set the variables for the Alpaca API and secret keys. Using the Alpaca SDK, create the Alpaca `tradeapi.REST` object. In this object, include the parameters for the Alpaca API key, the secret key, and the version number. ###Code # Set the variables for the Alpaca API and secret keys alpaca_api_key = os.getenv("ALPACA_API_KEY") alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY") # Create the Alpaca tradeapi.REST object alpaca = tradeapi.REST( alpaca_api_key, alpaca_secret_key, api_version="v2") ###Output _____no_output_____ ###Markdown Set the following parameters for the Alpaca API call:- `tickers`: Use the tickers for the member’s stock and bond holdings.- `timeframe`: Use a time frame of one day.- `start_date` and `end_date`: using 7/30/2018 - 7/30/2021 ###Code # Set the tickers for the stock portion of the portfolio tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"] # Set timeframe to 1D timeframe = "1D" # Format current date as ISO format # Set both the start and end date at the date of your prior weekday # This will give you the closing price of the previous trading day # Alternatively you can use a start and end date of 2020-08-07 start_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat() end_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat() # Use the Alpaca get_barset function to get current closing prices the portfolio # Be sure to set the `df` property after the function to format the response object as a DataFrame df_portfolio = alpaca.get_barset( tickers, timeframe, start = start_date, end = end_date ).df # Review the first 5 rows of the Alpaca DataFrame df_portfolio.head() # Access the closing price for FB from the Alpaca DataFrame # Converting the value to a floating point number fb_close_price = df_portfolio["FB"]["close"] fb_close_price = float(fb_close_price) # Print the FB closing price print(f"The closing price of Facebook is ${fb_close_price:,.2f}") # Access the closing price for AMZN from the Alpaca DataFrame # Converting the value to a floating point number amzn_close_price = df_portfolio["AMZN"]["close"] amzn_close_price = float(amzn_close_price) # Print the AMZN closing price print(f"The closing price of Amazon is ${amzn_close_price:,.2f}") # Access the closing price for FB from the Alpaca DataFrame # Converting the value to a floating point number aapl_close_price = df_portfolio["AAPL"]["close"] aapl_close_price = float(aapl_close_price) # Print the AAPL closing price print(f"The closing price of Apple is ${aapl_close_price:,.2f}") # Access the closing price for FB from the Alpaca DataFrame # Converting the value to a floating point number nflx_close_price = df_portfolio["NFLX"]["close"] nflx_close_price = float(nflx_close_price) # Print the NFLX closing price print(f"The closing price of Netflix is ${nflx_close_price:,.2f}") # Access the closing price for GOOG from the Alpaca DataFrame # Converting the value to a floating point number goog_close_price = df_portfolio["GOOG"]["close"] goog_close_price = float(goog_close_price) # Print the GOOG closing price print(f"The closing price of Google is ${goog_close_price:,.2f}") ###Output The closing price of Google is $2,704.66 ###Markdown 4.1 Create a Financial Planner for Retirement Create the Monte Carlo SimulationIn this section, you’ll use the MCForecastTools library to create a Monte Carlo simulation for the member’s savings portfolio. To do this, complete the following steps:1. Make an API call via the Alpaca SDK to get 3 years of historical closing prices for an even 5-way split between FAANG stocks.2. Run a Monte Carlo simulation of 500 samples and (ANSWER FROM QUESTIONAIRE) for the FAANG portfolio, and then plot the results.The following image shows the overlay line plot resulting from a simulation with these characteristics.3. Plot the probability distribution of the Monte Carlo simulation. Plot the probability distribution of the Monte Carlo simulation. The following image shows the histogram plot resulting from a simulation with these characteristics.4. Generate the summary statistics for the Monte Carlo simulation. Make an API call via the Alpaca SDK to get 3 years of historical closing prices for FAANG ###Code # Set start and end dates of 3 years back from your current date # Alternatively, you can use an end date of 2020-08-07 and work 3 years back from that date start_date = pd.Timestamp("2018-07-30", tz="America/New_York").isoformat() end_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat() # Set number of rows to 1000 to retrieve the maximum amount of rows limit_rows = 1000 # Use the Alpaca get_barset function to make the API call to get the 3 years worth of pricing data # The tickers and timeframe parameters should have been set in Part 1 of this activity # The start and end dates should be updated with the information set above # Remember to add the df property to the end of the call so the response is returned as a DataFrame prices_df = alpaca.get_barset( tickers, timeframe, start=start_date, end=end_date, limit=limit_rows ).df # Display both the first and last five rows of the DataFrame display(prices_df.head()) display(prices_df.tail()) # Configure the Monte Carlo simulation to forecast 5 years cumulative returns # Run 500 samples. MC_faang = MCSimulation( portfolio_data = prices_df, weights = [.2, .2, .2, .2, .2], num_simulation = 500, num_trading_days = 252*5 ) # Review the simulation input data MC_faang.portfolio_data.head() # Run the Monte Carlo simulation to forecast 5 years cumulative returns MC_faang.calc_cumulative_return() # Visualize the 5-year Monte Carlo simulation by creating an # overlay line plot MC_sim_line_plot = MC_faang.plot_simulation() ###Output _____no_output_____ ###Markdown Generate the summary statistics for the Monte Carlo simulation. ###Code # Generate summary statistics from the 5-year Monte Carlo simulation results # Save the results as a variable MC_summary_statistics = MC_faang.summarize_cumulative_return() # Review the 5-year Monte Carlo summary statistics print(MC_summary_statistics) ###Output count 500.000000 mean 3.678908 std 1.516097 min 1.191165 25% 2.600935 50% 3.493042 75% 4.537284 max 12.354789 95% CI Lower 1.486905 95% CI Upper 7.179377 Name: 1260, dtype: float64 ###Markdown Analyze the Retirement Portfolio ForecastsUsing the current value of only the stock and bond portion of the member's portfolio and the summary statistics that you generated from the Monte Carlo simulation, answer the following question in your Jupyter notebook:- What are the lower and upper bounds for the expected value of the portfolio with a 95% confidence interval? ###Code # Print the current balance of the stock and bond portion of the members portfolio print(f"The current balance of your investing in FAANG stocks is ${savings_amount:,.2f}") # Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount # Print the result of your calculations print(f"There is a 95% chance that the portfolio over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.") ###Output There is a 95% chance that the portfolio over the next 5 years will end within in the range of $1,486.90 and $7,179.38. ###Markdown 4.2 Coding for top 4 popular mutual fundshttps://www.marketwatch.com/tools/mutual-fund/top25largest ###Code tickers = ["SPY", "IVV", "VTI", "VOO"] prices_df = alpaca.get_barset( tickers, timeframe, start=start_date, end=end_date, limit=limit_rows ).df display(prices_df.head()) display(prices_df.tail()) # Configure the Monte Carlo simulation to forecast 5 years cumulative returns # Run 500 samples. MC_mutual_funds = MCSimulation( portfolio_data = prices_df, weights = [.25, .25, .25, .25], num_simulation = 500, num_trading_days = 252*5 ) # Review the simulation input data MC_mutual_funds.portfolio_data.head() # Run the Monte Carlo simulation to forecast 5 years cumulative returns MC_mutual_funds.calc_cumulative_return() # Visualize the 5-year Monte Carlo simulation by creating an # overlay line plot MC_sim_line_plot = MC_mutual_funds.plot_simulation() # Visualize the probability distribution of the 5-year Monte Carlo simulation # by plotting a histogram MC_sim_dist_plot = MC_mutual_funds.plot_distribution() # Generate summary statistics from the 5-year Monte Carlo simulation results # Save the results as a variable MC_summary_statistics = MC_mutual_funds.summarize_cumulative_return() # Review the 5-year Monte Carlo summary statistics print(MC_summary_statistics) # Print the current balance of the mutual funds of the members portfolio print(f"The current balance of your investing in mutual funds is ${savings_amount:,.2f}") # Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current mutual fund portfolio ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount # Print the result of your calculations print(f"There is a 95% chance that the portfolio over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.") ###Output There is a 95% chance that the portfolio over the next 5 years will end within in the range of $1,429.92 and $3,915.83. ###Markdown Comparing investing in a "safe" bank account (i.e. high yield savings account, CD)Compound Interest Formula FV = P (1 + r / n)^Yn, where P is the starting principal, r is the annual interest rate, Y is the number of years invested, and n is the number of compounding periods per year. FV is the future value, meaning the amount the principal grows to after Y years. ###Code P = int(input("Enter starting principle please. ")) n = int(input("Enter number of compounding periods per year. ")) r = float(input("Enter annual interest rate. e.g. 15 for 15% ")) y = int(input("Enter the amount of years. ")) FV = P * (((1 + ((r/100.0)/n)) ** (n*y))) print(f"The final amount after", y, f"years is ${FV:,.2f}.") # another way to write code for compounding interest. can tinker with it to make into function that takes in variables from questionaire? years = range(1,31) rate = 0.07 rates = pd.Series(index = years, data = rate) x = 1000*((rates + 1).cumprod()) final_amount = x.tail(1).item() print(f"${final_amount:,.2f}.") ###Output $7,612.26.
pyyaml_save_read.ipynb
###Markdown ###Code import yaml # import pyyaml d = {"lr": 0.001, "lr_decay": 0.98, "lr_min": 1.0e-07, "lr_scheduler": "multi"} ###Output _____no_output_____ ###Markdown Dump = Save ###Code with open('new.yml', 'w') as f: yaml.dump(d, f, default_flow_style=False) !cat new.yml with open('new_2.yml', 'w') as f: yaml.dump(d, f) !cat new_2.yml ###Output {lr: 0.001, lr_decay: 0.98, lr_min: 1.0e-07, lr_scheduler: multi} ###Markdown Load ###Code with open('new.yml') as f: info = yaml.load(f) print(info) ###Output {'lr': 0.001, 'lr_decay': 0.98, 'lr_min': 1e-07, 'lr_scheduler': 'multi'} ###Markdown download sample yaml ###Code !wget https://filesamples.com/samples/code/yaml/verify_apache.yaml -O example.yaml with open("example.yaml", "r") as stream: data = yaml.safe_load(stream) !cat example.yaml data dumped = yaml.dump(data, default_flow_style=False) print(dumped) ###Output - handlers: - name: restart apache service: name: httpd state: restarted hosts: webservers remote_user: root tasks: - name: ensure apache is at the latest version yum: name: httpd state: latest - name: write the apache config file notify: - restart apache template: dest: /etc/httpd.conf src: /srv/httpd.j2 - name: ensure apache is running service: name: httpd state: started vars: http_port: 80 max_clients: 200
src_optimization/22_nonlinear_stencil_02_efficiency_01/e_plot_by_cells.ipynb
###Markdown Plots ###Code import matplotlib.pyplot as plt from matplotlib import rcParams import pandas as pd import seaborn as sns def plot(p_data, p_yId, p_xId, p_hueId, p_styleId, p_logScale=False, p_marker_label=False, p_marker_value=0, p_export_filename=None, p_xLabel=None, p_yLabel=None): rcParams['figure.figsize'] = 12,8 rcParams['font.size'] = 12 rcParams['svg.fonttype'] = 'none' plot = sns.lineplot(x=p_xId, y=p_yId, hue=p_hueId, style=p_styleId, data=p_data) if p_logScale == True: plot.set_yscale('log') plot.set_xscale('log') if p_xLabel != None: plot.set(xlabel=p_xLabel) else: plot.set(xlabel=p_xId) if p_yLabel != None: plot.set(ylabel=p_yLabel) else: plot.set(ylabel=p_yId) plt.grid(color='gainsboro') plt.grid(True,which='minor', linestyle='--', linewidth=0.5, color='gainsboro') if(p_marker_label != False): plt.axhline(p_marker_value, linestyle='--', color='red', label=p_marker_label) plt.legend() if(p_export_filename != None): plt.savefig(p_export_filename) plt.show() ###Output _____no_output_____ ###Markdown Gauss3 Efficiency by cells functions overview ###Code import pandas as pd data_frame = pd.read_csv('./e_efficiency_by_cells.csv') data_frame = data_frame[data_frame.region_id == 'apply'] data_frame = data_frame[data_frame.func_id != '\Verb{precalc}'] plot(p_data=data_frame, p_yId='runtime', p_xId='obj_cells', p_hueId='func_id', p_styleId=None, p_logScale=True, p_export_filename='runtime_by_cells.svg', p_xLabel="Object Cells", p_yLabel="Runtime [s]") plot(p_data=data_frame, p_yId='efficiency', p_xId='obj_cells', p_hueId='func_id', p_styleId=None, p_logScale=True, p_marker_label='precalc', p_marker_value=1, p_export_filename='efficiency_by_cells.svg', p_xLabel="Object Cells", p_yLabel="Absolute Efficiency") ###Output _____no_output_____ ###Markdown Arithmetic Intensity by cost Empirically Determined Parametersbased on `src_master_thesis/node_characterization/likwid-bench_gauss3.out`: ###Code emp_flops_max=2459.32383 emp_mem_band=233.172 import pandas as pd import seaborn as sns sns.set_theme() sns.set_style("ticks") maschine_balance=emp_flops_max/emp_mem_band ops_data = pd.read_csv('./e_measure_ops.csv') ops_data['func_id'] = ops_data.apply(lambda row: f'nonlinear_{row["func_id"].lower()}', axis=1) roofline_data = pd.read_csv('./e_roofline.csv') roofline_data = roofline_data[roofline_data.region_id == 'apply'] roofline_data = roofline_data.merge(ops_data, left_on='impl_id', right_on='func_id') roofline_data['func_id'] = 'function cost' roofline_data['ai']=roofline_data.apply(lambda row: (row['mflop_s']/row['mbytes_s']), axis=1) # # NOTE: add maschine balance # roofline_data_copy = roofline_data.copy() roofline_data_copy['func_id'] = 'maschine balance' roofline_data_copy['ai'] = maschine_balance roofline_data = roofline_data_copy.append(roofline_data) # display(roofline_data) plot(p_data=roofline_data, p_yId='ai', p_xId='ops', p_hueId='func_id', p_styleId=None, p_logScale=False) ###Output _____no_output_____ ###Markdown Performance by cost ###Code import pandas as pd import seaborn as sns sns.set_theme() sns.set_style("ticks") ops_data = pd.read_csv('./e_measure_ops.csv') ops_data['func_id'] = ops_data.apply(lambda row: f'nonlinear_{row["func_id"].lower()}', axis=1) roofline_data = pd.read_csv('./e_roofline.csv') roofline_data = roofline_data[roofline_data.region_id == 'apply'] roofline_data = roofline_data.merge(ops_data, left_on='impl_id', right_on='func_id') display(roofline_data) roofline_data['gflop_s']=roofline_data.apply(lambda row: (row['mflop_s']/1000), axis=1) plot(p_data=roofline_data, p_yId='gflop_s', p_xId='ops', p_hueId=None, p_styleId=None, p_logScale=False) ###Output _____no_output_____
extra-course-parts/13_Classes.ipynb
###Markdown 13. Classes*Combine building blocks* 13.1 Introduction****The code we've been writing so far has been a sequential set of commands and functions where variables have to be passed around from function to function whenever required. Python is, however, inherently an *object-oriented* programming language. This means that you can create *objects* that are self-sustained building blocks of code or data which you can combine to form more complex programs.In fact we've been using objects all along; strings are objects, as are lists and dictionaries - the *methods* we've been using on them (for example *myList.sort()*) are part of these objects.The concept of objects is not very intuitive, but we'll give you a taste here so you can see how powerful it is in practice. 13.2 Exercises******Creating a class, the template for an object**First you have to create a template for your object; this determines what an object can do once you start to use it. This template is called a **class**. Consider this example: ###Code # Define the MyMathOperations class # Note that we start the class name with an uppercase letter to distinguish it from normal variables class MyMathClass: def add(self,x,y): print(x + y) def subtract(self,x,y): print(x - y) def multiply(self,x,y): print(x * y) ###Output _____no_output_____ ###Markdown So within a class you define the *methods* add(), substract() and multiply(). The argument list for each of these has to start with **self** - this means it belongs to this class, and can be called from it using the **.add()** syntax as we used for strings, lists and dictionaries. **Using an object**When you execute the above example, nothing happens. This is because the class is not *instantiated* to become a working *object*. It's very easy to do this and then use the class; add these lines to the above example: ###Code if __name__ == '__main__': # Instantiate the object from the class myMathObject = MyMathClass() myMathObject.add(3,5) myMathObject.subtract(5,4) myMathObject.multiply(9,3) ###Output 8 1 27 ###Markdown One big immediate advantage of doing this is that you can group similar functions (methods) together, and only have to call up the class to be able to execute them (you don't have to import all of the functions separately).You can also connect variables to a class. You can do this when you instantiate (initialise) the class, or change/add new ones later on. Consider this modified example: ###Code class MyNewMathClass: # This method is called when initialising the class def __init__(self,x,y): self.x = x self.y = y def add(self): return self.x + self.y def subtract(self): return self.x - self.y def multiply(self): return self.x * self.y def doSomeOperations(self): print("Numbers {} and {}".format(self.x,self.y)) print(" Adding...", self.add()) print(" Subtracting...", self.subtract()) print(" Multiplying...", self.multiply()) print if __name__ == '__main__': # Instantiate the object from the class myMathObject = MyNewMathClass(3,5) myMathObject.doSomeOperations() myMathObject.x = 5 myMathObject.y = 4 myMathObject.doSomeOperations() ###Output Numbers 3 and 5 Adding... 8 Subtracting... -2 Multiplying... 15 Numbers 5 and 4 Adding... 9 Subtracting... 1 Multiplying... 20 ###Markdown **Exercise**Write your own class that takes two strings on startup. It should have a method to check which letters are shared between the two strings, and another method to check which are unique in each string. You should then write out this information. ###Code class MyStringClass: # This method is called when initialising the class def __init__(self,string1,string2): # This method is called when initialising the class self.string1 = string1 self.string2 = string2 # Already make sets for comparisons later... self.stringSet1 = set(string1) self.stringSet2 = set(string2) def getSharedCharacters(self): return self.stringSet1.intersection(self.stringSet2) def getUniqueCharacters(self): uniqueChars1 = self.stringSet1.difference(self.stringSet2) uniqueChars2 = self.stringSet2.difference(self.stringSet1) return (uniqueChars1,uniqueChars2) def doCharacterCheck(self): print ("Strings '{}' and '{}'".format(self.string1,self.string2)) print (" Shared characters are {}".format(", ".join(self.getSharedCharacters()))) (uniqueChars1,uniqueChars2) = self.getUniqueCharacters() print (" Unique in string1 are {}".format(", ".join(uniqueChars1))) print (" Unique in string2 are {}".format(", ".join(uniqueChars2))) print if __name__ == '__main__': # Instantiate the object from the class stringComparer = MyStringClass('myWord','otherWord') stringComparer.doCharacterCheck() ###Output Strings 'myWord' and 'otherWord' Shared characters are W, o, r, d Unique in string1 are m, y Unique in string2 are t, h, e ###Markdown **Combining classes**The object-oriented way of programming becomes really powerful when you start to combine classes; in programming speak you can create a *subclass* that *inherits* the methods, variables, ... from one or several other classes (the *superclasses*). This way you can use classes as 'building blocks' to create more complex programs very quickly: ###Code class MyInputClass: def getUserInput(self,questionString): userInput = None while not userInput: userInput = input(questionString) return userInput def getUserString(self): return self.getUserInput("Please enter a string: ") class MyStringClass: # This is a modified version of the class introduced earlier def setStringsAndCreateStringSets(self,string1,string2): self.string1 = string1 self.string2 = string2 # Already make sets for comparisons later... self.stringSet1 = set(string1) self.stringSet2 = set(string2) def getSharedCharacters(self): return self.stringSet1.intersection(self.stringSet2) class UserStringSharedCharacters(MyInputClass,MyStringClass): def getSharedCharactersFromUserStrings(self): string1 = self.getUserString() string2 = self.getUserString() self.setStringsAndCreateStringSets(string1,string2) sharedCharacters = self.getSharedCharacters() print ("Shared characters between '{}' and '{}' are {}".format(string1,string2,', '.join(sharedCharacters))) if __name__ == '__main__': userStringSharedChars = UserStringSharedCharacters() userStringSharedChars.getSharedCharactersFromUserStrings() ###Output Please enter a string: abcdef Please enter a string: dcvare Shared characters between 'abcdef' and 'dcvare' are e, a, c, d ###Markdown **Exercise**Convert the program to read in the sample information from exercise 9. Make a class that contains a generic CSV file reader (the comma-separated format), then another one that deals specifically with the information in this particular file, and then prints out the IDs for value ranges in the same way. Everything should be done as classes. ###Code import os class CsvFile: def readCsvFile(self,fileName): # Read in a .csv (comma-delimited) format file # Doublecheck if file exists if not os.path.exists(fileName): print("File {} does not exist!".format(fileName)) return None # Open the file and read the information fileHandle = open(fileName) lines = fileHandle.readlines() fileHandle.close() # Now read the information. The first line has the header information which # we are going to use to create the dictionary! fileInfoDict = {} fileInfoDict['headers'] = lines[0].strip().split(',') fileInfoDict['data'] = [] # Now read in the information for line in lines[1:]: line = line.strip() # Remove newline characters cols = line.split(',') fileInfoDict['data'].append(cols) # Return the dictionary with the file information return fileInfoDict class SampleInformationFile(CsvFile): def readFile(self,fileName): fileInfoDict = self.readCsvFile(fileName) # Reorganise generic information from file in correct way.. self.sampleInformation = {} for dataList in fileInfoDict['data']: sampleId = int(dataList[0]) self.sampleInformation[sampleId] = {} for i in range(1,len(fileInfoDict['headers'])): valueName = fileInfoDict['headers'][i] value = dataList[i] if valueName in ('pH','temperature','volume'): value = float(value) self.sampleInformation[sampleId][valueName] = value # No need to return anything; the data is stored in self.sampleInformation, and this is accessible from anywhere in this object... def getSampleIdsForValueRange(self,valueName,lowValue,highValue): # Return the sample IDs that fit within the given value range for a kind of value sampleIdList = self.sampleInformation.keys() sampleIdList = sorted(sampleIdList) sampleIdsFound = [] for sampleId in sampleIdList: currentValue = self.sampleInformation[sampleId][valueName] if lowValue <= currentValue <= highValue: sampleIdsFound.append(sampleId) return sampleIdsFound if __name__ == '__main__': sampleInfoFile = SampleInformationFile() sampleInfoFile.readFile("data/SampleInfo.txt") print(sampleInfoFile.getSampleIdsForValueRange('pH',6.0,7.0)) print(sampleInfoFile.getSampleIdsForValueRange('temperature',280,290)) print(sampleInfoFile.getSampleIdsForValueRange('volume',200,220)) ###Output [3, 7, 10, 12, 16, 20] [3, 4, 5, 6, 9, 11, 17, 20] [8, 10, 14, 15]
lsh-py/docs/source/sections/LSH_recall.ipynb
###Markdown Base LSH and Multi Probe LSH exampleDownload color histograms of the flick30k dataset [here](https://www.kaggle.com/ritchie46/flickr30khistograms/download). ###Code import numpy as np from scipy.spatial.distance import cdist from floky import L2 import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import ScalarFormatter import time ###Output _____no_output_____ ###Markdown Data preparationFirst we load the data in numpy. Next we compute the real $N$ nearest neighbors with `scipy.spatial.distance.cdist`. From these $N$ distance results we compute the mean and determine the top k results. Next we scale the data by $R$. This makes it easier to verify if the LSH algorithm can find nearest neighbors.If we scale the data by $\frac{1}{R}$ we expect the exact Nearest Neighbor to have a distance smaller than 1. If this isn't the case, we need to choose another distance $R$. ###Code with open("flickr30k_histograms.csv") as f: a = np.loadtxt(f, delimiter=",") # We will do N queries and compute recall and query times. N = 100 # Find the exact nearest neighbors. This is needed to compute recall. t0 = time.time_ns() dist = cdist(a[:N], a) # ms exact_duration = (time.time_ns() - t0) / 1e6 exact_duration # non trivial top 1 # we skip the first as that is the query point itself top_k = dist.argsort(1)[:, 1:2] mean = dist.mean() top_k_dist = dist[np.arange(N)[:, None], top_k] # Scale data by distance. So scaled R will be 1. R = mean / 2.5 a /= R dist /= R top_k_dist /= R R # Check if real nearest neigbors are < R = 1 print("{}% < R".format((top_k_dist < 1).sum() / (top_k_dist.shape[0] * top_k_dist.shape[1]) * 100)) top_k_dist[:10] ###Output 83.0% < R ###Markdown Comparison Query / Preprocessing duration and RecallBelow we'll examine the impact of the query duration on the recall.We take a look at two **k** ( of values in the hash) values: * 15 * 30 For Base LSH we increase the numebr of hash tables to increase the recall.For Multi-probe LSH we increase the number of probes we execute. We will keep the number of hash tables constant to only **5**. ###Code def cum_mov_avg(x, avg, n): return (x + n * avg) / (n + 1) def recall(k, L): dim = len(a[0]) lsh = L2(k, L, dim, in_mem=True) t0 = time.time() lsh.fit(a) fit_duration = time.time() - t0 t0 = time.time_ns() p = lsh.predict(a[:N], only_index=True, top_k=6); predict_duration = time.time_ns() - t0 c = 0 avg_collisions = 0 for i, pi in enumerate(p): if pi.n_collisions == 1: continue idx = set(pi.index[1:]) if len(idx.intersection(top_k[i])) > 0: c += 1 avg_collisions = cum_mov_avg(pi.n_collisions, avg_collisions, i) return c / N, avg_collisions, fit_duration, predict_duration ks = [] Ls = [] recalls = [] avg_cs = [] duration_fit = [] duration_predict = [] for k in [15, 30]: for L in [5, 10, 15, 20, 50, 100]: ks.append(k) Ls.append(L) r, avg_collision, fit_duration, predict_duration = recall(k, L) duration_fit.append(fit_duration) duration_predict.append(predict_duration) recalls.append(r) avg_cs.append(avg_collision) df = pd.DataFrame({"recall": recalls, "avg_collisions": avg_cs, "L": Ls, "K": ks, "duration_fit": duration_fit, "duration_predict": duration_predict }) df def recall_multi_probe(k, budget, lsh): lsh.multi_probe(budget) t0 = time.time_ns() p = lsh.predict(a[:N], only_index=True, top_k=6); predict_duration = time.time_ns() - t0 c = 0 avg_collisions = 0 for i, pi in enumerate(p): if pi.n_collisions == 1: continue idx = set(pi.index[1:]) if len(idx.intersection(top_k[i])) > 0: c += 1 avg_collisions = cum_mov_avg(pi.n_collisions, avg_collisions, i) return c / N, avg_collisions, predict_duration ks = [] recalls = [] avg_cs = [] probes = [] duration_fit = [] duration_predict = [] for k in [15, 30]: dim = len(a[0]) t0 = time.time() lsh = L2(k, 5, dim, in_mem=True) fit_duration = time.time() - t0 lsh.fit(a) for probe in [10, 20, 15, 20, 50, 100]: ks.append(k) probes.append(probe) r, avg_collision, predict_duration = recall_multi_probe(k, probe, lsh) duration_predict.append(predict_duration) duration_fit.append(fit_duration) recalls.append(r) avg_cs.append(avg_collision) df_mp = pd.DataFrame({"recall": recalls, "avg_collisions": avg_cs, "probes": probes, "K": ks, "duration_fit": duration_fit, "duration_predict": duration_predict }) df_mp fig, ax = plt.subplots(figsize=(20, 6), nrows=2, ncols=3) for i, (k, df_) in enumerate(df.groupby("K")): color = f"C{i}" marker = "^" ax[0, 0].plot(df_.L, df_.recall, c=color, marker=marker, label=f"k = {k}") ax[0, 1].plot(df_.L, df_.duration_predict / 1e6, c=color, marker=marker) ax[0, 2].plot(df_.L, df_.duration_fit, c=color, marker=marker) for i, (k, df_) in enumerate(df_mp.groupby("K")): color = f"C{i}" ax[1, 0].plot(df_.probes, df_.recall, c=color, marker=marker, label=f"k = {k}") ax[1, 1].plot(df_.probes, df_.duration_predict / 1e6, c=color, marker=marker) ax[1, 2].plot(df_.probes, df_.duration_fit, c=color, marker=marker) ax[0, 0].legend() ax[1, 0].legend() ax[0, 1].axhline(exact_duration, c="black", label="exact search") ax[1, 1].axhline(exact_duration, c="black", label="exact search") ax[0, 1].legend() ax[1, 1].legend() plt.xlabel("L") ax[0, 0].set_ylabel("recall") ax[0, 0].set_ylim(0, 1) ax[0, 0].set_xlabel("L hashtables") ax[0, 1].set_xlabel("L hashtables") ax[0, 1].set_ylabel("query duration [ms]") ax[0, 1].set_ylim(0, exact_duration * 1.05) ax[0, 2].set_ylabel("fit duration [s]") ax[0, 2].set_xlabel("L hashtables") ax[1, 0].set_ylabel("recall") ax[1, 0].set_xlabel("# probes") ax[1, 0].set_ylim(0, 1) ax[1, 0].set_xscale("log") ax[1, 0].xaxis.set_major_formatter(ScalarFormatter()) ax[1, 1].set_xlabel("# probes") ax[1, 1].set_ylabel("query duration [ms]") ax[1, 1].xaxis.set_major_formatter(ScalarFormatter()) ax[1, 1].yaxis.set_major_formatter(ScalarFormatter()) ax[1, 1].set_ylim(0, exact_duration * 1.05) ax[1, 2].set_ylabel("fit duration [s]") ax[1, 2].set_xlabel("# probes") plt.show() ###Output _____no_output_____
30-problem-solution_introduction_to_altair.ipynb
###Markdown - Create a scatter plot showing the relationship between Horsepower and Miles_per_Gallon- Did this relationship change over time? ###Code alt.Chart(data).mark_point().encode(x='Horsepower', y='Miles_per_Gallon') alt.Chart(data).mark_point().encode(x='Horsepower', y='Miles_per_Gallon', row='Year') ###Output _____no_output_____
benchmark/12.average_precision_repliating_dl.ipynb
###Markdown In this notebook we calculate `mean average precision` for a subset of the plates (U2OS at the longest time point) whose features were extracted using a pre-trained neural network. The following are the steps taken1. Augmented ORF, CRISPR and Compound profiles are read and the replicate plates are merged into a single dataframe.2. The augmented ORF, CRISPR and Compound profiles are spherized separately.3. Negative control and empty wells are removed from the dataframe.4. Negative control and empty wells are removed from the dataframe.5. Average precision (AP) is computed for each replicate of each perturbation and the mean average precision (mAP) is computed for each condition.6. The same is repeated after shuffling the dataframe which is an estimate of the null distribution.7. Table of mAP values is printed and bar plot of mAP values is plotted. ###Code cell = "U2OS" mean_average_precision_df = pd.DataFrame() group_by_feature = 'Metadata_broad_sample' batch = "2020_11_04_CPJUMP1_DL" experiment_df = ( pd.read_csv('output/experiment-metadata.tsv', sep='\t') .query('Batch==@batch') ) for modality in experiment_df.Perturbation.unique(): modality_df = experiment_df.query('Perturbation==@modality') for time_point in modality_df.Time.unique(): time_df = modality_df.query('Time==@time_point') all_plates_df = pd.DataFrame() for plate in time_df.Assay_Plate_Barcode.unique(): plate_df = utils.load_data(batch, plate, "spherized.csv.gz") all_plates_df = utils.concat_profiles(all_plates_df, plate_df) all_plates_df = utils.remove_negcon_empty_wells(all_plates_df) score = utils.MeanAveragePrecision(all_plates_df, all_plates_df, group_by_feature) mean_average_precision_df = mean_average_precision_df.append({'Description':f'{modality}_{cell}_{time_point}', 'Modality':f'{modality}', 'Cell':f'{cell}', 'time':f'{time_point}', 'mAP':f'{score.map:.3f}', 'feature_set_replicates':'DP_True'}, ignore_index=True) all_plates_shuffled_df = utils.shuffle_profiles(all_plates_df) score_shuffled = utils.MeanAveragePrecision(all_plates_shuffled_df, all_plates_shuffled_df, group_by_feature) mean_average_precision_df = mean_average_precision_df.append({'Description':f'{modality}_{cell}_{time_point}', 'Modality':f'{modality}', 'Cell':f'{cell}', 'time':f'{time_point}', 'mAP':f'{score_shuffled.map:.3f}', 'feature_set_replicates':'DP_Shuffled'}, ignore_index=True) print(mean_average_precision_df[['Description', 'mAP','feature_set_replicates']].query('feature_set_replicates=="DP_True"').to_markdown(index=False)) print(mean_average_precision_df[['Description', 'mAP','feature_set_replicates']].query('feature_set_replicates=="DP_Shuffled"').to_markdown(index=False)) mean_average_precision_df['mAP'] = mean_average_precision_df['mAP'].astype(float) mean_average_precision_df.loc[(mean_average_precision_df.Modality=='compound') & (mean_average_precision_df.time=='24'), 'time'] = 'short' mean_average_precision_df.loc[(mean_average_precision_df.Modality=='compound') & (mean_average_precision_df.time=='48'), 'time'] = 'long' mean_average_precision_df.loc[(mean_average_precision_df.Modality=='crispr') & (mean_average_precision_df.time=='96'), 'time'] = 'short' mean_average_precision_df.loc[(mean_average_precision_df.Modality=='crispr') & (mean_average_precision_df.time=='144'), 'time'] = 'long' mean_average_precision_df.loc[(mean_average_precision_df.Modality=='orf') & (mean_average_precision_df.time=='48'), 'time'] = 'short' mean_average_precision_df.loc[(mean_average_precision_df.Modality=='orf') & (mean_average_precision_df.time=='96'), 'time'] = 'long' plot_mAP_df = ( mean_average_precision_df.rename(columns={'Modality':'Perturbation'}) ) fig = px.bar(data_frame=plot_mAP_df, x='Perturbation', y='mAP', color='feature_set_replicates', barmode='overlay', facet_row='time', facet_col='Cell') fig.update_layout(title='mAP vs. Perturbation', yaxis=dict(title='mAP'), yaxis3=dict(title='mAP')) fig.show("png") fig.write_image(f'figures/12.mAP_CellProfiler.png', width=640, height=480, scale=2) print(plot_mAP_df[['Description','Perturbation','time', 'Cell' ,'mAP', 'feature_set_replicates']].to_markdown(index=False)) plot_mAP_df.to_csv('output/deepprofiler_mAP.csv', index=False) ###Output _____no_output_____
OPC_Sensor/Models with Min Max Normalization/KNN/.ipynb_checkpoints/KNN-checkpoint.ipynb
###Markdown Importing Libraries ###Code import numpy as np import pandas as pd from matplotlib import pyplot as plt import os.path as op import pickle ###Output _____no_output_____ ###Markdown Data Fetching ###Code A1=np.empty((0,5),dtype='float32') U1=np.empty((0,7),dtype='float32') node=['150','149','147','144','142','140','136','61'] mon=['Apr','Mar','Aug','Jun','Jul','Sep','May','Oct'] for j in node: for i in mon: inp= pd.read_csv('../data_gkv/AT510_Node_'+str(j)+'_'+str(i)+'19_OutputFile.csv',usecols=[1,2,3,15,16],low_memory=False) out= pd.read_csv('../data_gkv/AT510_Node_'+str(j)+'_'+str(i)+'19_OutputFile.csv',usecols=[5,6,7,8,17,18,19],low_memory=False) inp=np.array(inp,dtype='float32') out=np.array(out,dtype='float32') A1=np.append(A1, inp, axis=0) U1=np.append(U1, out, axis=0) print(A1) print(U1) ###Output [[1.50000e+02 1.90401e+05 7.25000e+02 2.75500e+01 8.03900e+01] [1.50000e+02 1.90401e+05 8.25000e+02 2.75600e+01 8.03300e+01] [1.50000e+02 1.90401e+05 9.25000e+02 2.75800e+01 8.02400e+01] ... [6.10000e+01 1.91020e+05 1.94532e+05 2.93700e+01 7.52100e+01] [6.10000e+01 1.91020e+05 1.94632e+05 2.93500e+01 7.52700e+01] [6.10000e+01 1.91020e+05 1.94732e+05 2.93400e+01 7.53000e+01]] [[ 28. 3. -52. ... 16.97 19.63 20.06] [ 28. 15. -53. ... 16.63 19.57 23.06] [ 31. 16. -55. ... 17.24 19.98 20.24] ... [ 76. 12. -76. ... 3.47 3.95 4.35] [ 75. 13. -76. ... 3.88 4.33 4.42] [ 76. 12. -75. ... 3.46 4.07 4.28]] ###Markdown Min Max Scaler ###Code from sklearn.preprocessing import MinMaxScaler import warnings scaler_obj=MinMaxScaler() X1=scaler_obj.fit_transform(A1) Y1=scaler_obj.fit_transform(U1) warnings.filterwarnings(action='ignore', category=UserWarning) ###Output _____no_output_____ ###Markdown Model ###Code from sklearn.neighbors import KNeighborsRegressor from sklearn.multioutput import MultiOutputRegressor # Splitting Data into training and testing dataset from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(X1,Y1,test_size=0.25,random_state=42) model6 =MultiOutputRegressor(KNeighborsRegressor(n_neighbors=7,weights='uniform',algorithm='auto',leaf_size=50,p=2)) model_fit6=model6.fit(x_train, y_train) print('Model Training done!!') # Dumping Model into a file filename6 = 'Models_File/knn.sav' pickle.dump(model_fit6, open(filename6, 'wb')) ###Output Model Training done!! ###Markdown Error Analysis ###Code from sklearn import metrics from sklearn.metrics import r2_score train_sizes=['NO2','O3','NO','CO','PM1','PM2.5','PM10'] y_test_pred6=model_fit6.predict(x_test) y_train_pred6=model_fit6.predict(x_train) #finding out the r2 score r2_test6=r2_score(y_test,y_test_pred6,multioutput='variance_weighted') r2_train6=r2_score(y_train,y_train_pred6,multioutput='variance_weighted') print('r2 score on train data '+ str(r2_train6)) print('r2 score on test data '+ str(r2_test6)) knn_mae=metrics.mean_absolute_error(y_test, y_test_pred6) knn_mse=metrics.mean_squared_error(y_test, y_test_pred6) knn_rmse=np.sqrt(metrics.mean_squared_error(y_test, y_test_pred6)) print('Mean Absolute Error:',knn_mae) print('Mean Squared Error:',knn_mse ) print('Root Mean Squared Error:',knn_rmse) import pickle from sklearn.metrics import r2_score from sklearn import metrics from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(X1,Y1,test_size=0.25,random_state=42) loaded_model_fit7 = pickle.load(open("knn.sav", 'rb')) y_test_pred=loaded_model_fit7.predict(x_test) print("Predicted :\n",y_test_pred) r2_test=r2_score(y_test,y_test_pred,multioutput='variance_weighted') print("R2 Score : ",r2_test) ###Output Predicted : [[0.00011546 0.06553679 0.00010997 ... 0.00640681 0.00386692 0.00135243] [0.00011029 0.06553687 0.00012299 ... 0.00811652 0.00491546 0.00169688] [0.00011284 0.06553693 0.00011782 ... 0.0196785 0.01237714 0.0042929 ] ... [0.00011125 0.06553665 0.00011532 ... 0.05718024 0.03629992 0.01205484] [0.0001149 0.06553687 0.00010984 ... 0.00784995 0.00463913 0.00165329] [0.00011033 0.06553662 0.00012027 ... 0.0052287 0.00358975 0.00154209]] R2 Score : 0.650844072704262 ###Markdown y-test vs y-predict ###Code # printing y_test and y_test_predict print("Y_Test:",y_test) print("Y_Test_Predict:",y_test_pred6) from matplotlib import style style.use('ggplot') for i in range(0,7): plt.figure(figsize=[12,10]) plt.plot(y_test[:,i],linewidth=3, markersize=12) plt.plot(y_test_pred6[:,i],linewidth=2, markersize=12) plt.xlabel('X') plt.ylabel(train_sizes[i]) plt.show() ###Output Y_Test: [[0.00011559 0.06553685 0.00011085 ... 0.0021448 0.0014142 0.00052142] [0.00011088 0.06553695 0.00012144 ... 0.01090628 0.00639894 0.00234271] [0.0001138 0.06553686 0.00011756 ... 0.02938369 0.01855402 0.00761428] ... [0.00011103 0.06553663 0.00011547 ... 0.05674056 0.03595096 0.01243099] [0.00011477 0.06553688 0.00010965 ... 0.00815022 0.00468672 0.00148292] [0.00010879 0.06553657 0.00012025 ... 0.00375339 0.00246608 0.00081172]] Y_Test_Predict: [[0.00011546 0.06553679 0.00010997 ... 0.00640681 0.00386692 0.00135243] [0.00011029 0.06553687 0.00012299 ... 0.00811652 0.00491546 0.00169688] [0.00011284 0.06553693 0.00011782 ... 0.0196785 0.01237714 0.0042929 ] ... [0.00011125 0.06553665 0.00011532 ... 0.05718024 0.03629992 0.01205484] [0.0001149 0.06553687 0.00010984 ... 0.00784995 0.00463913 0.00165329] [0.00011033 0.06553662 0.00012027 ... 0.0052287 0.00358975 0.00154209]]
matplotlib/gallery_jupyter/pyplots/fig_axes_customize_simple.ipynb
###Markdown Fig Axes Customize SimpleCustomize the background, labels and ticks of a simple plot. ###Code import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown ``plt.figure`` creates a ```matplotlib.figure.Figure`` instance ###Code fig = plt.figure() rect = fig.patch # a rectangle instance rect.set_facecolor('lightgoldenrodyellow') ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) rect = ax1.patch rect.set_facecolor('lightslategray') for label in ax1.xaxis.get_ticklabels(): # label is a Text instance label.set_color('tab:red') label.set_rotation(45) label.set_fontsize(16) for line in ax1.yaxis.get_ticklines(): # line is a Line2D instance line.set_color('tab:green') line.set_markersize(25) line.set_markeredgewidth(3) plt.show() ###Output _____no_output_____ ###Markdown ------------References""""""""""The use of the following functions, methods, classes and modules is shownin this example: ###Code import matplotlib matplotlib.axis.Axis.get_ticklabels matplotlib.axis.Axis.get_ticklines matplotlib.text.Text.set_rotation matplotlib.text.Text.set_fontsize matplotlib.text.Text.set_color matplotlib.lines.Line2D matplotlib.lines.Line2D.set_color matplotlib.lines.Line2D.set_markersize matplotlib.lines.Line2D.set_markeredgewidth matplotlib.patches.Patch.set_facecolor ###Output _____no_output_____
aula06_2020_09_10_backpropagation_iris_dataset.ipynb
###Markdown BACKPROPAGATION IRIS DATASET ###Code random.seed(5000) ###Output _____no_output_____ ###Markdown Carregar dados da Iris ###Code with open('Dataset/data_iris.txt') as csvfile: csvreader = csv.reader(csvfile) dataset = list(csvreader) ###Output _____no_output_____ ###Markdown Padronizar dados para valores numericos ###Code for row in dataset: row[4] = ["Iris-setosa", "Iris-versicolor", "Iris-virginica"].index(row[4]) row[:4] = [float(row[j]) for j in range(len(row))] ###Output _____no_output_____ ###Markdown Dividir os dados para trinamento ###Code random.shuffle(dataset) datatrain = dataset[:int(len(dataset) * 0.8)] datatest = dataset[int(len(dataset) * 0.8):] train_X = [data[:4] for data in datatrain] train_y = [data[4] for data in datatrain] test_X = [data[:4] for data in datatest] test_y = [data[4] for data in datatest] ###Output _____no_output_____ ###Markdown Multiplicação das matrizes para teste ###Code def matrix_mul_bias(A, B, bias): C = [[0 for i in range(len(B[0]))] for i in range(len(A))] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): C[i][j] += A[i][k] * B[k][j] C[i][j] += bias[j] return C ###Output _____no_output_____ ###Markdown Multiplicação do vetor A com matriz B ###Code def vec_mat_bias(A, B, bias): C = [0 for i in range(len(B[0]))] for j in range(len(B[0])): for k in range(len(B)): C[j] += A[k] * B[k][j] C[j] += bias[j] return C ###Output _____no_output_____ ###Markdown Multiplicação das para Backpropagation ###Code def mat_vec(A, B): C = [0 for i in range(len(A))] for i in range(len(A)): for j in range(len(B)): C[i] += A[i][j] * B[j] return C ###Output _____no_output_____ ###Markdown Função de Sigmoid ###Code def sigmoid(A, deriv=False): if deriv: for i in range(len(A)): A[i] = A[i] * (1 - A[i]) else: for i in range(len(A)): A[i] = 1 / (1 + math.exp(-A[i])) return A ###Output _____no_output_____ ###Markdown Parametros para treinamento ###Code alfa = 0.005 epoch = 1000 neuron = [4, 5, 3] ###Output _____no_output_____ ###Markdown Iniciar pesos e bias ###Code weight = [[0 for j in range(neuron[1])] for i in range(neuron[0])] weight_2 = [[0 for j in range(neuron[2])] for i in range(neuron[1])] bias = [0 for i in range(neuron[1])] bias_2 = [0 for i in range(neuron[2])] ###Output _____no_output_____ ###Markdown Iniciar pesos com valores randômicos [-1.0 | 1.0] ###Code for i in range(neuron[0]): for j in range(neuron[1]): weight[i][j] = 2 * random.random() - 1 for i in range(neuron[1]): for j in range(neuron[2]): weight_2[i][j] = 2 * random.random() - 1 show_total_cost = '' for e in range(epoch): cost_total = 0 for idx, x in enumerate(train_X): # forward propagation h_1 = vec_mat_bias(x, weight, bias) X_1 = sigmoid(h_1) h_2 = vec_mat_bias(X_1, weight_2, bias_2) X_2 = sigmoid(h_2) # converter para único target = [0, 0, 0] target[int(train_y[idx])] = 1 # função de custo, erro de raiz quadrada eror = 0 for i in range(neuron[2]): eror += (target[i] - X_2[i]) ** 2 cost_total += eror * 1 / neuron[2] # backpropagation # atualização dos pesos e bias camada 2 delta_2 = [] for j in range(neuron[2]): delta_2.append(-1 * 2. / neuron[2] * (target[j]-X_2[j]) * X_2[j] * (1-X_2[j])) for i in range(neuron[1]): for j in range(neuron[2]): weight_2[i][j] -= alfa * (delta_2[j] * X_1[i]) bias_2[j] -= alfa * delta_2[j] # atualização dos pesos e bias camada 1 delta_1 = mat_vec(weight_2, delta_2) for j in range(neuron[1]): delta_1[j] = delta_1[j] * (X_1[j] * (1-X_1[j])) for i in range(neuron[0]): for j in range(neuron[1]): weight[i][j] -= alfa * (delta_1[j] * x[i]) bias[j] -= alfa * delta_1[j] cost_total /= len(train_X) if(e % 100 == 0): show_total_cost += f'Custo total: {cost_total}\n' # print(f'Custo total: {cost_total}') ###Output _____no_output_____ ###Markdown Testes ###Code res = matrix_mul_bias(test_X, weight, bias) res_2 = matrix_mul_bias(res, weight_2, bias) ###Output _____no_output_____ ###Markdown Obter previsão ###Code preds = [] for r in res_2: preds.append(max(enumerate(r), key=lambda x:x[1])[0]) ###Output _____no_output_____ ###Markdown Cálculo de precisão ###Code acc = 0.0 for i in range(len(preds)): if preds[i] == int(test_y[i]): acc += 1 accuracy = acc / len(preds) * 100 print(show_total_cost) print(f'Previsão: {preds}') print(f'Precisão: {accuracy:.2f}%') ###Output Custo total: 0.34550111123583205 Custo total: 0.13149238823242787 Custo total: 0.10949941015860527 Custo total: 0.09704320839532987 Custo total: 0.08506138069831262 Custo total: 0.07289757613509798 Custo total: 0.06139907048319877 Custo total: 0.05157342318796261 Custo total: 0.04379695079398785 Custo total: 0.03786338701243066 Previsão: [2, 0, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 0, 2, 1, 2, 0, 1, 1, 2, 1, 1, 0, 2, 2, 0, 1, 2, 1, 1] Precisão: 83.33%
6.Deep_Reinforcement_Learning/gym/Deep_Q-learning-cart_DQN_using_tensorflow.ipynb
###Markdown In conda env openAIsudo -H pip install python=3.5 sudo -H pip install tensorflow==1.3 Also Kernel should be openAI ###Code %%bash pwd ###Output /Users/parksoy/Desktop/Soyoung_Udacity_ND_DeepLearning/6.Deep_Reinforcement_Learning/gym ###Markdown Deep $Q$-learningIn this notebook, we'll build a neural network that can learn to play games through reinforcement learning. More specifically, we'll use $Q$-learning to train an agent to play a game called [Cart-Pole](https://gym.openai.com/envs/CartPole-v0). In this game, a freely swinging pole is attached to a cart. The cart can move to the left and right, and the goal is to keep the pole upright as long as possible.![Cart-Pole](assets/cart-pole.jpg)We can simulate this game using [OpenAI Gym](https://github.com/openai/gym). First, let's check out how OpenAI Gym works. Then, we'll get into training an agent to play the Cart-Pole game. ###Code import gym import numpy as np # Create the Cart-Pole game environment env = gym.make('CartPole-v1') # Number of possible actions print('Number of possible actions:', env.action_space.n, env.action_space) ###Output WARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype. Number of possible actions: 2 Discrete(2) ###Markdown We interact with the simulation through `env`. You can see how many actions are possible from `env.action_space.n`, and to get a random action you can use `env.action_space.sample()`. Passing in an action as an integer to `env.step` will generate the next step in the simulation. This is general to all Gym games. In the Cart-Pole game, there are two possible actions, moving the cart left or right. So there are two actions we can take, encoded as 0 and 1.Run the code below to interact with the environment. ###Code actions = [] # actions that the agent selects rewards = [] # obtained rewards state = env.reset() while True: action = env.action_space.sample() # choose a random action state, reward, done, _ = env.step(action) rewards.append(reward) actions.append(action) if done: break ###Output _____no_output_____ ###Markdown We can look at the actions and rewards: ###Code print('Actions:', actions) print('Rewards:', rewards) ###Output Actions: [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1] Rewards: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] ###Markdown The game resets after the pole has fallen past a certain angle. For each step while the game is running, it returns a reward of 1.0. The longer the game runs, the more reward we get. Then, our network's goal is to maximize the reward by keeping the pole vertical. It will do this by moving the cart to the left and the right. $Q$-NetworkTo keep track of the action values, we'll use a neural network that accepts a state $s$ as input. The output will be $Q$-values for each available action $a$ (i.e., the output is **all** action values $Q(s,a)$ _corresponding to the input state $s$_).For this Cart-Pole game, the state has four values: the position and velocity of the cart, and the position and velocity of the pole. Thus, the neural network has **four inputs**, one for each value in the state, and **two outputs**, one for each possible action. As explored in the lesson, to get the training target, we'll first use the context provided by the state $s$ to choose an action $a$, then simulate the game using that action. This will get us the next state, $s'$, and the reward $r$. With that, we can calculate $\hat{Q}(s,a) = r + \gamma \max_{a'}{Q(s', a')}$. Then we update the weights by minimizing $(\hat{Q}(s,a) - Q(s,a))^2$. Below is one implementation of the $Q$-network. It uses two fully connected layers with ReLU activations. Two seems to be good enough, three might be better. Feel free to try it out. ###Code import tensorflow as tf class QNetwork: def __init__(self, learning_rate=0.01, state_size=4, action_size=2, hidden_size=10, name='QNetwork'): # state inputs to the Q-network with tf.variable_scope(name): self.inputs_ = tf.placeholder(tf.float32, [None, state_size], name='inputs') # One hot encode the actions to later choose the Q-value for the action self.actions_ = tf.placeholder(tf.int32, [None], name='actions') one_hot_actions = tf.one_hot(self.actions_, action_size) # Target Q values for training self.targetQs_ = tf.placeholder(tf.float32, [None], name='target') # ReLU hidden layers self.fc1 = tf.contrib.layers.fully_connected(self.inputs_, hidden_size) self.fc2 = tf.contrib.layers.fully_connected(self.fc1, hidden_size) # Linear output layer self.output = tf.contrib.layers.fully_connected(self.fc2, action_size, activation_fn=None) #Train with loss (targetQ - Q)^2 #output has length 2, for two actions. This next line chooses #one value from output (per row) according to the one-hot encoded actions. self.Q = tf.reduce_sum(tf.multiply(self.output, one_hot_actions), axis=1) self.loss = tf.reduce_mean(tf.square(self.targetQs_ - self.Q)) self.opt = tf.train.AdamOptimizer(learning_rate).minimize(self.loss) ###Output /Users/parksoy/anaconda3/envs/openAI/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /Users/parksoy/anaconda3/envs/openAI/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) ###Markdown Experience replayReinforcement learning algorithms can have stability issues due to correlations between states. To reduce correlations when training, we can store the agent's experiences and later draw a random mini-batch of those experiences to train on. Here, we'll create a `Memory` object that will store our experiences, our transitions $$. This memory will have a maximum capacity, so we can keep newer experiences in memory while getting rid of older experiences. Then, we'll sample a random mini-batch of transitions $$ and train on those.Below, I've implemented a `Memory` object. If you're unfamiliar with `deque`, this is a double-ended queue. You can think of it like a tube open on both sides. You can put objects in either side of the tube. But if it's full, adding anything more will push an object out the other side. This is a great data structure to use for the memory buffer. ###Code from collections import deque class Memory(): def __init__(self, max_size=1000): self.buffer = deque(maxlen=max_size) def add(self, experience): self.buffer.append(experience) def sample(self, batch_size): idx = np.random.choice(np.arange(len(self.buffer)), size=batch_size, replace=False) return [self.buffer[ii] for ii in idx] ###Output _____no_output_____ ###Markdown $Q$-Learning training algorithmWe will use the below algorithm to train the network. For this game, the goal is to keep the pole upright for 195 frames. So we can start a new episode once meeting that goal. The game ends if the pole tilts over too far, or if the cart moves too far the left or right. When a game ends, we'll start a new episode. Now, to train the agent:* Initialize the memory $D$* Initialize the action-value network $Q$ with random weights* **For** episode $\leftarrow 1$ **to** $M$ **do** * Observe $s_0$ * **For** $t \leftarrow 0$ **to** $T-1$ **do** * With probability $\epsilon$ select a random action $a_t$, otherwise select $a_t = \mathrm{argmax}_a Q(s_t,a)$ * Execute action $a_t$ in simulator and observe reward $r_{t+1}$ and new state $s_{t+1}$ * Store transition $$ in memory $D$ * Sample random mini-batch from $D$: $$ * Set $\hat{Q}_j = r_j$ if the episode ends at $j+1$, otherwise set $\hat{Q}_j = r_j + \gamma \max_{a'}{Q(s'_j, a')}$ * Make a gradient descent step with loss $(\hat{Q}_j - Q(s_j, a_j))^2$ * **endfor*** **endfor**You are welcome (and encouraged!) to take the time to extend this code to implement some of the improvements that we discussed in the lesson, to include fixed $Q$ targets, double DQNs, prioritized replay, and/or dueling networks. HyperparametersOne of the more difficult aspects of reinforcement learning is the large number of hyperparameters. Not only are we tuning the network, but we're tuning the simulation. ###Code train_episodes = 1000 # max number of episodes to learn from max_steps = 200 # max steps in an episode gamma = 0.99 # future reward discount # Exploration parameters explore_start = 1.0 # exploration probability at start explore_stop = 0.01 # minimum exploration probability decay_rate = 0.0001 # exponential decay rate for exploration prob # Network parameters hidden_size = 64 # number of units in each Q-network hidden layer learning_rate = 0.0001 # Q-network learning rate # Memory parameters memory_size = 10000 # memory capacity batch_size = 20 # experience mini-batch size pretrain_length = batch_size # number experiences to pretrain the memory tf.reset_default_graph() mainQN = QNetwork(name='main', hidden_size=hidden_size, learning_rate=learning_rate) ###Output /Users/parksoy/anaconda3/envs/openAI/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /Users/parksoy/anaconda3/envs/openAI/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /Users/parksoy/anaconda3/envs/openAI/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) ###Markdown Populate the experience memoryHere we re-initialize the simulation and pre-populate the memory. The agent is taking random actions and storing the transitions in memory. This will help the agent with exploring the game. ###Code # Initialize the simulation env.reset() # Take one random step to get the pole and cart moving state, reward, done, _ = env.step(env.action_space.sample()) memory = Memory(max_size=memory_size) # Make a bunch of random actions and store the experiences for ii in range(pretrain_length): # Make a random action action = env.action_space.sample() next_state, reward, done, _ = env.step(action) if done: # The simulation fails so no next state next_state = np.zeros(state.shape) # Add experience to memory memory.add((state, action, reward, next_state)) # Start new episode env.reset() # Take one random step to get the pole and cart moving state, reward, done, _ = env.step(env.action_space.sample()) else: # Add experience to memory memory.add((state, action, reward, next_state)) state = next_state ###Output _____no_output_____ ###Markdown TrainingBelow we'll train our agent. ###Code # Now train with experiences saver = tf.train.Saver() rewards_list = [] with tf.Session() as sess: # Initialize variables sess.run(tf.global_variables_initializer()) step = 0 for ep in range(1, train_episodes): total_reward = 0 t = 0 while t < max_steps: step += 1 # Uncomment this next line to watch the training env.render() # Explore or Exploit explore_p = explore_stop + (explore_start - explore_stop)*np.exp(-decay_rate*step) if explore_p > np.random.rand(): # Make a random action action = env.action_space.sample() else: # Get action from Q-network #feed = {mainQN.inputs_: state.reshape((1, *state.shape))} Qs = sess.run(mainQN.output, feed_dict={mainQN.inputs_: state.reshape((1, *state.shape))}) action = np.argmax(Qs) # Take action, get new state and reward next_state, reward, done, _ = env.step(action) total_reward += reward if done: # the episode ends so no next state next_state = np.zeros(state.shape) t = max_steps print('Episode: {}'.format(ep), 'Total reward: {}'.format(total_reward), 'Training loss: {:.4f}'.format(loss), 'Explore P: {:.4f}'.format(explore_p)) rewards_list.append((ep, total_reward)) # Add experience to memory memory.add((state, action, reward, next_state)) # Start new episode env.reset() # Take one random step to get the pole and cart moving state, reward, done, _ = env.step(env.action_space.sample()) else: # Add experience to memory memory.add((state, action, reward, next_state)) state = next_state t += 1 # Sample mini-batch from memory batch = memory.sample(batch_size) states = np.array([each[0] for each in batch]) actions = np.array([each[1] for each in batch]) rewards = np.array([each[2] for each in batch]) next_states = np.array([each[3] for each in batch]) # Train network target_Qs = sess.run(mainQN.output, feed_dict={mainQN.inputs_: next_states}) # Set target_Qs to 0 for states where episode ends episode_ends = (next_states == np.zeros(states[0].shape)).all(axis=1) target_Qs[episode_ends] = (0, 0) targets = rewards + gamma * np.max(target_Qs, axis=1) loss, _ = sess.run([mainQN.loss, mainQN.opt], feed_dict={mainQN.inputs_: states, mainQN.targetQs_: targets, mainQN.actions_: actions}) saver.save(sess, "checkpoints/cartpole.ckpt") ###Output Episode: 1 Total reward: 3.0 Training loss: 1.1599 Explore P: 0.9997 Episode: 2 Total reward: 20.0 Training loss: 1.1814 Explore P: 0.9977 Episode: 3 Total reward: 15.0 Training loss: 1.1074 Explore P: 0.9962 Episode: 4 Total reward: 22.0 Training loss: 1.2165 Explore P: 0.9941 Episode: 5 Total reward: 15.0 Training loss: 1.0962 Explore P: 0.9926 Episode: 6 Total reward: 14.0 Training loss: 1.1756 Explore P: 0.9912 Episode: 7 Total reward: 21.0 Training loss: 1.2184 Explore P: 0.9892 Episode: 8 Total reward: 24.0 Training loss: 1.2125 Explore P: 0.9868 Episode: 9 Total reward: 11.0 Training loss: 1.2785 Explore P: 0.9857 Episode: 10 Total reward: 15.0 Training loss: 1.2947 Explore P: 0.9843 Episode: 11 Total reward: 17.0 Training loss: 1.3504 Explore P: 0.9826 Episode: 12 Total reward: 15.0 Training loss: 1.1414 Explore P: 0.9812 Episode: 13 Total reward: 35.0 Training loss: 1.4642 Explore P: 0.9778 Episode: 14 Total reward: 15.0 Training loss: 1.3605 Explore P: 0.9763 Episode: 15 Total reward: 26.0 Training loss: 1.4965 Explore P: 0.9738 Episode: 16 Total reward: 10.0 Training loss: 1.3594 Explore P: 0.9729 Episode: 17 Total reward: 12.0 Training loss: 1.3288 Explore P: 0.9717 Episode: 18 Total reward: 12.0 Training loss: 1.5042 Explore P: 0.9705 Episode: 19 Total reward: 15.0 Training loss: 1.5071 Explore P: 0.9691 Episode: 20 Total reward: 15.0 Training loss: 1.5344 Explore P: 0.9677 Episode: 21 Total reward: 19.0 Training loss: 1.7653 Explore P: 0.9659 Episode: 22 Total reward: 10.0 Training loss: 1.4561 Explore P: 0.9649 Episode: 23 Total reward: 30.0 Training loss: 1.7309 Explore P: 0.9620 Episode: 24 Total reward: 22.0 Training loss: 1.5788 Explore P: 0.9599 Episode: 25 Total reward: 16.0 Training loss: 2.1181 Explore P: 0.9584 Episode: 26 Total reward: 26.0 Training loss: 1.7890 Explore P: 0.9560 Episode: 27 Total reward: 20.0 Training loss: 1.4674 Explore P: 0.9541 Episode: 28 Total reward: 11.0 Training loss: 1.8882 Explore P: 0.9530 Episode: 29 Total reward: 16.0 Training loss: 2.0678 Explore P: 0.9515 Episode: 30 Total reward: 12.0 Training loss: 1.6757 Explore P: 0.9504 Episode: 31 Total reward: 35.0 Training loss: 2.3059 Explore P: 0.9471 Episode: 32 Total reward: 21.0 Training loss: 3.9898 Explore P: 0.9451 Episode: 33 Total reward: 16.0 Training loss: 3.5834 Explore P: 0.9437 Episode: 34 Total reward: 8.0 Training loss: 2.5676 Explore P: 0.9429 Episode: 35 Total reward: 28.0 Training loss: 3.4999 Explore P: 0.9403 Episode: 36 Total reward: 11.0 Training loss: 4.7156 Explore P: 0.9393 Episode: 37 Total reward: 27.0 Training loss: 4.6368 Explore P: 0.9368 Episode: 38 Total reward: 23.0 Training loss: 4.9790 Explore P: 0.9346 Episode: 39 Total reward: 13.0 Training loss: 18.6209 Explore P: 0.9334 Episode: 40 Total reward: 25.0 Training loss: 8.5095 Explore P: 0.9311 Episode: 41 Total reward: 12.0 Training loss: 3.0701 Explore P: 0.9300 Episode: 42 Total reward: 18.0 Training loss: 6.6973 Explore P: 0.9284 Episode: 43 Total reward: 27.0 Training loss: 9.2620 Explore P: 0.9259 Episode: 44 Total reward: 14.0 Training loss: 5.6347 Explore P: 0.9246 Episode: 45 Total reward: 10.0 Training loss: 7.5204 Explore P: 0.9237 Episode: 46 Total reward: 29.0 Training loss: 18.0371 Explore P: 0.9211 Episode: 47 Total reward: 13.0 Training loss: 6.4436 Explore P: 0.9199 Episode: 48 Total reward: 24.0 Training loss: 21.0477 Explore P: 0.9177 Episode: 49 Total reward: 16.0 Training loss: 3.2908 Explore P: 0.9162 Episode: 50 Total reward: 10.0 Training loss: 7.7244 Explore P: 0.9153 Episode: 51 Total reward: 18.0 Training loss: 22.4228 Explore P: 0.9137 Episode: 52 Total reward: 20.0 Training loss: 12.0076 Explore P: 0.9119 Episode: 53 Total reward: 14.0 Training loss: 4.9683 Explore P: 0.9106 Episode: 54 Total reward: 36.0 Training loss: 4.9670 Explore P: 0.9074 Episode: 55 Total reward: 44.0 Training loss: 4.5941 Explore P: 0.9035 Episode: 56 Total reward: 11.0 Training loss: 31.7736 Explore P: 0.9025 Episode: 57 Total reward: 9.0 Training loss: 4.5797 Explore P: 0.9017 Episode: 58 Total reward: 9.0 Training loss: 18.3685 Explore P: 0.9009 Episode: 59 Total reward: 39.0 Training loss: 28.3731 Explore P: 0.8974 Episode: 60 Total reward: 20.0 Training loss: 9.7233 Explore P: 0.8956 Episode: 61 Total reward: 23.0 Training loss: 16.9201 Explore P: 0.8936 Episode: 62 Total reward: 11.0 Training loss: 9.1767 Explore P: 0.8926 Episode: 63 Total reward: 14.0 Training loss: 35.6544 Explore P: 0.8914 Episode: 64 Total reward: 12.0 Training loss: 16.3475 Explore P: 0.8903 Episode: 65 Total reward: 25.0 Training loss: 17.7496 Explore P: 0.8881 Episode: 66 Total reward: 14.0 Training loss: 12.2471 Explore P: 0.8869 Episode: 67 Total reward: 15.0 Training loss: 5.3807 Explore P: 0.8856 Episode: 68 Total reward: 10.0 Training loss: 15.5058 Explore P: 0.8847 Episode: 69 Total reward: 11.0 Training loss: 5.6644 Explore P: 0.8838 Episode: 70 Total reward: 17.0 Training loss: 5.1486 Explore P: 0.8823 Episode: 71 Total reward: 31.0 Training loss: 39.6477 Explore P: 0.8796 Episode: 72 Total reward: 16.0 Training loss: 17.3608 Explore P: 0.8782 Episode: 73 Total reward: 9.0 Training loss: 51.9727 Explore P: 0.8774 Episode: 74 Total reward: 24.0 Training loss: 4.9196 Explore P: 0.8753 Episode: 75 Total reward: 7.0 Training loss: 43.4169 Explore P: 0.8747 Episode: 76 Total reward: 17.0 Training loss: 8.8308 Explore P: 0.8733 Episode: 77 Total reward: 15.0 Training loss: 6.8456 Explore P: 0.8720 Episode: 78 Total reward: 9.0 Training loss: 34.9034 Explore P: 0.8712 Episode: 79 Total reward: 19.0 Training loss: 5.1730 Explore P: 0.8695 Episode: 80 Total reward: 11.0 Training loss: 6.3333 Explore P: 0.8686 Episode: 81 Total reward: 17.0 Training loss: 58.5313 Explore P: 0.8671 Episode: 82 Total reward: 28.0 Training loss: 31.3829 Explore P: 0.8647 Episode: 83 Total reward: 60.0 Training loss: 43.2549 Explore P: 0.8596 Episode: 84 Total reward: 9.0 Training loss: 34.1543 Explore P: 0.8589 Episode: 85 Total reward: 11.0 Training loss: 80.6658 Explore P: 0.8579 Episode: 86 Total reward: 10.0 Training loss: 20.5472 Explore P: 0.8571 Episode: 87 Total reward: 15.0 Training loss: 79.1897 Explore P: 0.8558 Episode: 88 Total reward: 14.0 Training loss: 75.7503 Explore P: 0.8546 Episode: 89 Total reward: 12.0 Training loss: 7.4997 Explore P: 0.8536 Episode: 90 Total reward: 24.0 Training loss: 39.0961 Explore P: 0.8516 Episode: 91 Total reward: 27.0 Training loss: 26.0492 Explore P: 0.8493 Episode: 92 Total reward: 20.0 Training loss: 7.3271 Explore P: 0.8477 Episode: 93 Total reward: 21.0 Training loss: 54.3442 Explore P: 0.8459 Episode: 94 Total reward: 10.0 Training loss: 65.0093 Explore P: 0.8451 Episode: 95 Total reward: 10.0 Training loss: 22.7581 Explore P: 0.8442 Episode: 96 Total reward: 11.0 Training loss: 8.7713 Explore P: 0.8433 Episode: 97 Total reward: 45.0 Training loss: 6.1900 Explore P: 0.8396 Episode: 98 Total reward: 18.0 Training loss: 49.6014 Explore P: 0.8381 Episode: 99 Total reward: 15.0 Training loss: 67.9963 Explore P: 0.8368 Episode: 100 Total reward: 34.0 Training loss: 26.8744 Explore P: 0.8340 Episode: 101 Total reward: 10.0 Training loss: 11.8253 Explore P: 0.8332 Episode: 102 Total reward: 10.0 Training loss: 11.3261 Explore P: 0.8324 Episode: 103 Total reward: 12.0 Training loss: 10.4733 Explore P: 0.8314 Episode: 104 Total reward: 12.0 Training loss: 83.9013 Explore P: 0.8304 Episode: 105 Total reward: 20.0 Training loss: 50.8625 Explore P: 0.8288 Episode: 106 Total reward: 10.0 Training loss: 237.4370 Explore P: 0.8280 Episode: 107 Total reward: 21.0 Training loss: 11.1711 Explore P: 0.8262 Episode: 108 Total reward: 13.0 Training loss: 9.8193 Explore P: 0.8252 Episode: 109 Total reward: 17.0 Training loss: 197.8580 Explore P: 0.8238 Episode: 110 Total reward: 16.0 Training loss: 10.9191 Explore P: 0.8225 Episode: 111 Total reward: 14.0 Training loss: 38.1945 Explore P: 0.8214 Episode: 112 Total reward: 22.0 Training loss: 13.8786 Explore P: 0.8196 Episode: 113 Total reward: 52.0 Training loss: 145.6032 Explore P: 0.8154 Episode: 114 Total reward: 32.0 Training loss: 57.4257 Explore P: 0.8128 Episode: 115 Total reward: 13.0 Training loss: 15.1616 Explore P: 0.8118 ###Markdown Visualizing trainingBelow we plot the total rewards for each episode. The rolling average is plotted in blue. ###Code %matplotlib inline import matplotlib.pyplot as plt def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / N eps, rews = np.array(rewards_list).T #(ep, total_reward) smoothed_rews = running_mean(rews, 10) plt.plot(eps[-len(smoothed_rews):], smoothed_rews, label='running_mean') plt.plot(eps, rews, color='grey', alpha=0.3, label='rewards_list') plt.xlabel('Episode') plt.ylabel('Total Reward') plt.legend() ###Output _____no_output_____ ###Markdown ![png](output_21_1.png) Playing Atari GamesSo, Cart-Pole is a pretty simple game. However, the same model can be used to train an agent to play something much more complicated like Pong or Space Invaders. Instead of a state like we're using here though, you'd want to use convolutional layers to get the state from the screen images.![Deep Q-Learning Atari](assets/atari-network.png)I'll leave it as a challenge for you to use deep Q-learning to train an agent to play Atari games. Here's the original paper which will get you started: http://www.davidqiu.com:8888/research/nature14236.pdf. ###Code env.close() ###Output _____no_output_____
doc/load_json.ipynb
###Markdown Season ###Code import requests import json # read the JSON file from the web json_file = 'https://raw.githubusercontent.com/emorynlp/character-mining/master/json/friends_season_01.json' r = requests.get(json_file) # load season 1 season = json.loads(r.text) season_id = season['season_id'] print(season_id) ###Output s01 ###Markdown Episodes ###Code # retrieve episodes episodes = season['episodes'] # iterate through the episodes for episode in episodes: episode_id = episode['episode_id'] print(episode_id) ###Output s01_e01 s01_e02 s01_e03 s01_e04 s01_e05 s01_e06 s01_e07 s01_e08 s01_e09 s01_e10 s01_e11 s01_e12 s01_e13 s01_e14 s01_e15 s01_e16 s01_e17 s01_e18 s01_e19 s01_e20 s01_e21 s01_e22 s01_e23 s01_e24 ###Markdown Scenes ###Code # retrive scenes from the 18th episode episode = episodes[17] scenes = episode['scenes'] # iterate through the scenes for scene in scenes: scene_id = scene['scene_id'] print(scene_id) ###Output s01_e18_c01 s01_e18_c02 s01_e18_c03 s01_e18_c04 s01_e18_c05 s01_e18_c06 s01_e18_c07 s01_e18_c08 ###Markdown Utterances ###Code # retrieve utterances from the 5th scene scene = scenes[4] utterances = scene['utterances'] # iterate through the utterances for utterance in utterances: utterance_id = utterance['utterance_id'] print(utterance_id) ###Output s01_e18_c05_u001 s01_e18_c05_u002 s01_e18_c05_u003 s01_e18_c05_u004 s01_e18_c05_u005 s01_e18_c05_u006 s01_e18_c05_u007 s01_e18_c05_u008 s01_e18_c05_u009 s01_e18_c05_u010 s01_e18_c05_u011 s01_e18_c05_u012 s01_e18_c05_u013 s01_e18_c05_u014 s01_e18_c05_u015 s01_e18_c05_u016 s01_e18_c05_u017 s01_e18_c05_u018 s01_e18_c05_u019 s01_e18_c05_u020 s01_e18_c05_u021 s01_e18_c05_u022 ###Markdown Utterance ###Code # retrive fields from the 18th utterance utterance = utterances[17] # list of speakers speakers = utterance['speakers'] print(speakers) # the original transcript transcript = utterance['transcript'] print(transcript) # list of sentences, where each sentence is a list of tokens tokens = utterance['tokens'] print(tokens) ###Output ['Phoebe Buffay', 'Rachel Green'] Yes, we should. I think we should. [['Yes', ',', 'we', 'should', '.'], ['I', 'think', 'we', 'should', '.']] ###Markdown For seasons 6-9, caption information is available. ###Code # load season 6 json_file = 'https://raw.githubusercontent.com/emorynlp/character-mining/master/json/friends_season_06.json' r = requests.get(json_file) season = json.loads(r.text) # 1st episode, 1st scene, 3rd utterance utterance = season['episodes'][0]['scenes'][0]['utterances'][2] caption = utterance['caption'] print('Begin time in milliseconds: %d' % caption[0]) print('End time in milliseconds: %d' % caption[1]) print('Text: %s' % caption[2]) ###Output Begin time in milliseconds: 6923 End time in milliseconds: 8382 Text: you sure you wanna do this
scripts/BuildDataset.ipynb
###Markdown Criação da base de dados Import ###Code import pandas as pd from csv import reader import os.path from os import path import json ###Output _____no_output_____ ###Markdown Variáveis Globais ###Code repositories_path = '../results/evaluatedProjects.csv' dt_g_columns = ['project_name','file','class','type','cbo','cboModified','fanin','fanout','wmc','dit','noc','rfc','lcom','lcom*','tcc','lcc','totalMethodsQty','staticMethodsQty','publicMethodsQty','privateMethodsQty','protectedMethodsQty','defaultMethodsQty','visibleMethodsQty','abstractMethodsQty','finalMethodsQty','synchronizedMethodsQty','totalFieldsQty','staticFieldsQty','publicFieldsQty','privateFieldsQty','protectedFieldsQty','defaultFieldsQty','finalFieldsQty','synchronizedFieldsQty','nosi','loc','returnQty','loopQty','comparisonsQty','tryCatchQty','parenthesizedExpsQty','stringLiteralsQty','numbersQty','assignmentsQty','mathOperationsQty','variablesQty','maxNestedBlocksQty','anonymousClassesQty','innerClassesQty','lambdasQty','uniqueWordsQty','modifiers','logStatementsQty','isLargeClassOrganic'] dt_g = pd.DataFrame(columns = dt_g_columns) repositories = pd.read_csv(repositories_path, usecols=['Nome']) removed_repositories = [] ###Output _____no_output_____ ###Markdown Unificação dos dados coletados nas métricas ###Code with open(repositories_path, 'r') as read_obj: csv_reader = reader(read_obj) header = next(csv_reader) if header != None: for row in csv_reader: if row: repository_name = row[0] metrics_result_path = '../results/'+repository_name+'/class.csv' if os.path.getsize(metrics_result_path) > 0 : repository = pd.read_csv(metrics_result_path) df_r = pd.DataFrame(repository) df_r['project_name'] = repository_name if df_r.shape[0] > 0: dt_g = pd.merge(dt_g,df_r, how='outer') else: removed_repositories.append(repository_name) else: removed_repositories.append(repository_name) ###Output geral tamanho 0 geral tamanho 0 somando 0 1676 resultado 1676 geral tamanho 1676 somando 1676 4 resultado 1680 geral tamanho 1680 geral tamanho 1680 somando 1680 10176 resultado 11856 geral tamanho 11856 somando 11856 26750 resultado 38606 geral tamanho 38606 somando 38606 257 resultado 38863 geral tamanho 38863 somando 38863 752 resultado 39615 geral tamanho 39615 somando 39615 14350 resultado 53965 geral tamanho 53965 somando 53965 11856 resultado 65821 geral tamanho 65821 somando 65821 488 resultado 66309 geral tamanho 66309 somando 66309 1 resultado 66310 geral tamanho 66310 somando 66310 1088 resultado 67398 geral tamanho 67398 somando 67398 3531 resultado 70929 geral tamanho 70929 somando 70929 306 resultado 71235 geral tamanho 71235 somando 71235 266 resultado 71501 geral tamanho 71501 somando 71501 1445 resultado 72946 geral tamanho 72946 somando 72946 21562 resultado 94508 geral tamanho 94508 somando 94508 670 resultado 95178 geral tamanho 95178 somando 95178 3 resultado 95181 geral tamanho 95181 somando 95181 15038 resultado 110219 geral tamanho 110219 somando 110219 585 resultado 110804 geral tamanho 110804 somando 110804 2140 resultado 112944 geral tamanho 112944 somando 112944 6568 resultado 119512 geral tamanho 119512 somando 119512 765 resultado 120277 geral tamanho 120277 somando 120277 589 resultado 120866 geral tamanho 120866 somando 120866 222 resultado 121088 geral tamanho 121088 somando 121088 173 resultado 121261 geral tamanho 121261 somando 121261 1138 resultado 122399 geral tamanho 122399 somando 122399 272 resultado 122671 geral tamanho 122671 somando 122671 60 resultado 122731 geral tamanho 122731 somando 122731 5584 resultado 128315 geral tamanho 128315 somando 128315 482 resultado 128797 geral tamanho 128797 somando 128797 7061 resultado 135858 geral tamanho 135858 somando 135858 6328 resultado 142186 geral tamanho 142186 somando 142186 287 resultado 142473 geral tamanho 142473 somando 142473 183 resultado 142656 geral tamanho 142656 somando 142656 94 resultado 142750 geral tamanho 142750 somando 142750 415 resultado 143165 geral tamanho 143165 somando 143165 2276 resultado 145441 geral tamanho 145441 somando 145441 378 resultado 145819 geral tamanho 145819 somando 145819 513 resultado 146332 geral tamanho 146332 somando 146332 157 resultado 146489 geral tamanho 146489 somando 146489 2005 resultado 148494 geral tamanho 148494 geral tamanho 148494 somando 148494 1063 resultado 149557 geral tamanho 149557 somando 149557 4580 resultado 154137 geral tamanho 154137 somando 154137 1827 resultado 155964 geral tamanho 155964 somando 155964 2350 resultado 158314 geral tamanho 158314 somando 158314 2202 resultado 160516 geral tamanho 160516 somando 160516 592 resultado 161108 geral tamanho 161108 somando 161108 5505 resultado 166613 geral tamanho 166613 somando 166613 621 resultado 167234 geral tamanho 167234 somando 167234 163 resultado 167397 geral tamanho 167397 somando 167397 852 resultado 168249 geral tamanho 168249 somando 168249 3906 resultado 172155 geral tamanho 172155 somando 172155 54 resultado 172209 geral tamanho 172209 somando 172209 7836 resultado 180045 geral tamanho 180045 somando 180045 2556 resultado 182601 geral tamanho 182601 somando 182601 1934 resultado 184535 geral tamanho 184535 somando 184535 1407 resultado 185942 geral tamanho 185942 somando 185942 3855 resultado 189797 geral tamanho 189797 somando 189797 1522 resultado 191319 geral tamanho 191319 somando 191319 2246 resultado 193565 geral tamanho 193565 somando 193565 23795 resultado 217360 geral tamanho 217360 somando 217360 51 resultado 217411 geral tamanho 217411 somando 217411 11147 resultado 228558 geral tamanho 228558 somando 228558 45 resultado 228603 geral tamanho 228603 somando 228603 287 resultado 228890 geral tamanho 228890 somando 228890 563 resultado 229453 geral tamanho 229453 somando 229453 509 resultado 229962 geral tamanho 229962 somando 229962 140 resultado 230102 geral tamanho 230102 somando 230102 617 resultado 230719 geral tamanho 230719 somando 230719 1542 resultado 232261 geral tamanho 232261 somando 232261 1575 resultado 233836 geral tamanho 233836 somando 233836 91 resultado 233927 geral tamanho 233927 somando 233927 22916 resultado 256843 geral tamanho 256843 somando 256843 1472 resultado 258315 geral tamanho 258315 somando 258315 1704 resultado 260019 geral tamanho 260019 somando 260019 143 resultado 260162 geral tamanho 260162 somando 260162 160 resultado 260322 geral tamanho 260322 somando 260322 499 resultado 260821 geral tamanho 260821 somando 260821 509 resultado 261330 geral tamanho 261330 somando 261330 88 resultado 261418 geral tamanho 261418 somando 261418 67 resultado 261485 geral tamanho 261485 somando 261485 776 resultado 262261 geral tamanho 262261 somando 262261 105 resultado 262366 geral tamanho 262366 somando 262366 16 resultado 262382 geral tamanho 262382 somando 262382 114 resultado 262496 geral tamanho 262496 somando 262496 403 resultado 262899 geral tamanho 262899 somando 262899 3 resultado 262902 geral tamanho 262902 somando 262902 269 resultado 263171 geral tamanho 263171 somando 263171 1776 resultado 264947 geral tamanho 264947 somando 264947 98 resultado 265045 geral tamanho 265045 somando 265045 45 resultado 265090 geral tamanho 265090 somando 265090 139 resultado 265229 geral tamanho 265229 somando 265229 1080 resultado 266309 geral tamanho 266309 somando 266309 1580 resultado 267889 geral tamanho 267889 somando 267889 28 resultado 267917 ###Markdown repositórios removidos ###Code print(removed_repositories) ###Output ['JavaGuide', 'advanced-java', 'guava', 'toBeTopJavaer'] ###Markdown Unificação dos dados coletados com as ferramentas de _code smells_ ###Code organic_result_path = '../results/elasticsearch-analysis-ik/organicResult.json' organic_results = json.load(open(organic_result_path,'r')) for result in organic_results: dataframe_class = pd.DataFrame.from_dict(result, orient="index") row_dt = dt_g.loc[dt_g['file'] == result['sourceFile']['file']['path']] row_dt['isLargeClassOrganic'] = result['smells'] isLargeClas = row_dt['isLargeClassOrganic'] ###Output _____no_output_____
notebooks/09_clean_all_data.ipynb
###Markdown 1. Load raw combined data ###Code # Load movie+book data import pandas as pd all_data_df = pd.read_pickle('../data/all_data') all_data_df.shape all_df = all_data_df.drop(columns=['vote','metascore','keywords']).\ drop_duplicates(subset=['movie_title','director']) all_df.rename(columns = {'certificate':'MPAA','star':'actor','year':'publish_year',\ 'rating_value':'rating_value_b','rating_count':'rating_count_b','review_count':'review_count_b'},\ inplace=True) all_df.info() ###Output <class 'pandas.core.frame.DataFrame'> Int64Index: 837 entries, 0 to 18138 Data columns (total 30 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 movie_title 837 non-null object 1 rating 837 non-null float64 2 MPAA 837 non-null object 3 genre 837 non-null object 4 release_date 837 non-null datetime64[ns] 5 budget 810 non-null float64 6 opening_weekend_usa 596 non-null float64 7 gross_usa 636 non-null float64 8 gross_world 683 non-null float64 9 runtime 833 non-null float64 10 distributor 836 non-null object 11 language 837 non-null object 12 country 837 non-null object 13 director 837 non-null object 14 writer 837 non-null object 15 actor 837 non-null object 16 author 837 non-null object 17 rating_value_b 837 non-null float64 18 rating_count_b 837 non-null float64 19 review_count_b 837 non-null float64 20 page 818 non-null float64 21 publish_year 835 non-null float64 22 title 837 non-null object 23 book_popularity 837 non-null float64 24 author_popularity 837 non-null float64 25 release_year 837 non-null int64 26 count_a 837 non-null int64 27 film_count_d 837 non-null int64 28 avg_rating_d 837 non-null float64 29 avg_gross_d 837 non-null int64 dtypes: datetime64[ns](1), float64(14), int64(4), object(11) memory usage: 202.7+ KB ###Markdown 2. Examine features * Book and author popularity ###Code # Load book_history_2 book_history = pd.read_pickle('../dump/book_history_2_data') book_history['release_date'] = book_history['release_date'].astype('datetime64[ns]') book_history.info() np.log(book_history.title_search).hist(bins=20) np.log(book_history.search_fiction_book).hist(bins=20) np.log(book_history.author_search).hist(bins=20) np.log(book_history.search_fiction_author).hist(bins=20) all_df['book_popularity_test'] = all_df['title_search'] / all_df['search_fiction_book'] # log plot distribution looks ok np.log(all_df['book_popularity_test']).hist() all_df['log_book_popularity'] = np.log(all_df['book_popularity_test']) # Same for author populatiry all_df['author_popularity_test'] = all_df['author_search'] / all_df['search_fiction_author'] np.log(all_df['author_popularity_test']).hist() all_df['log_author_popularity'] = np.log(all_df['author_popularity_test']) all_df.shape all_df.to_pickle('../dump/complete_data') ###Output _____no_output_____ ###Markdown 3. Simple EDA ###Code all_df.corr() # sns.heatmap(all_df.corr(), cmap="seismic", annot=True, vmin=-1, vmax=1); sns.heatmap(all_df.corr(), cmap="seismic", vmin=-0.8, vmax=1); continuous_variables = ['opening_weekend_usa', 'gross_usa', 'gross_world','rating', \ 'budget','runtime','release_year', 'release_month','dow',\ 'film_count_d', 'avg_rating_d', 'avg_gross_d', \ 'page', 'publish_year','log_book_search','title_search','search_fiction_book', \ 'log_author_search','author_search', 'search_fiction_author',\ 'book_popularity', 'author_popularity'] all_df_select = all_df[continuous_variables] # sns.pairplot(all_df_select) ###Output _____no_output_____ ###Markdown 4. Clean each columnClean the format and convert data type if necessarry for later steps. (1) Target variable (i) opening_weekend_usa ###Code # Examine the distribution. Pretty skewed. all_df['opening_weekend_usa'].hist(bins=20) # all_df['opening_weekend_usa'] # Try log. Slightly better. Still not very normal np.log(all_df['opening_weekend_usa']).hist(bins=20) # demonstration of the power transform on data with a skew from numpy import exp from numpy.random import randn from sklearn.preprocessing import PowerTransformer from matplotlib import pyplot as plt # generate gaussian data sample data = randn(1000) # add a skew to the data distribution data = exp(data) # histogram of the raw data with a skew plt.hist(data, bins=25) plt.show() # reshape data to have rows and columns data = data.reshape((len(data),1)) # power transform the raw data power = PowerTransformer(method='yeo-johnson', standardize=True) data_trans = power.fit_transform(data) # histogram of the transformed data plt.hist(data_trans, bins=25) plt.show() # Explore power transform data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='yeo-johnson', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Explore power transform (box-cox) data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Seems like both log and power transform are similarr all_df['log_owu'] = np.log(all_df['opening_weekend_usa']) data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) all_df['log_owu'] = data_trans.reshape(len(data),) all_df.shape ###Output _____no_output_____ ###Markdown (ii) gross_world ###Code # Examine the distribution. Pretty skewed. # all_df['opening_weekend_usa'].hist(bins=20) all_df['gross_world'] # Try log. Slightly better. Still not very normal np.log(all_df['gross_world']).hist(bins=20) # demonstration of the power transform on data with a skew from numpy import exp from numpy.random import randn from sklearn.preprocessing import PowerTransformer from matplotlib import pyplot as plt # generate gaussian data sample data = randn(1000) # add a skew to the data distribution data = exp(data) # histogram of the raw data with a skew plt.hist(data, bins=25) plt.show() # reshape data to have rows and columns data = data.reshape((len(data),1)) # power transform the raw data power = PowerTransformer(method='yeo-johnson', standardize=True) data_trans = power.fit_transform(data) # histogram of the transformed data plt.hist(data_trans, bins=25) plt.show() # Explore power transform data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='yeo-johnson', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Explore power transform (box-cox) data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Seems like both log and power transform are similarr all_df['log_owu'] = np.log(all_df['opening_weekend_usa']) data = all_df[['opening_weekend_usa']] power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) all_df['log_owu'] = data_trans.reshape(len(data),) all_df.shape ###Output _____no_output_____ ###Markdown (ii) IMDb rating ###Code # Distribution looks ok. Will keep it as it is for now. all_df['rating'].hist(bins=20) ###Output _____no_output_____ ###Markdown (2) Independent variables (predictors) (a) Continuous variables 1. time ###Code # Movie release year all_df['release_year'].hist(bins=20) # Convert to "how old" the movie is (2020-all_df['release_year']).hist(bins=20) # Try power transform data = (all_df[['release_year']].apply(lambda x: 2022 - x)) power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Create a new column in case needed in the futurre all_df['T_movie_age'] = data_trans.reshape(len(data),) # Also check for book first published year (2020-all_df['publish_year']).hist(bins=20) # Try power transform data = (all_df[['publish_year']].apply(lambda x: 2021 - x)) power = PowerTransformer(method='box-cox', standardize=True) data_trans = power.fit_transform(data) plt.hist(data_trans, bins=25) plt.show() # Create a new column in case needed in the futurre all_df['T_book_age'] = data_trans.reshape(len(data),) # Save the cleaned all_df all_df.to_pickle('../data/complete_data_cleaned') ###Output _____no_output_____
scripts/tugas1b.ipynb
###Markdown Kecerdasan Buatan Tugas 1: Model Linear MekanismeAnda hanya diwajibkan untuk mengumpulkan file ini saja ke uploader yang disediakan di http://elearning2.uai.ac.id/. Ganti nama file ini saat pengumpulan menjadi tugas1_NIM.ipynb.**Keterlambatan**: Pengumpulan tugas yang melebihi tenggat yang telah ditentukan tidak akan diterima. Keterlambatan akan berakibat pada nilai nol untuk tugas ini.**Kolaborasi**: Anda diperbolehkan untuk berdiskusi dengan teman Anda, tetapi dilarang keras menyalin kode maupun tulisan dari teman Anda. Petunjuk_Packages_ yang Anda akan gunakan dalam mengerjakan tugas ini antara lain:- keras- matplotlib- numpy- pandas- pillow- scipy- seabornAnda diperbolehkan (jika dirasa perlu) untuk mengimpor modul tambahan untuk tugas ini. Namun, seharusnya modul yang tersedia sudah cukup untuk memenuhi kebutuhan Anda. Untuk kode yang Anda ambil dari sumber lain, **cantumkan URL menuju referensi tersebut jika diambil dari internet**!Perhatikan poin untuk tiap soal! **Semakin kecil poinnya, berarti kode yang diperlukan untuk menjawab soal tersebut seharusnya semakin sedikit!** **Nilai akhir: XX/40** Deskripsi DatasetPada tugas kali ini, Anda akan mencoba menggunakan metode *machine learning* untuk melakukan dua jenis prediksi: **regresi** dan **klasifikasi**.**Untuk kasus regresi**, Anda diminta untuk memprediksi jumlah penjualan berdasarkan uang yang dihabiskan pada media iklan yang digunakan. Terdapat tiga media iklan, yaitu TV, Radio dan Newspaper. Dengan detail atribut sebagai berikut:- TV: biaya yang dihabiskan untuk iklan tayangan TV untuk setiap satu produk dalam sebuah pasar (dalam ribuan dollar)- Radio: biaya yang dihabiskan untuk iklan di radio (dalam ribuan dollar)- Newspaper: biaya yang dihabiskan untuk iklan di koran (dalam ribuan dollar)- Sales: penjualan dari setiap satuan produk pada suatu pasar (dalam ribuan widget)**Untuk kasus klasifikasi**, Anda akan menggunakan dataset Food-101 yang memiliki 101 kategori makanan dengan total 101.000 gambar makanan. Dataset untuk tugas ini diambil dari Food-101 (https://www.vision.ee.ethz.ch/datasets_extra/food-101/). Untuk versi yang lebih sederhana, Anda hanya akan membandingkan apakah gambar yang diberikan berupa *sushi* atau *pizza*. Anda akan melakukan klasifikasi menggunakan algoritma regresi logistik dan neural networks dalam tugas ini. Mengimpor Modul dan Dataset ###Code from __future__ import print_function, division # Gunakan print(...) dan bukan print ... import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import random import requests from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix, mean_squared_error, r2_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder %matplotlib inline RANDOM_STATE = 1337 np.random.seed(RANDOM_STATE) ###Output _____no_output_____ ###Markdown 1. Eksplorasi Awal Data - Advertising (6 poin) ###Code df = pd.read_csv('https://github.com/aliakbars/uai-ai/raw/master/datasets/advertising.csv', index_col=0) ###Output _____no_output_____ ###Markdown Soal 1.1.a (1 poin)Laporkan deskripsi dari Advertising dataset dengan menggunakan metode dari Pandas! Soal 1.1.b (2 poin)Berapa nilai `sales` paling rendah dan nilai `sales` paling tinggi dari data yang Anda miliki? Berapa ribu dollar uang yang dihabiskan untuk membayar biaya iklan di `TV`, `radio`, dan `newspaper` untuk produk tersebut? Soal 1.2 (3 poin)Gambarkan scatter plot dari `sales` terhadap media iklan `TV`, `radio`, dan `newspaper`. 2. Prediksi Penjualan Berdasarkan Biaya Media Iklan dengan Regresi Linear (19 poin) Soal 2.1 (4 poin)Kita akan membuat simple linear regression dengan satu fitur. Dalam kasus ini, mari mencoba melihat hubungan antara `sales` dengan biaya untuk media iklan di `TV`.Ambil fitur dari kolom `TV` dan response dari kolom `sales`, kemudian buat sebuah model linear regression menggunakan pustaka scikit-learn dan latih model tersebut dengan data yang Anda miliki! Laporkan nilai bias dan koefisiennya. Lalu, jelaskan bagaimana intepretasi Anda terhadap koefisien dari model yang Anda miliki.*Petunjuk: Lihat cara penggunaan pustakanya di [sini](http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.htmlsphx-glr-auto-examples-linear-model-plot-ols-py).* *Jawaban Anda di sini* Soal 2.2.a (3 poin)Mari kita lihat seberapa baik garis regresi yang dibuat dari model yang Anda miliki. Buatlah prediksi dari biaya `TV` yang paling minimum dan biaya `TV` yang paling maksimum! Gambarkan scatter plot dan garis regresi model Anda atas prediksi tersebut. Bagaimana garis tersebut mencocokkan data Anda? Soal 2.2.b (3 poin)Coba lakukan kembali regresi pada data tersebut, tetapi kali ini gunakan fungsi basis polinomial orde 3. Gambarkan kembali scatter plot dan fungsi regresinya. Soal 2.2.c (3 poin)Salah satu cara untuk memastikan bahwa model yang Anda hasilkan sudah cukup baik pada model regresi adalah dengan menghitung nilai *mean squared error* (MSE). Coba hitung nilai MSE untuk regresi dengan dan tanpa fungsi basis polinomial seperti yang Anda kerjakan pada bagian a dan b. Apa yang dapat Anda amati? Apakah nilainya sesuai dengan ekspektasi Anda? *Jawaban Anda di sini* Soal 2.3.a (4 poin)Sekarang kita akan melakukan Multiple Linear Regression. Buatlah sebuah model dengan menggunakan Linear Regression dari scikit-learn untuk fitur `TV`, `radio`, dan `newspaper`. Variabel dependen yang digunakan adalah `sales`. Keluarkan pula nilai bias dan nilai koefisien ketiga fitur tersebut. Sebelum itu, bagi dataset menjadi data latih dan data uji dengan proporsi data uji sebanyak 20%. Soal 2.3.b (2 poin)Lakukan evaluasi model *multiple linear regression* yang Anda miliki dari data uji dengan menggunakan *mean squared error*. 3. Eksplorasi Awal Data Food-101 (3 poin) Pertama, kita akan memuat data menggunakan kode di bawah ini. `X` merupakan gambar yang telah diterjemahkan dalam bentuk *tensor* atau array multidimensi. Dimensi pertama menunjukkan jumlah datanya, dua dimensi berikutnya menunjukkan panjang dan lebar dari gambarnya, dan dimensi keempat merupakan *channels* (RGB). Di sisi lain, `y` adalah kelas dari masing-masing gambar yang diberikan dalam `X` sehingga `X.shape[0] == y.shape[0]`. ###Code def load_file(url): filename = url.split('/')[-1] with open(filename, 'wb') as f: resp = requests.get(url) f.write(resp.content) return np.load(filename) X = load_file('https://github.com/aliakbars/uai-ai/raw/master/datasets/food.npy') y = load_file('https://github.com/aliakbars/uai-ai/raw/master/datasets/food_labels.npy') X.shape ###Output _____no_output_____
standardiser2/docs/Charge-separated_systems.ipynb
###Markdown Rules for conjugated charge-seperated systems IntroductionThese rules address cases in which positive and negative formal charges are in conjugation, and the molecule can be neutralised _via_ successive rearrangement of adjacent double and single bonds.Some issues relating to these rules are discussed below. Possible redundancy of rulesRecall that bonds to Group I & II metals are broken and a round of protonation/deprotonation-based neutralisation are done _before_ these rules are applied, and that a further round of neutralisation is carried out afterwards. The neutralisation step before rule application is worthy of note, as the it can mean some rules for charge-seperated systems are apparently redundant in some situations (unsubsituted analogues, in particular). Below is an example of where the cation in the charge-seperated species bears a proton and the `neutralise` module thus produces an equivalent overall effect as the `rules` module... 1) Application of _rules_ module... ###Code smiles = 'CC[N-]C(C)=[NH+]C' HTML(show_change(smiles)) ###Output [2016/Mar/24 16:22:42 DEBUG ] rule 15 'Fix 1,3 charge-seperated systems (non-aromatic)' applied ###Markdown 2) Application of _neutralise_ module (_i.e._ simple addition/removal of protons)... ###Code neutralise.apply(Chem.MolFromSmiles(smiles)) ###Output [2016/Mar/24 16:22:42 DEBUG ] 1 positive/H, 0 positive/quat and 1 negative (of which 0 are acid) charges identified [2016/Mar/24 16:22:42 DEBUG ] Overall H balance: 0; formal charge: 0 ###Markdown For full-substituted species, this is not an issue, as the `neutralise` module will have no effect... 1) Application of _rules_ module... ###Code HTML(show_change("C[N-]C(C)=[N+](C)C")) ###Output [2016/Mar/24 16:22:42 DEBUG ] rule 15 'Fix 1,3 charge-seperated systems (non-aromatic)' applied ###Markdown 2) Application of _neutralise_ module (has no effect here)... ###Code neutralise.apply(Chem.MolFromSmiles("C[N-]C(C)=[N+](C)C")) ###Output [2016/Mar/24 16:22:42 DEBUG ] 0 positive/H, 1 positive/quat and 1 negative (of which 0 are acid) charges identified [2016/Mar/24 16:22:42 DEBUG ] Overall H balance: 0; formal charge: 0 ###Markdown The `neutralise` module will not attempt to charge balance these systems as they appear to be potential zwitterions; see the [documentation](3_neutralise.ipynb) for that module for futher details. Interaction of `neutralise` module and 'charge-seperated' rulesThe pre-application of the `neutralise` module could conceivably lead to problems in aromatic systems where potentially undesirable imine species might be produced. However, it doesn't seem to be a problem in practice as the undesirable species are fixed by the subsequent application of other rules.This is illustrated below... ###Code mol = Chem.MolFromSmiles("[n-]1c(=[NH+]C)cccc1") mol ###Output _____no_output_____ ###Markdown The initial application of the `neutralise` module removes the charges _via_ protonation/deprotonation to give a potentially undesirable hydropyridine-imine... ###Code neutralise.apply(mol) ###Output [2016/Mar/24 16:22:42 DEBUG ] 1 positive/H, 0 positive/quat and 1 negative (of which 0 are acid) charges identified [2016/Mar/24 16:22:42 DEBUG ] Overall H balance: 0; formal charge: 0 ###Markdown However, this is then fixed by application of the appropriate 'hydropyridine-imine -> aminopyridine' transform during the rule-application step, so the desired parent is actually obtained... ###Code standardise.apply(Chem.MolFromSmiles("[n-]1c(=[NH+]C)cccc1")) ###Output [2016/Mar/24 16:22:42 DEBUG ] Starting fragment 1 'C[NH+]=c1cccc[n-]1'... [2016/Mar/24 16:22:42 DEBUG ] 1) Check for non-organic elements... [2016/Mar/24 16:22:42 DEBUG ] 2) Attempting to neutralise (first pass)... [2016/Mar/24 16:22:42 DEBUG ] 1 positive/H, 0 positive/quat and 1 negative (of which 0 are acid) charges identified [2016/Mar/24 16:22:42 DEBUG ] Overall H balance: 0; formal charge: 0 [2016/Mar/24 16:22:42 DEBUG ] 3) Applying rules... [2016/Mar/24 16:22:42 DEBUG ] apply> mol = 'CN=c1cccc[nH]1' [2016/Mar/24 16:22:42 DEBUG ] apply> starting pass 1... [2016/Mar/24 16:22:42 DEBUG ] rule 7 'hydropyridin-2-imine -> 2-amino-pyridine (N-subst.)' applied on pass 1 [2016/Mar/24 16:22:42 DEBUG ] ...total of 1 hits in pass: will continue... [2016/Mar/24 16:22:42 DEBUG ] apply> starting pass 2... [2016/Mar/24 16:22:42 DEBUG ] ...total of 0 hits in pass: finished. [2016/Mar/24 16:22:42 DEBUG ] 4) Attempting to neutralise (second pass)... [2016/Mar/24 16:22:42 DEBUG ] 0 positive/H, 0 positive/quat and 0 negative (of which 0 are acid) charges identified [2016/Mar/24 16:22:42 DEBUG ] Overall H balance: 0; formal charge: 0 [2016/Mar/24 16:22:42 DEBUG ] 5) Checking if frag is a salt/solvate... [2016/Mar/24 16:22:42 DEBUG ] ...fragment kept. ###Markdown Note that this is as would be obtained by application of the rules in the absence of the neutralisation step... ###Code HTML(show_change("[n-]1c(=[N+](C)C)cccc1")) ###Output [2016/Mar/24 16:22:42 DEBUG ] rule 16 'Fix 1,3 charge-seperated systems (aromatic 1)' applied ###Markdown Aromatics and iminesIn some cases it is not clear whether, when the starting structure contains an amide anion, that the uncharged imine produced is more or less desirable that the original zwitterion or than the cationic methyl-pyridine that would be produced by simple protonation of the amide anion. Examples are shown below; note that the `neutralise` module does not touch these molecules as it perceives them to be zwitterionic.. ###Code HTML(show_change("C[n+]1c([N-](C))cccc1")) HTML(show_change("C[n+]1ccc([N-]C)cc1")) ###Output [2016/Mar/24 16:22:42 DEBUG ] rule 20 'Fix 1,5 charge-seperated systems (aromatic 2)' applied
pd/pd9 - Merging on Index.ipynb
###Markdown hierarchy index ###Code df_left_hr = DataFrame({'key1':['SF','SF','SF','LA','LA'], 'key2':[10,20,30,20,30], 'data_set':np.arange(5.)}) df_left_hr.dropna df_right_hr = DataFrame(np.arange(10).reshape(5,2), index=[['LA','LA','SF','SF','SF'], [20,10,10,10,20]], columns=['col_1','col_2']) df_right_hr ###Output _____no_output_____ ###Markdown **For hierarchial indexes, the length of `left_on` must be equal to the number of levels in the index of "right" (`right_index`)** ###Code pd.merge(df_left_hr,df_right_hr, left_on=['key1','key2'],right_index=True) df_left.join(df_right) ###Output _____no_output_____
Udemy Courses Data Analysis Notebook.ipynb
###Markdown Udemy Courses Data Analysis **The Dataset contains all course data for all the subjects. We will analysis this data using pandas library.** Importing Libraries ###Code import pandas as pd ###Output _____no_output_____ ###Markdown Importing Dataset ###Code df = pd.read_csv("./Dataset/Udemy Courses.csv") df.head() df.shape ###Output _____no_output_____ ###Markdown 1. What are all different subjects for which Udemy is offering courses? ###Code df['subject'].unique() ###Output _____no_output_____ ###Markdown 2. Which subject has the maximum number of courses? ###Code df['subject'].value_counts() ###Output _____no_output_____ ###Markdown 3. Show all the courses which are Free of Cost. ###Code free_courses = df[df['price'] == "Free"] free_courses.head(n = 3) # df[df.price == "Free"] free_courses.shape ###Output _____no_output_____ ###Markdown 4. Show all the courses which are Paid. ###Code paid_courses = df[df['price'] != "Free"] paid_courses.head(n=3) paid_courses.shape ###Output _____no_output_____ ###Markdown 5. Which are Top Selling Courses? ###Code top_selling_courses = df.sort_values(by="num_subscribers", axis=0, ascending=False) top_selling_courses.head() ###Output _____no_output_____ ###Markdown 6. Which are the Least selling Courses? ###Code least_selling_courses = df.sort_values(by="num_subscribers") least_selling_courses.head() ###Output _____no_output_____ ###Markdown 7. Show all the courses of Graphic Design where the price is below 100 ###Code df = df.replace(to_replace =["Free"], value ="0") df = df.astype({"price" : "int32"}) df[ (df.subject == "Graphic Design") & (df.price < 100)].head() ###Output _____no_output_____ ###Markdown 8. List out all the courses that are related with "Python" ###Code df[df.course_title.str.contains("Python")].head() ###Output _____no_output_____ ###Markdown 9. What are courses that published in year 2015? ###Code course_published_2015 = df[df.published_timestamp.str.contains("2015")] course_published_2015.head() # Second Method df['published_timestamp'] = pd.to_datetime(df.published_timestamp) df['year'] = df['published_timestamp'].dt.year df[df.year ==2015].head(3) ###Output _____no_output_____ ###Markdown 10. What are the Max. Number of Subscribers for Each Level of courses? ###Code df.groupby("level")['num_subscribers'].max() # Maximum value of each column in present here df.groupby("level").max() ###Output _____no_output_____
HW2/python/.ipynb_checkpoints/HW2_scratchwork-checkpoint.ipynb
###Markdown Dev for hw2 - dsc291 - team 4 How does the performance of random-poke.py related to the size of the caches in the ec2 instance?*^that's Yoav's proposed question 1 for HW2***Foreword on question choice**I am open to any questions any of you are interested in following up. None of you have expressed an interest in any particular question, so if this question is okay, let's do it so we have something. We can always consider doing more later.For now, let's focus on hashing out a clear course of action for HW2 in the following text (This all will be sent to an .md on our github repository (https://github.com/timtyree/dsc291team4/).**Questions I'd like us all to think about:*** What are all of the measurements we should be recording?* How do we control cache-size when we're generating cache-misses with some probability?* Is there a measure of ec2 cache redundancy that I should know about? **Goal 1**: measure cache-miss rates that result from reducing random-poke.py at some cache size**(step 1) list all the measurements we should be recording for each cache-miss datum**- latency of the cache miss (used to identify cache miss)- time/date/day-of-week that a cache miss happens- a measure of cache/network size- a measure of cache redundancy (what could this be?)**(step 2) develop ^those measurements and test that they work how we expect*** TODO: set up a local for development. no need to spend computational resource on development* TODO: make the simplest possible method to produce a cache miss with a nontrivial frequency**(step 3) record the relevant data in an s3 bucket in an easy to reproduce way*** TODO: reduce using a count function to yield the number of machines in the cluster* TODO: start regularly recording the number of machines in the cache along with the current time of day.* QUESTION: Is there a redundancy measure for caches on an ec2 instance that I should know about? **Goal 2**: Analyze/Visualize data and see what emerges* I've got experience doing this. To what degree have each of you done this before? make function that calls a function regularly ###Code import datetime, time # from datetime import datetime, time from time import sleep def do_at_time(action, sec=None,min=None,hour=None, day=None, month=None, year=None): today = datetime.datetime.now() sleep = (datetime.datetime(today.year, today.month, today.day, 15, 20, 0) - today).seconds # print('Waiting for ' + str(datetime.timedelta(seconds=sleep))) time.sleep(sleep) return action def do_after_waiting(action, sec=0, min=0, hour=0): '''do action after waiting sec seconds, min minutes, and hour hours.''' today = datetime.datetime.now() sleep = (datetime.datetime(today.year, today.month, today.day, 15, 20, 0) - today).seconds # print('Waiting for ' + str(datetime.timedelta(seconds=sleep))) time.sleep(sleep) return action %load_ext autoreload %autoreload 2 # today-today # datetime.timedelta # print(today) td = today-today # time.sleep td.total_seconds() str(int(time.time())) %run run_trial ###Output ERROR:root:File `'run_trial.py'` not found.
3_generate_population_cohort.ipynb
###Markdown Table of Contents1&nbsp;&nbsp;Loading data1.1&nbsp;&nbsp;Sanity check1.2&nbsp;&nbsp;Loading all reprots1.3&nbsp;&nbsp;Narrow down based on country and qualification2&nbsp;&nbsp;Generate data for all patients2.1&nbsp;&nbsp;Generate data2.1.1&nbsp;&nbsp;Sanity check2.2&nbsp;&nbsp;Population distribution3&nbsp;&nbsp;Conditioned on Gender3.1&nbsp;&nbsp;Male3.2&nbsp;&nbsp;Female4&nbsp;&nbsp;Conditioned on Age4.1&nbsp;&nbsp;Bin age into groups4.2&nbsp;&nbsp;Three age groups Loading dataWe investigate period from 03-11 to 09-30 from 2013 to 2020. If anyone want to analyze different time period, just replace the start or end time. For example, replace '09-30' by '12-31' to study the period from March 11 to December 31. ###Code import itertools from tqdm import tqdm import pandas as pd import pickle import numpy as np from collections import Counter import scipy.stats as stats from statsmodels.stats.multitest import multipletests # %matplotlib notebook pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) import warnings warnings.filterwarnings('ignore') # load the dictionaries for drugs, AE se_dic = pickle.load(open('../Data/curated/AE_dic.pk', 'rb')) drug_dic = pickle.load(open('../Data/curated/drug_mapping.pk', 'rb')) # In this MeDRA_dic, key is string of PT_name, value is a list: # [PT, PT_name, HLT,HLT_name,HLGT,HLGT_name,SOC,SOC_name,SOC_abbr] meddra_pd_all = pickle.load(open('../Data/curated/AE_mapping.pk', 'rb')) def chi_sq(A, B,C,D): A, B, C,D = A.astype(float), B.astype(float), C.astype(float), D.astype(float) numerator =(A*D-B*C)**2 denominator = (A+B)*(C+D)*(A+C)*(B+D) numerator = numerator/denominator numerator_ = numerator*(A+B+C+D) return numerator_ def lower_CI(A, B,C,D, ROR): A, B, C,D, ROR = A.astype(float), B.astype(float), C.astype(float), D.astype(float), ROR.astype(float) s = np.sqrt(1/A+ 1/B + 1/C +1/D) CI_low = np.e**(np.log(ROR)-1.96*s) # CI_high = e**(np.log(ROR)+1.96*s) return CI_low ###Output _____no_output_____ ###Markdown Sanity check ###Code meddra_pd_all.head(1) meddra_pd_all[meddra_pd_all.PT=='10018358'] # drug dictionary to df drug_dic_pd = pd.DataFrame(drug_dic) drug_dic_df = drug_dic_pd.T drug_dic_df.columns=['drugbank_ID', 'code'] drug_dic_df.head() drug_dic_df[drug_dic_df.code == 931] # drug_dic['remdesivir'] # Make a drug_code_dic to find the drug name by code drug_code_dic = {} for key, value in drug_dic.items(): drug_code_dic[value[-1]]=[key, value[0]] pickle.dump(drug_code_dic, open('../Data/parsed/drug_code_dic.pk', 'wb')) list(drug_code_dic.items())[:10] ###Output _____no_output_____ ###Markdown Loading all reprots ###Code all_pd = pickle.load(open('../Data/curated/patient_safety.pk', 'rb')) all_pd.head(3) ###Output _____no_output_____ ###Markdown Narrow down based on country and qualification ###Code all_pd_US = all_pd[all_pd.country=='US'] print('Focus on US, reports #', all_pd_US.shape) id_qua = [i in ['1', '2', '3'] for i in all_pd_US.qualify ] all_pd_US_pro = all_pd_US[id_qua] # professional: 1,2,3 print('Focus on professional qualification, reports #', all_pd_US_pro.shape) pickle.dump(all_pd_US_pro, open('../Data/pandemic/all_pd_US_pro.pk', 'wb')) ###Output Focus on US, reports # (6351817, 23) Focus on professional qualification, reports # (2551071, 23) ###Markdown Generate data for all patientsThe overall population (all patients) is denoted by 'uncondition'. Variables with 'uncondition' in name refers to the population of all patients. Generate data ###Code all_pd_US_pro = pickle.load(open('../Data/pandemic/all_pd_US_pro.pk', 'rb')) # SE_list = list(SE_dic_df.code) DF = all_pd_US_pro SE_list = list(sorted(set(list(itertools.chain(*DF.SE))))) print('#-SE in US pro',len(SE_list)) ind = [i in SE_list for i in meddra_pd_all.PT] whatever_ = meddra_pd_all[ind] print(whatever_.shape) whatever_.head(3) # reports in 2020 yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] n_re = [] for yr in yr_list: st = str(yr)+'-03-10' end = str(yr)+'-09-31' ind = [st<i<end for i in all_pd_US_pro['receipt_date']] # all ['date'] --> ['receipt_date'] locals()['all_pd_US_pro_'+str(yr)]= all_pd_US_pro[ind] n_reports = len(locals()['all_pd_US_pro_'+str(yr)]) n_re.append(n_reports) print('rows in {}:{}'.format(yr,n_reports)) yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] """initialize the Data frame """ se_matrix = pd.DataFrame({'SE': list(whatever_.PT), 'name':list(whatever_['PT_name']) }) #'medra_ID': list(SE_dic_df['medra_ID']) for yr in yr_list: n_report = len(locals()['all_pd_US_pro_'+str(yr)]) print('{} year has {} reports'.format(yr, n_report)) A =[] for se in tqdm(SE_list): name = locals()['all_pd_US_pro_'+str(yr)] indx = [se in j for j in name.SE] n_A = sum(indx) A.append(n_A) B = [n_report - i for i in A] se_matrix[str(yr)+'_A'] = A se_matrix[str(yr)+'_B'] = B pickle.dump(se_matrix, open('../Data/pandemic/SE_uncondition_raw.pk', 'wb')) para = se_matrix yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019] for yr in yr_list: # calculate ROR para[str(yr)+'_ROR'] = (para['2020_A']*para[str(yr)+'_B'])/(para['2020_B']*para[str(yr)+'_A']) for yr in yr_list: # calculate Delta: average difference para[str(yr)+'_Delta'] = (para['2020_A'] - para[str(yr)+'_A'])/para[str(yr)+'_A'] pd.set_option('display.max_columns', None) """Note: 0/0 = NaN, 1/0 = inf""" para.head() pickle.dump(para, open('../Data/pandemic/SE_uncondition.pk', 'wb')) # update the dataframe with ROR and Delta ###Output _____no_output_____ ###Markdown Sanity check ###Code uncondition_2019_history = pickle.load(open('../Data/pandemic/SE_uncondition.pk', 'rb')) uncondition_2019_history[uncondition_2019_history.name=='cardiac arrest'] x = uncondition_2019_history[uncondition_2019_history['2019_Delta']>0] print(x.shape) y = x[x['2020_A']>1000] print(y.shape) y[['SE', 'name','2018_A', '2019_A', '2020_A', '2019_Delta']] uncondition_2019_history[uncondition_2019_history.name=='cough'] ###Output _____no_output_____ ###Markdown Population distribution ###Code all_pd_US_pro = pickle.load(open('../Data/pandemic/all_pd_US_pro.pk', 'rb')) # update the dataframe with ROR and Delta len(all_pd_US_pro) st = '-03-10' end = '-09-31' ind = [st<i[4:]<end for i in all_pd_US_pro['receipt_date']] all_pd_US_pro_period= all_pd_US_pro[ind] n_all = len(all_pd_US_pro_period) print('the #-reports during March 11-Sept 30, accmulated from 2013-2020', n_all) n_male = len(all_pd_US_pro_period[all_pd_US_pro_period.gender=='1']) n_female = len(all_pd_US_pro_period[all_pd_US_pro_period.gender=='2']) in_young = [str(0)<str(i)<str(20) for i in all_pd_US_pro_period.age] in_adult = [str(19)<str(i)<str(65) for i in all_pd_US_pro_period.age] in_elderly = [str(64)<str(i) for i in all_pd_US_pro_period.age] n_young = len(all_pd_US_pro_period[in_young]) n_adult = len(all_pd_US_pro_period[in_adult]) n_elderly = len(all_pd_US_pro_period[in_elderly]) # unknown sex: n_unknownsex = n_all-n_male-n_female n_unknownage = n_all - n_young -n_adult-n_elderly print('#-male reports',n_male, n_male/n_all) print('#-female reports',n_female, n_female/n_all) print('unknown sex: ', n_unknownsex, n_unknownsex/n_all) # unknown age print('#-young reports', n_young, n_young/n_all) print('#-adult reports', n_adult, n_adult/n_all) print('#-elderly reports',n_elderly, n_elderly/n_all) print('unknown age', n_unknownage, n_unknownage/n_all) ## mean and std average young_age = np.array(list(all_pd_US_pro_period[in_young].age)) print(young_age.mean(), young_age.std()) adult_age = np.array(list(all_pd_US_pro_period[in_adult].age)) print(adult_age.mean(), adult_age.std()) elderly_age = np.array(list(all_pd_US_pro_period[in_elderly].age)) print(elderly_age.mean(), elderly_age.std()) # "1= Physician # 2= Pharmacist # 3= Other Health Professional # 4= Lawyer # 5= Consumer" ## Qualification/reporter distribution all_pd = pickle.load(open('../Data/curated/patient_safety.pk', 'rb')) print('#-of all reports',all_pd.shape) all_pd_US = all_pd[all_pd.country=='US'] print('Focus on US, reports #', all_pd_US.shape) st = '-03-10' end = '-09-31' ind = [st<i[4:]<end for i in all_pd_US['receipt_date']] all_pd_US_period= all_pd_US[ind] all_pd_US_period['qualify'].value_counts() ###Output #-of all reports (9325731, 23) Focus on US, reports # (6351817, 23) ###Markdown Conditioned on Gender Male ###Code all_pd_US_pro = pickle.load(open('../Data/pandemic/all_pd_US_pro.pk', 'rb')) # update the dataframe with ROR and Delta print(len(all_pd_US_pro)) all_pd_US_pro_male = all_pd_US_pro[all_pd_US_pro.gender=='1'] DF = all_pd_US_pro_male # reports in 2020 """initialize the Data frame """ # SE_list = list(SE_dic_df.code) # male_matrix = pd.DataFrame({'SE': SE_list, 'name':list(SE_dic_df.index), 'medra_ID': list(SE_dic_df['medra_ID'])}) SE_list = list(sorted(set(list(itertools.chain(*DF.SE))))) ind = [i in SE_list for i in meddra_pd_all.PT] whatever_ = meddra_pd_all[ind] male_matrix = pd.DataFrame({'SE': list(whatever_.PT), 'name':list(whatever_['PT_name']) }) yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] for yr in yr_list: st = str(yr)+'-03-10' end = str(yr)+'-09-31' ind = [st<i<end for i in DF['receipt_date']] locals()['all_pd_US_pro_'+str(yr)]= DF[ind] print('rows in {}:{}'.format(yr,len(locals()['all_pd_US_pro_'+str(yr)]))) n_report = len(locals()['all_pd_US_pro_'+str(yr)]) print('{} year has {} reports'.format(yr, n_report)) A =[] for se in tqdm(SE_list): name = locals()['all_pd_US_pro_'+str(yr)] indx = [se in j for j in name.SE] n_A = sum(indx) A.append(n_A) B = [n_report - i for i in A] male_matrix[str(yr)+'_A'] = A male_matrix[str(yr)+'_B'] = B male_matrix.head(3) pickle.dump(male_matrix, open('../Data/pandemic/SE_male_raw.pk', 'wb')) para_male = male_matrix yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019] for yr in yr_list: # calculate ROR para_male[str(yr)+'_ROR'] = (para_male['2020_A']*para_male[str(yr)+'_B'])/(para_male['2020_B']*para_male[str(yr)+'_A']) for yr in yr_list: # calculate Delta: average difference para_male[str(yr)+'_Delta'] = (para_male['2020_A'] - para_male[str(yr)+'_A'])/para_male[str(yr)+'_A'] pd.set_option('display.max_columns', None) """Note: 0/0 = NaN, 1/0 = inf""" para_male.head() pickle.dump(para_male, open('../Data/pandemic/SE_male.pk', 'wb')) # update the dataframe with ROR and Delta ###Output _____no_output_____ ###Markdown Female ###Code all_pd_US_pro_female = all_pd_US_pro[all_pd_US_pro.gender=='2'] DF = all_pd_US_pro_female # reports in 2020 """initialize the Data frame """ # SE_list = list(SE_dic_df.code) # female_matrix = pd.DataFrame({'SE': SE_list, 'name':list(SE_dic_df.index), 'medra_ID': list(SE_dic_df['medra_ID'])}) SE_list = list(sorted(set(list(itertools.chain(*DF.SE))))) ind = [i in SE_list for i in meddra_pd_all.PT] whatever_ = meddra_pd_all[ind] female_matrix = pd.DataFrame({'SE': list(whatever_.PT), 'name':list(whatever_['PT_name']) }) yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] for yr in yr_list: st = str(yr)+'-03-10' end = str(yr)+'-09-31' ind = [st<i<end for i in DF['receipt_date']] locals()['all_pd_US_pro_'+str(yr)]= DF[ind] print('rows in {}:{}'.format(yr,len(locals()['all_pd_US_pro_'+str(yr)]))) n_report = len(locals()['all_pd_US_pro_'+str(yr)]) print('{} year has {} reports'.format(yr, n_report)) A =[] for se in tqdm(SE_list): name = locals()['all_pd_US_pro_'+str(yr)] indx = [se in j for j in name.SE] n_A = sum(indx) A.append(n_A) B = [n_report - i for i in A] female_matrix[str(yr)+'_A'] = A female_matrix[str(yr)+'_B'] = B pickle.dump(female_matrix, open('../Data/pandemic/SE_female_raw.pk', 'wb')) para_female = female_matrix yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019] for yr in yr_list: # calculate ROR para_female[str(yr)+'_ROR'] = (para_female['2020_A']*para_female[str(yr)+'_B'])/(para_female['2020_B']*para_female[str(yr)+'_A']) for yr in yr_list: # calculate Delta: average difference para_female[str(yr)+'_Delta'] = (para_female['2020_A'] - para_female[str(yr)+'_A'])/para_female[str(yr)+'_A'] pd.set_option('display.max_columns', None) """Note: 0/0 = NaN, 1/0 = inf""" para_female.head() pickle.dump(para_female, open('../Data/pandemic/SE_female.pk', 'wb')) # update the dataframe with ROR and Delta ###Output _____no_output_____ ###Markdown Conditioned on AgeBased on [WHO](https://www.who.int/hiv/pub/guidelines/arv2013/intro/keyterms/en/) and the [Men Ageing And Health](https://apps.who.int/iris/bitstream/handle/10665/66941/WHO_NMH_NPH_01.2.pdf;jsessionid=A48157B9B4DFAA3A9874176D8A7C2894?sequence=1), the age group:- Young: 1-19 - Adult: 20-65- Elderly: >65 Bin age into groups ###Code age_US_df = pickle.load(open('../Data/pandemic/all_pd_US_pro.pk', 'rb')) # update the dataframe with ROR and Delta # Bin age into groups age_US_df['age'] = pd.to_numeric(age_US_df['age'], errors='coerce') bins = [1, 20, 65, max(age_US_df.age)+1] age_labels = ['young', 'adult','elderly'] age_US_df['age_group'] = pd.cut(age_US_df.age, bins, right = False, labels= age_labels) ###Output _____no_output_____ ###Markdown Three age groups ###Code for age in age_labels: age_US_df_group = age_US_df[age_US_df.age_group==age] DF = age_US_df_group # reports in 2020 """initialize the Data frame """ # SE_list = list(SE_dic_df.code) # age_matrix = pd.DataFrame({'SE': SE_list, 'name':list(SE_dic_df.index), 'medra_ID': list(SE_dic_df['medra_ID'])}) """Remember sort the SE set!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11""" SE_list = list(sorted(set(list(itertools.chain(*DF.SE))))) ind = [i in SE_list for i in meddra_pd_all.PT] whatever_ = meddra_pd_all[ind] age_matrix = pd.DataFrame({'SE': list(whatever_.PT), 'name':list(whatever_['PT_name']) }) yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] for yr in yr_list: st = str(yr)+'-03-10' end = str(yr)+'-09-31' ind = [st<i<end for i in DF['receipt_date']] locals()['all_pd_US_pro_'+str(yr)]= DF[ind] print('rows in {}:{}'.format(yr,len(locals()['all_pd_US_pro_'+str(yr)]))) n_report = len(locals()['all_pd_US_pro_'+str(yr)]) print('{} year has {} reports'.format(yr, n_report)) A =[] for se in tqdm(SE_list): name = locals()['all_pd_US_pro_'+str(yr)] indx = [se in j for j in name.SE] n_A = sum(indx) A.append(n_A) B = [n_report - i for i in A] age_matrix[str(yr)+'_A'] = A age_matrix[str(yr)+'_B'] = B pickle.dump(age_matrix, open('../Data/pandemic/SE_'+age+'_raw.pk', 'wb')) para_age = age_matrix yr_list = [2013, 2014, 2015, 2016, 2017, 2018, 2019] for yr in yr_list: # calculate ROR para_age[str(yr)+'_ROR'] = (para_age['2020_A']*para_age[str(yr)+'_B'])/(para_age['2020_B']*para_age[str(yr)+'_A']) for yr in yr_list: # calculate Delta: average difference para_age[str(yr)+'_Delta'] = (para_age['2020_A'] - para_age[str(yr)+'_A'])/para_age[str(yr)+'_A'] """Note: 0/0 = NaN, 1/0 = inf""" pickle.dump(para_age, open('../Data/pandemic/SE_'+age+'.pk', 'wb')) # update the dataframe with ROR and Delta print(age,'related data saved') locals()['all_pd_US_pro_'+str(yr)].head(10) ###Output _____no_output_____
nb/075_submission.ipynb
###Markdown Overview- nb067ベース(cv:0.94102, sub:0.945)- wavenet(not_roll)- nb070(mlp(deep))のprobaを使う- ROLL_FEATS = False- MOD_BATCH = True Const ###Code NB = '075' isSmallSet = False if isSmallSet: LENGTH = 7000 else: LENGTH = 500_000 ROLL_FEATS = False MOD_BATCH7 = True PATH_PROBAS = './../data/output_ignore/probas_nb070_mlp_deep_cv_0.9383.npz' PATH_TRAIN = './../data/input/train_clean.csv' PATH_TEST = './../data/input/test_clean.csv' PATH_SMPLE_SUB = './../data/input/sample_submission.csv' DIR_OUTPUT = './../data/output/' DIR_OUTPUT_IGNORE = './../data/output_ignore/' cp = ['#f8b195', '#f67280', '#c06c84', '#6c5b7b', '#355c7d'] sr = 10*10**3 # 10 kHz ###Output _____no_output_____ ###Markdown Import everything I need :) ###Code import warnings warnings.filterwarnings('ignore') import time import gc import random import os import itertools import multiprocessing import numpy as np from scipy import signal # from pykalman import KalmanFilter import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from fastprogress import progress_bar from lightgbm import LGBMRegressor from sklearn.model_selection import KFold, train_test_split, StratifiedKFold, GroupKFold from sklearn.metrics import f1_score, mean_absolute_error, confusion_matrix from sklearn.ensemble import RandomForestRegressor from sklearn.tree import DecisionTreeRegressor # from sklearn.svm import SVR from sklearn.linear_model import Lasso # from dtreeviz.trees import dtreeviz import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.callbacks import Callback, LearningRateScheduler from tensorflow.keras.losses import categorical_crossentropy from tensorflow.keras.optimizers import Adam from tensorflow.keras import backend as K from tensorflow.keras import losses, models, optimizers # import tensorflow_addons as tfa ###Output _____no_output_____ ###Markdown My function ###Code def f1_macro(true, pred): return f1_score(true, pred, average='macro') def get_df_batch(df, batch): idxs = df['batch'] == batch assert any(idxs), 'そのようなbatchはありません' return df[idxs] def get_signal_mv_mean(df, n=3001): signal_mv = np.zeros(len(df)) for bt in df['batch'].unique(): idxs = df['batch'] == bt _signal_mv = df['signal'][idxs].rolling(n, center=True).mean().interpolate('spline', order=5, limit_direction='both').values signal_mv[idxs] = _signal_mv return signal_mv def get_signal_mv_std(df, n=3001): signal_mv = np.zeros(len(df)) for bt in df['batch'].unique(): idxs = df['batch'] == bt _signal_mv = df['signal'][idxs].rolling(n, center=True).std().interpolate('spline', order=5, limit_direction='both').values signal_mv[idxs] = _signal_mv return signal_mv def get_signal_mv_min(df, n=3001): signal_mv = np.zeros(len(df)) for bt in df['batch'].unique(): idxs = df['batch'] == bt _signal_mv = df['signal'][idxs].rolling(n, center=True).min().interpolate('spline', order=5, limit_direction='both').values signal_mv[idxs] = _signal_mv return signal_mv def get_signal_mv_max(df, n=3001): signal_mv = np.zeros(len(df)) for bt in df['batch'].unique(): idxs = df['batch'] == bt _signal_mv = df['signal'][idxs].rolling(n, center=True).max().interpolate('spline', order=5, limit_direction='both').values signal_mv[idxs] = _signal_mv return signal_mv def group_feat_train(_train): train = _train.copy() # group init train['group'] = int(0) # group 1 idxs = (train['batch'] == 3) | (train['batch'] == 7) train['group'][idxs] = int(1) # group 2 idxs = (train['batch'] == 5) | (train['batch'] == 8) train['group'][idxs] = int(2) # group 3 idxs = (train['batch'] == 2) | (train['batch'] == 6) train['group'][idxs] = int(3) # group 4 idxs = (train['batch'] == 4) | (train['batch'] == 9) train['group'][idxs] = int(4) return train[['group']] def group_feat_test(_test): test = _test.copy() # group init test['group'] = int(0) x_idx = np.arange(len(test)) # group 1 idxs = (100000<=x_idx) & (x_idx<200000) test['group'][idxs] = int(1) idxs = (900000<=x_idx) & (x_idx<=1000000) test['group'][idxs] = int(1) # group 2 idxs = (200000<=x_idx) & (x_idx<300000) test['group'][idxs] = int(2) idxs = (600000<=x_idx) & (x_idx<700000) test['group'][idxs] = int(2) # group 3 idxs = (400000<=x_idx) & (x_idx<500000) test['group'][idxs] = int(3) # group 4 idxs = (500000<=x_idx) & (x_idx<600000) test['group'][idxs] = int(4) idxs = (700000<=x_idx) & (x_idx<800000) test['group'][idxs] = int(4) return test[['group']] class permutation_importance(): def __init__(self, model, metric): self.is_computed = False self.n_feat = 0 self.base_score = 0 self.model = model self.metric = metric self.df_result = [] def compute(self, X_valid, y_valid): self.n_feat = len(X_valid.columns) if self.metric == 'auc': y_valid_score = self.model.predict_proba(X_valid)[:, 1] fpr, tpr, thresholds = roc_curve(y_valid, y_valid_score) self.base_score = auc(fpr, tpr) else: pred = np.round(self.model.predict(X_valid)).astype('int8') self.base_score = self.metric(y_valid, pred) self.df_result = pd.DataFrame({'feat': X_valid.columns, 'score': np.zeros(self.n_feat), 'score_diff': np.zeros(self.n_feat)}) # predict for i, col in enumerate(X_valid.columns): df_perm = X_valid.copy() np.random.seed(1) df_perm[col] = np.random.permutation(df_perm[col]) y_valid_pred = self.model.predict(df_perm) if self.metric == 'auc': y_valid_score = self.model.predict_proba(df_perm)[:, 1] fpr, tpr, thresholds = roc_curve(y_valid, y_valid_score) score = auc(fpr, tpr) else: score = self.metric(y_valid, np.round(y_valid_pred).astype('int8')) self.df_result['score'][self.df_result['feat']==col] = score self.df_result['score_diff'][self.df_result['feat']==col] = self.base_score - score self.is_computed = True def get_negative_feature(self): assert self.is_computed!=False, 'compute メソッドが実行されていません' idx = self.df_result['score_diff'] < 0 return self.df_result.loc[idx, 'feat'].values.tolist() def get_positive_feature(self): assert self.is_computed!=False, 'compute メソッドが実行されていません' idx = self.df_result['score_diff'] > 0 return self.df_result.loc[idx, 'feat'].values.tolist() def show_permutation_importance(self, score_type='loss'): '''score_type = 'loss' or 'accuracy' ''' assert self.is_computed!=False, 'compute メソッドが実行されていません' if score_type=='loss': ascending = True elif score_type=='accuracy': ascending = False else: ascending = '' plt.figure(figsize=(15, int(0.25*self.n_feat))) sns.barplot(x="score_diff", y="feat", data=self.df_result.sort_values(by="score_diff", ascending=ascending)) plt.title('base_score - permutation_score') def plot_corr(df, abs_=False, threshold=0.95): if abs_==True: corr = df.corr().abs()>threshold vmin = 0 else: corr = df.corr() vmin = -1 # Plot fig, ax = plt.subplots(figsize=(12, 10), dpi=100) fig.patch.set_facecolor('white') sns.heatmap(corr, xticklabels=df.corr().columns, yticklabels=df.corr().columns, vmin=vmin, vmax=1, center=0, annot=False) # Decorations ax.set_title('Correlation', fontsize=22) def get_low_corr_column(df, threshold): df_corr = df.corr() df_corr = abs(df_corr) columns = df_corr.columns # 対角線の値を0にする for i in range(0, len(columns)): df_corr.iloc[i, i] = 0 while True: columns = df_corr.columns max_corr = 0.0 query_column = None target_column = None df_max_column_value = df_corr.max() max_corr = df_max_column_value.max() query_column = df_max_column_value.idxmax() target_column = df_corr[query_column].idxmax() if max_corr < threshold: # しきい値を超えるものがなかったため終了 break else: # しきい値を超えるものがあった場合 delete_column = None saved_column = None # その他との相関の絶対値が大きい方を除去 if sum(df_corr[query_column]) <= sum(df_corr[target_column]): delete_column = target_column saved_column = query_column else: delete_column = query_column saved_column = target_column # 除去すべき特徴を相関行列から消す(行、列) df_corr.drop([delete_column], axis=0, inplace=True) df_corr.drop([delete_column], axis=1, inplace=True) return df_corr.columns # 相関が高い特徴量を除いた名前リスト def reduce_mem_usage(df, verbose=True): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: if col!='open_channels': col_type = df[col].dtypes if col_type in numerics: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) end_mem = df.memory_usage().sum() / 1024**2 if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem)) return df def create_signal_mod(train): left = 3641000 right = 3829000 thresh_dict = { 3: [0.1, 2.0], 2: [-1.1, 0.7], 1: [-2.3, -0.6], 0: [-3.8, -2], } train['signal'] = train['signal'].values for ch in train[train['batch']==7]['open_channels'].unique(): idxs_noisy = (train['open_channels']==ch) & (left<train.index) & (train.index<right) idxs_not_noisy = (train['open_channels']==ch) & ~idxs_noisy mean = train[idxs_not_noisy]['signal'].mean() idxs_outlier = idxs_noisy & (thresh_dict[ch][1]<train['signal'].values) train['signal'][idxs_outlier] = mean idxs_outlier = idxs_noisy & (train['signal'].values<thresh_dict[ch][0]) train['signal'][idxs_outlier] = mean return train def create_signal_mod2(train): left = 3641000 right = 3829000 thresh_dict = { 3: [0.1, 2.0], 2: [-1.1, 0.7], 1: [-2.3, -0.6], 0: [-3.8, -2], } train['signal'] = train['signal'].values for ch in train[train['batch']==7]['open_channels'].unique(): idxs_noisy = (train['open_channels']==ch) & (left<train.index) & (train.index<right) idxs_not_noisy = (train['open_channels']==ch) & ~idxs_noisy mean = train[idxs_not_noisy]['signal'].mean() std = train[idxs_not_noisy]['signal'].std() idxs_outlier = idxs_noisy & (thresh_dict[ch][1]<train['signal'].values) noise = np.random.normal(loc=0, scale=std, size=len(train['signal'].values[idxs_outlier])) train['signal'][idxs_outlier] = mean + noise idxs_outlier = idxs_noisy & (train['signal'].values<thresh_dict[ch][0]) noise = np.random.normal(loc=0, scale=std, size=len(train['signal'].values[idxs_outlier])) train['signal'][idxs_outlier] = mean + noise return train def train_lgbm(X, y, X_te, lgbm_params, random_state=5, n_fold=5, verbose=50, early_stopping_rounds=100, show_fig=True): # using features print(f'features({len(X.columns)}): \n{X.columns}') if not verbose==0 else None # folds = KFold(n_splits=n_fold, shuffle=True, random_state=random_state) folds = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=random_state) scores = [] oof = np.zeros(len(X)) oof_round = np.zeros(len(X)) test_pred = np.zeros(len(X_te)) df_pi = pd.DataFrame(columns=['feat', 'score_diff']) for fold_n, (train_idx, valid_idx) in enumerate(folds.split(X, y=y)): if verbose==0: pass else: print('\n------------------') print(f'- Fold {fold_n + 1}/{N_FOLD} started at {time.ctime()}') # prepare dataset X_train, X_valid = X.iloc[train_idx], X.iloc[valid_idx] y_train, y_valid = y[train_idx], y[valid_idx] # train model = LGBMRegressor(**lgbm_params, n_estimators=N_ESTIMATORS) model.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_valid, y_valid)], verbose=verbose, early_stopping_rounds=early_stopping_rounds) # pred y_valid_pred = model.predict(X_valid, model.best_iteration_) y_valid_pred_round = np.round(y_valid_pred).astype('int8') _test_pred = model.predict(X_te, model.best_iteration_) if show_fig==False: pass else: # permutation importance pi = permutation_importance(model, f1_macro) # model と metric を渡す pi.compute(X_valid, y_valid) pi_result = pi.df_result df_pi = pd.concat([df_pi, pi_result[['feat', 'score_diff']]]) # result oof[valid_idx] = y_valid_pred oof_round[valid_idx] = y_valid_pred_round score = f1_score(y_valid, y_valid_pred_round, average='macro') scores.append(score) test_pred += _test_pred if verbose==0: pass else: print(f'---> f1-score(macro) valid: {f1_score(y_valid, y_valid_pred_round, average="macro"):.4f}') print('') print('====== finish ======') print('score list:', scores) print('CV mean score(f1_macro): {0:.4f}, std: {1:.4f}'.format(np.mean(scores), np.std(scores))) print(f'oof score(f1_macro): {f1_score(y, oof_round, average="macro"):.4f}') print('') if show_fig==False: pass else: # visualization plt.figure(figsize=(5, 5)) plt.plot([0, 10], [0, 10], color='gray') plt.scatter(y, oof, alpha=0.05, color=cp[1]) plt.xlabel('true') plt.ylabel('pred') plt.show() # confusion_matrix plot_confusion_matrix(y, oof_round, classes=np.arange(11)) # permutation importance plt.figure(figsize=(15, int(0.25*len(X.columns)))) order = df_pi.groupby(["feat"]).mean()['score_diff'].reset_index().sort_values('score_diff', ascending=False) sns.barplot(x="score_diff", y="feat", data=df_pi, order=order['feat']) plt.title('base_score - permutation_score') plt.show() # submission test_pred = test_pred/N_FOLD test_pred_round = np.round(test_pred).astype('int8') return test_pred_round, test_pred, oof_round, oof def plot_confusion_matrix(truth, pred, classes, normalize=False, title=''): cm = confusion_matrix(truth, pred) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize=(10, 10)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title('Confusion matrix', size=15) plt.colorbar(fraction=0.046, pad=0.04) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.grid(False) plt.tight_layout() def train_test_split_lgbm(X, y, X_te, lgbm_params, random_state=5, test_size=0.3, verbose=50, early_stopping_rounds=100, show_fig=True): # using features print(f'features({len(X.columns)}): \n{X.columns}') if not verbose==0 else None # folds = KFold(n_splits=n_fold, shuffle=True, random_state=random_state) # folds = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=random_state) # prepare dataset X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=test_size, random_state=random_state) # train model = LGBMRegressor(**lgbm_params, n_estimators=N_ESTIMATORS) model.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_valid, y_valid)], verbose=verbose, early_stopping_rounds=early_stopping_rounds) # pred oof = model.predict(X_valid, model.best_iteration_) oof_round = np.round(oof).astype('int8') test_pred = model.predict(X_te, model.best_iteration_) test_pred_round = np.round(test_pred).astype('int8') print('====== finish ======') print(f'oof score(f1_macro): {f1_score(y_valid, oof_round, average="macro"):.4f}') print('') if show_fig==False: pass else: # visualization plt.figure(figsize=(5, 5)) plt.plot([0, 10], [0, 10], color='gray') plt.scatter(y_valid, oof, alpha=0.05, color=cp[1]) plt.xlabel('true') plt.ylabel('pred') plt.show() # confusion_matrix plot_confusion_matrix(y_valid, oof_round, classes=np.arange(11)) # permutation importance pi = permutation_importance(model, f1_macro) # model と metric を渡す pi.compute(X_valid, y_valid) pi.show_permutation_importance(score_type='accuracy') # loss or accuracy plt.show() return test_pred_round, test_pred, oof_round, oof ###Output _____no_output_____ ###Markdown ref: https://www.kaggle.com/martxelo/fe-and-ensemble-mlp-and-lgbm ###Code def calc_gradients(s, n_grads=4): ''' Calculate gradients for a pandas series. Returns the same number of samples ''' grads = pd.DataFrame() g = s.values for i in range(n_grads): g = np.gradient(g) grads['grad_' + str(i+1)] = g return grads def calc_low_pass(s, n_filts=10): ''' Applies low pass filters to the signal. Left delayed and no delayed ''' wns = np.logspace(-2, -0.3, n_filts) # wns = [0.3244] low_pass = pd.DataFrame() x = s.values for wn in wns: b, a = signal.butter(1, Wn=wn, btype='low') zi = signal.lfilter_zi(b, a) low_pass['lowpass_lf_' + str('%.4f' %wn)] = signal.lfilter(b, a, x, zi=zi*x[0])[0] low_pass['lowpass_ff_' + str('%.4f' %wn)] = signal.filtfilt(b, a, x) return low_pass def calc_high_pass(s, n_filts=10): ''' Applies high pass filters to the signal. Left delayed and no delayed ''' wns = np.logspace(-2, -0.1, n_filts) # wns = [0.0100, 0.0264, 0.0699, 0.3005, 0.4885, 0.7943] high_pass = pd.DataFrame() x = s.values for wn in wns: b, a = signal.butter(1, Wn=wn, btype='high') zi = signal.lfilter_zi(b, a) high_pass['highpass_lf_' + str('%.4f' %wn)] = signal.lfilter(b, a, x, zi=zi*x[0])[0] high_pass['highpass_ff_' + str('%.4f' %wn)] = signal.filtfilt(b, a, x) return high_pass def calc_roll_stats(s, windows=[10, 50, 100, 500, 1000, 3000]): ''' Calculates rolling stats like mean, std, min, max... ''' roll_stats = pd.DataFrame() for w in windows: roll_stats['roll_mean_' + str(w)] = s.rolling(window=w, min_periods=1).mean().interpolate('spline', order=5, limit_direction='both') roll_stats['roll_std_' + str(w)] = s.rolling(window=w, min_periods=1).std().interpolate('spline', order=5, limit_direction='both') roll_stats['roll_min_' + str(w)] = s.rolling(window=w, min_periods=1).min().interpolate('spline', order=5, limit_direction='both') roll_stats['roll_max_' + str(w)] = s.rolling(window=w, min_periods=1).max().interpolate('spline', order=5, limit_direction='both') roll_stats['roll_range_' + str(w)] = roll_stats['roll_max_' + str(w)] - roll_stats['roll_min_' + str(w)] roll_stats['roll_q10_' + str(w)] = s.rolling(window=w, min_periods=1).quantile(0.10).interpolate('spline', order=5, limit_direction='both') roll_stats['roll_q25_' + str(w)] = s.rolling(window=w, min_periods=1).quantile(0.25).interpolate('spline', order=5, limit_direction='both') roll_stats['roll_q50_' + str(w)] = s.rolling(window=w, min_periods=1).quantile(0.50).interpolate('spline', order=5, limit_direction='both') roll_stats['roll_q75_' + str(w)] = s.rolling(window=w, min_periods=1).quantile(0.75).interpolate('spline', order=5, limit_direction='both') roll_stats['roll_q90_' + str(w)] = s.rolling(window=w, min_periods=1).quantile(0.90).interpolate('spline', order=5, limit_direction='both') # add zeros when na values (std) # roll_stats = roll_stats.fillna(value=0) return roll_stats def calc_ewm(s, windows=[10, 50, 100, 500, 1000, 3000]): ''' Calculates exponential weighted functions ''' ewm = pd.DataFrame() for w in windows: ewm['ewm_mean_' + str(w)] = s.ewm(span=w, min_periods=1).mean() ewm['ewm_std_' + str(w)] = s.ewm(span=w, min_periods=1).std() # add zeros when na values (std) ewm = ewm.fillna(value=0) return ewm def divide_and_add_features(s, signal_size=500000): ''' Divide the signal in bags of "signal_size". Normalize the data dividing it by 15.0 ''' # normalize s = s/15.0 ls = [] for i in progress_bar(range(int(s.shape[0]/signal_size))): sig = s[i*signal_size:(i+1)*signal_size].copy().reset_index(drop=True) sig_featured = add_features(sig) ls.append(sig_featured) return pd.concat(ls, axis=0) ###Output _____no_output_____ ###Markdown ref: https://www.kaggle.com/nxrprime/single-model-lgbm-kalman-filter-ii ###Code def Kalman1D(observations,damping=1): # To return the smoothed time series data observation_covariance = damping initial_value_guess = observations[0] transition_matrix = 1 transition_covariance = 0.1 initial_value_guess kf = KalmanFilter( initial_state_mean=initial_value_guess, initial_state_covariance=observation_covariance, observation_covariance=observation_covariance, transition_covariance=transition_covariance, transition_matrices=transition_matrix ) pred_state, state_cov = kf.smooth(observations) return pred_state ###Output _____no_output_____ ###Markdown Preparation setting ###Code sns.set() ###Output _____no_output_____ ###Markdown load dataset ###Code df_tr = pd.read_csv(PATH_TRAIN) df_te = pd.read_csv(PATH_TEST) ###Output _____no_output_____ ###Markdown 処理のしやすさのために、バッチ番号を振る ###Code batch_list = [] for n in range(10): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_tr['batch'] = batch_list batch_list = [] for n in range(4): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_te['batch'] = batch_list ###Output _____no_output_____ ###Markdown smallset? ###Code if isSmallSet: print('small set mode') # train batchs = df_tr['batch'].values dfs = [] for i_bt, bt in enumerate(df_tr['batch'].unique()): idxs = batchs == bt _df = df_tr[idxs][:LENGTH].copy() dfs.append(_df) df_tr = pd.concat(dfs).reset_index(drop=True) # test batchs = df_te['batch'].values dfs = [] for i_bt, bt in enumerate(df_te['batch'].unique()): idxs = batchs == bt _df = df_te[idxs][:LENGTH].copy() dfs.append(_df) df_te = pd.concat(dfs).reset_index(drop=True) ###Output _____no_output_____ ###Markdown Train ###Code # configurations and main hyperparammeters # EPOCHS = 180 EPOCHS = 180 NNBATCHSIZE = 16 GROUP_BATCH_SIZE = 4000 SEED = 321 LR = 0.0015 SPLITS = 5 def seed_everything(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) # tf.random.set_seed(seed) # read data def read_data(): train = pd.read_csv(PATH_TRAIN, dtype={'time': np.float32, 'signal': np.float32, 'open_channels':np.int32}) test = pd.read_csv(PATH_TEST, dtype={'time': np.float32, 'signal': np.float32}) sub = pd.read_csv(PATH_SMPLE_SUB, dtype={'time': np.float32}) # Y_train_proba = np.load('./../data/input/Y_train_proba.npy') # Y_test_proba = np.load('./../data/input/Y_test_proba.npy') probas = np.load(PATH_PROBAS) Y_train_proba = probas['arr_0'] Y_test_proba = probas['arr_1'] for i in range(11): train[f"proba_{i}"] = Y_train_proba[:, i] test[f"proba_{i}"] = Y_test_proba[:, i] # add offset batch_list = [] for n in range(10): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) train['batch'] = batch_list batch_list = [] for n in range(4): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) test['batch'] = batch_list group = group_feat_train(train) train = pd.concat([train, group], axis=1) group = group_feat_test(test) test = pd.concat([test, group], axis=1) off_set_4 = 0.952472 - (-1.766044) off_set_9 = 0.952472 - (-1.770441) # batch4 idxs = train['batch'] == 4 train['signal'][idxs] = train['signal'].values + off_set_4 # batch9 idxs = train['batch'] == 9 train['signal'][idxs] = train['signal'].values + off_set_9 off_set_test = 2.750 # group4 idxs = test['group'] == 4 test['signal'][idxs] = test['signal'][idxs].values + off_set_test # mod batch7 if MOD_BATCH7: train = create_signal_mod2(train) plt.figure(figsize=(20, 3)) plt.plot(train['signal']) plt.show() plt.figure(figsize=(20, 3)) plt.plot(test['signal']) plt.show() train = train.drop(['batch', 'group'], axis=1) test = test.drop(['batch', 'group'], axis=1) return train, test, sub # create batches of 4000 observations def batching(df, batch_size): df['group'] = df.groupby(df.index//batch_size, sort=False)['signal'].agg(['ngroup']).values df['group'] = df['group'].astype(np.uint16) return df # normalize the data (standard scaler). We can also try other scalers for a better score! def normalize(train, test): train_input_mean = train.signal.mean() train_input_sigma = train.signal.std() train['signal'] = (train.signal - train_input_mean) / train_input_sigma test['signal'] = (test.signal - train_input_mean) / train_input_sigma return train, test # get lead and lags features def lag_with_pct_change(df, windows): for window in windows: df['signal_shift_pos_' + str(window)] = df.groupby('group')['signal'].shift(window).fillna(0) df['signal_shift_neg_' + str(window)] = df.groupby('group')['signal'].shift(-1 * window).fillna(0) return df def roll_stats(df, windows): for w in windows: df['roll_mean_' + str(w)] = df.groupby('group')['signal'].rolling(window=w, min_periods=1).mean().values df['roll_std_' + str(w)] = df.groupby('group')['signal'].rolling(window=w, min_periods=1).std().values return df # main module to run feature engineering. Here you may want to try and add other features and check if your score imporves :). def run_feat_engineering(df, batch_size): # create batches df = batching(df, batch_size = batch_size) # create leads and lags (1, 2, 3 making them 6 features) df = lag_with_pct_change(df, [1, 2, 3]) # create signal ** 2 (this is the new feature) df['signal_2'] = df['signal'] ** 2 # roll_stats if ROLL_FEATS: df = roll_stats(df, [10, 300]) return df # fillna with the mean and select features for training def feature_selection(train, test): features = [col for col in train.columns if col not in ['index', 'group', 'open_channels', 'time']] train = train.replace([np.inf, -np.inf], np.nan) test = test.replace([np.inf, -np.inf], np.nan) for feature in features: feature_mean = pd.concat([train[feature], test[feature]], axis = 0).mean() train[feature] = train[feature].fillna(feature_mean) test[feature] = test[feature].fillna(feature_mean) return train, test, features # model function (very important, you can try different arquitectures to get a better score. I believe that top public leaderboard is a 1D Conv + RNN style) def Classifier(shape_): def cbr(x, out_layer, kernel, stride, dilation): x = Conv1D(out_layer, kernel_size=kernel, dilation_rate=dilation, strides=stride, padding="same")(x) x = BatchNormalization()(x) x = Activation("relu")(x) return x def wave_block(x, filters, kernel_size, n): dilation_rates = [2**i for i in range(n)] x = Conv1D(filters = filters, kernel_size = 1, padding = 'same')(x) res_x = x for dilation_rate in dilation_rates: tanh_out = Conv1D(filters = filters, kernel_size = kernel_size, padding = 'same', activation = 'tanh', dilation_rate = dilation_rate)(x) sigm_out = Conv1D(filters = filters, kernel_size = kernel_size, padding = 'same', activation = 'sigmoid', dilation_rate = dilation_rate)(x) x = Multiply()([tanh_out, sigm_out]) x = Conv1D(filters = filters, kernel_size = 1, padding = 'same')(x) res_x = Add()([res_x, x]) return res_x inp = Input(shape = (shape_)) x = cbr(inp, 64, 7, 1, 1) # x = BatchNormalization()(x) # 追加 (参考: https://www.kaggle.com/siavrez/wavenet-keras) # x = wave_block(x, 8, 3, 18) # 追加 x = BatchNormalization()(x) x = wave_block(x, 16, 3, 12) x = BatchNormalization()(x) x = wave_block(x, 32, 3, 8) x = BatchNormalization()(x) x = wave_block(x, 64, 3, 4) x = BatchNormalization()(x) x = wave_block(x, 128, 3, 1) x = cbr(x, 32, 7, 1, 1) x = BatchNormalization()(x) x = Dropout(0.2)(x) out = Dense(11, activation = 'softmax', name = 'out')(x) model = models.Model(inputs = inp, outputs = out) opt = Adam(lr = LR) # opt = tfa.optimizers.SWA(opt) # model.compile(loss = losses.CategoricalCrossentropy(), optimizer = opt, metrics = ['accuracy']) model.compile(loss = categorical_crossentropy, optimizer = opt, metrics = ['accuracy']) return model # function that decrease the learning as epochs increase (i also change this part of the code) def lr_schedule(epoch): if epoch < 30: lr = LR elif epoch < 40: lr = LR / 3 elif epoch < 50: lr = LR / 5 elif epoch < 60: lr = LR / 7 elif epoch < 70: lr = LR / 9 elif epoch < 80: lr = LR / 11 elif epoch < 90: lr = LR / 13 else: lr = LR / 100 return lr # class to get macro f1 score. This is not entirely necessary but it's fun to check f1 score of each epoch (be carefull, if you use this function early stopping callback will not work) class MacroF1(Callback): def __init__(self, model, inputs, targets): self.model = model self.inputs = inputs self.targets = np.argmax(targets, axis = 2).reshape(-1) def on_epoch_end(self, epoch, logs): pred = np.argmax(self.model.predict(self.inputs), axis = 2).reshape(-1) score = f1_score(self.targets, pred, average = 'macro') print(f'F1 Macro Score: {score:.5f}') # main function to perfrom groupkfold cross validation (we have 1000 vectores of 4000 rows and 8 features (columns)). Going to make 5 groups with this subgroups. def run_cv_model_by_batch(train, test, _splits, batch_col, feats, sample_submission, nn_epochs, nn_batch_size): seed_everything(SEED) K.clear_session() # config = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1, # gpu_options=tf.compat.v1.GPUOptions( # visible_device_list='4', # specify GPU number # allow_growth=True # ) # ) # sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=config) # tf.compat.v1.keras.backend.set_session(sess) # tf.compat.v1 ---> tf (tensorflow2系からtensorflow1系に変更) config = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1, # gpu_options=tf.GPUOptions( # visible_device_list='4', # specify GPU number # allow_growth=True # ) ) sess = tf.Session(graph=tf.get_default_graph(), config=config) tf.keras.backend.set_session(sess) oof_ = np.zeros((len(train), 11)) # build out of folds matrix with 11 columns, they represent our target variables classes (from 0 to 10) preds_ = np.zeros((len(test), 11)) target = ['open_channels'] group = train['group'] kf = GroupKFold(n_splits=_splits) splits = [x for x in kf.split(train, train[target], group)] new_splits = [] for sp in splits: new_split = [] new_split.append(np.unique(group[sp[0]])) new_split.append(np.unique(group[sp[1]])) new_split.append(sp[1]) new_splits.append(new_split) # pivot target columns to transform the net to a multiclass classification estructure (you can also leave it in 1 vector with sparsecategoricalcrossentropy loss function) tr = pd.concat([pd.get_dummies(train.open_channels), train[['group']]], axis=1) tr.columns = ['target_'+str(i) for i in range(11)] + ['group'] target_cols = ['target_'+str(i) for i in range(11)] train_tr = np.array(list(tr.groupby('group').apply(lambda x: x[target_cols].values))).astype(np.float32) train = np.array(list(train.groupby('group').apply(lambda x: x[feats].values))) test = np.array(list(test.groupby('group').apply(lambda x: x[feats].values))) for n_fold, (tr_idx, val_idx, val_orig_idx) in enumerate(new_splits[0:], start=0): train_x, train_y = train[tr_idx], train_tr[tr_idx] valid_x, valid_y = train[val_idx], train_tr[val_idx] print(f'Our training dataset shape is {train_x.shape}') print(f'Our validation dataset shape is {valid_x.shape}') gc.collect() shape_ = (None, train_x.shape[2]) # input is going to be the number of feature we are using (dimension 2 of 0, 1, 2) model = Classifier(shape_) # using our lr_schedule function cb_lr_schedule = LearningRateScheduler(lr_schedule) model.fit(train_x,train_y, epochs = nn_epochs, callbacks = [cb_lr_schedule, MacroF1(model, valid_x, valid_y)], # adding custom evaluation metric for each epoch batch_size = nn_batch_size,verbose = 2, validation_data = (valid_x,valid_y)) preds_f = model.predict(valid_x) f1_score_ = f1_score(np.argmax(valid_y, axis=2).reshape(-1), np.argmax(preds_f, axis=2).reshape(-1), average = 'macro') # need to get the class with the biggest probability print(f'Training fold {n_fold + 1} completed. macro f1 score : {f1_score_ :1.5f}') preds_f = preds_f.reshape(-1, preds_f.shape[-1]) oof_[val_orig_idx,:] += preds_f te_preds = model.predict(test) te_preds = te_preds.reshape(-1, te_preds.shape[-1]) preds_ += te_preds / _splits # calculate the oof macro f1_score f1_score_ = f1_score(np.argmax(train_tr, axis = 2).reshape(-1), np.argmax(oof_, axis = 1), average = 'macro') # axis 2 for the 3 Dimension array and axis 1 for the 2 Domension Array (extracting the best class) print(f'Training completed. oof macro f1 score : {f1_score_:1.5f}') # submission save_path = f'{DIR_OUTPUT}submission_nb{NB}_cv_{f1_score_:.4f}.csv' print(f'submission save path: {save_path}') sample_submission['open_channels'] = np.argmax(preds_, axis = 1).astype(int) sample_submission.to_csv(save_path, index=False, float_format='%.4f') # probas save_path = f'{DIR_OUTPUT_IGNORE}probas_nb{NB}_cv_{f1_score_:.4f}' print(f'probas save path: {save_path}') np.savez_compressed(save_path, oof_, preds_) return oof_ %%time # this function run our entire program def run_everything(): print(f'Reading Data Started...({time.ctime()})') train, test, sample_submission = read_data() train, test = normalize(train, test) print(f'Reading and Normalizing Data Completed') print(f'Creating Features({time.ctime()})') print(f'Feature Engineering Started...') train = run_feat_engineering(train, batch_size = GROUP_BATCH_SIZE) test = run_feat_engineering(test, batch_size = GROUP_BATCH_SIZE) train, test, features = feature_selection(train, test) print(f'Feature Engineering Completed...') print(f'Training Wavenet model with {SPLITS} folds of GroupKFold Started...({time.ctime()})') oof_ = run_cv_model_by_batch(train, test, SPLITS, 'group', features, sample_submission, EPOCHS, NNBATCHSIZE) print(f'Training completed...') return oof_ oof_ = run_everything() ###Output Reading Data Started...(Sun May 17 08:47:29 2020) ###Markdown analysis ###Code df_tr = pd.read_csv(PATH_TRAIN) batch_list = [] for n in range(10): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_tr['batch'] = batch_list # group 特徴量を作成 group = group_feat_train(df_tr) df_tr = pd.concat([df_tr, group], axis=1) y = df_tr['open_channels'].values oof = np.argmax(oof_, axis=1).astype(int) for group in sorted(df_tr['group'].unique()): idxs = df_tr['group'] == group oof_grp = oof[idxs].astype(int) y_grp = y[idxs] print(f'group_score({group}): {f1_score(y_grp, oof_grp, average="micro"):4f}') max_ = df_tr.loc[df_tr['batch']==3]['signal'].max() min_ = df_tr.loc[df_tr['batch']==3]['signal'].min() idxs = (df_tr['batch']==7) & (df_tr['signal']>max_) df_tr['signal'][idxs] = max_ idxs = (df_tr['batch']==7) & (df_tr['signal']<min_) df_tr['signal'][idxs] = min_ ###Output _____no_output_____ ###Markdown 可視化 ###Code x_idx = np.arange(len(df_tr)) idxs = y != oof failed = np.zeros(len(df_tr)) failed[idxs] = 1 n = 200 b = np.ones(n)/n failed_move = np.convolve(failed, b, mode='same') fig, axs = plt.subplots(2, 1, figsize=(20, 6)) axs = axs.ravel() # fig = plt.figure(figsize=(20, 3)) for i_gr, group in enumerate(sorted(df_tr['group'].unique())): idxs = df_tr['group'] == group axs[0].plot(np.arange(len(df_tr))[idxs], df_tr['signal'].values[idxs], color=cp[i_gr], label=f'group={group}') for x in range(10): axs[0].axvline(x*500000 + 500000, color='gray') axs[0].text(x*500000 + 250000, 5, x) axs[0].plot(x_idx, failed_move*10, '.', color='black', label='failed_mv') axs[0].set_xlim(0, 5500000) axs[0].legend() axs[1].plot(x_idx, y) axs[1].set_xlim(0, 5500000) # fig.legend() ###Output _____no_output_____
doc/turtle/turtle.ipynb
###Markdown Dessiner avec la tortueLe module `turtle` permet de dessiner à l'aide d'une petite tortue. ###Code cd turtle from turtle import * forward(100) ###Output _____no_output_____ ###Markdown Utilisez la fonction `done()` pour terminer. Ensuite vous pouvez fermer la fentêtre. ###Code done() ls ###Output turtle.cfg turtle.ipynb turtle1.png ###Markdown Etoile ###Code from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) < 1: break end_fill() done() ###Output _____no_output_____ ###Markdown Square ###Code for i in range(4): forward(100) left(90) def square(d): for i in range(4): forward(d) left(90) square(10) for i in range(10, 100, 10): square(i) done() ###Output _____no_output_____ ###Markdown Config ###Code cat turtle.cfg circle(50) dot() import random for i in range(10): x = random.randint(-100, 100) y = random.randint(-100, 100) goto(x, y) dot() clear() ###Output _____no_output_____
pandas_exercise3.ipynb
###Markdown ###Code import pandas as pd import numpy as np url='https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/Students_Alcohol_Consumption/student-mat.csv' df=pd.read_csv(url) df.head() school=df.loc[:,"school":"guardian"] school.head() #capatilize the all the string capitalizer=lambda x: x.capitalize() school['Fjob'].apply(capitalizer) school['Mjob'].apply(capitalizer) school.tail() school['Fjob']=school['Fjob'].apply(capitalizer) school['Mjob']=school['Mjob'].apply(capitalizer) school.tail() def legal_drinker(x): if x > 17: return True else: return False school["legal_drinker"]=school['age'].apply(legal_drinker) school.head() def multiply(x): if type(x) is int: return 10 * x return x school.applymap(multiply).head(5) ###Output _____no_output_____
notebooks/Figure 4 - 2D_vs_3D_analysis.ipynb
###Markdown Load cell detections, cell-type labels, ventricle segmentation, and organoid segmentation ###Code centers = np.load(os.path.join(working_dir, 'centroids.npy')) labels = np.load(os.path.join(working_dir, 'nuclei_gating.npy')) foreground = io.imread(os.path.join(working_dir, 'segment_foreground.tif')) ventricles = io.imread(os.path.join(working_dir, 'segment_ventricles.tif')) centers.shape, labels.shape, foreground.shape, ventricles.shape ###Output _____no_output_____ ###Markdown Get voxel dimensions to be able to refer to physical dimensions ###Code downsample = np.array([1, 6, 6]) voxelsize = utils.read_voxel_size(os.path.join(working_dir, 'voxel_size.csv')) voxelsize_down = voxelsize * downsample voxelsize, voxelsize_down ###Output _____no_output_____ ###Markdown Count cells along z-axis to see where which slices are valid ###Code %matplotlib notebook zrange = 330 zcounts = np.bincount(centers[:, 0], minlength=len(foreground)) zmean = (np.arange(len(foreground)) * zcounts).sum() // zcounts.sum() plt.figure() sns.lineplot(np.arange(len(foreground)), zcounts) plt.plot([zmean, zmean], [0, 5000], 'r-') plt.plot([zmean-zrange, zmean-zrange], [0, 5000], 'r--') plt.plot([zmean+zrange, zmean+zrange], [0, 5000], 'r--') plt.xlabel('zslice #') plt.ylabel('count') plt.title('zcounts') plt.show() plt.figure() plot.zprojection(ventricles, centers / downsample, zlim=[zmean-1, zmean+1], markersize=2) plt.imshow(foreground[zmean], cmap='gray', alpha=0.5) plt.axis('off') plt.title('foreground, ventricles, and cell centers @ zmean') plt.show() ###Output _____no_output_____ ###Markdown Get SOX2, TBR1, and DN centers ###Code utils.read_csv(os.path.join(working_dir, 'celltype_names.csv')) centers_sox2 = centers[np.where(labels[:, 0] == 1)] centers_tbr1 = centers[np.where(labels[:, 1] == 1)] centers_dn = centers[np.where(np.logical_and(labels[:, 0] == 0, labels[:, 1] == 0))] centers_sox2.shape, centers_tbr1.shape, centers_dn.shape ventricles_smooth = smooth_segmentation(ventricles, sigma=2) > 0.5 def pseudoslice(zlim): # Get full slice bounds zstart = zlim[0] zstop = zlim[1] start = np.asarray([zstart, 0, 0]) stop = np.asarray([zstop, *foreground.shape[1:]]) # Extract cells in full slice slice_centers = utils.filter_points_in_box(centers / downsample, start, stop) slice_sox2 = utils.filter_points_in_box(centers_sox2 / downsample, start, stop) slice_tbr1 = utils.filter_points_in_box(centers_tbr1 / downsample, start, stop) slice_dn = utils.filter_points_in_box(centers_dn / downsample, start, stop) # Extract segmentations of full slice slice_foreground = foreground[zstart:zstop] slice_ventricles = ventricles_smooth[zstart:zstop] slice_data = { 'centers': slice_centers, 'centers_sox2': slice_sox2, 'centers_tbr1': slice_tbr1, 'centers_dn': slice_dn, 'foreground': slice_foreground, 'ventricles': slice_ventricles, } return slice_data def measure_pseudoslice(s): # Cell frequencies freq_sox2 = len(s['centers_sox2']) / len(s['centers']) freq_tbr1 = len(s['centers_tbr1']) / len(s['centers']) freq_dn = len(s['centers_dn']) / len(s['centers']) # Cell densities svol = (s['foreground'] > 0).sum() * voxelsize_down.prod() / 1000**3 density_centers = len(s['centers']) / svol density_sox2 = len(s['centers_sox2']) / svol density_tbr1 = len(s['centers_sox2']) / svol density_dn = len(s['centers_dn']) / svol # Ventricle count seg = s['ventricles'] lbl, n_ventricles = label(seg) # Ventricle eq. diameter regions = regionprops(lbl) eqdiams = np.asarray([r.equivalent_diameter for r in regions]) ave_eqdiam = eqdiams.mean() measurements = { 'sox2 frequency': freq_sox2, 'tbr1 frequency': freq_tbr1, 'dn frequency': freq_dn, 'cell density': density_centers, 'sox2 cell density': density_sox2, 'tbr1 cell density': density_tbr1, 'dn cell density': density_dn, 'ventricle count': n_ventricles, 'ventricle average diameter': ave_eqdiam } return measurements ###Output _____no_output_____ ###Markdown Get whole org measurements by taking large pseudoslice ###Code zcenter = zmean nslices = zrange zlim = [zcenter-nslices, zcenter+nslices] # zlim = [0, 650] s = pseudoslice(zlim) wholeorg = measure_pseudoslice(s) wholeorg zrange = 180 zcounts = np.bincount(centers[:, 0], minlength=len(foreground)) zmean = (np.arange(len(foreground)) * zcounts).sum() // zcounts.sum() plt.figure() sns.lineplot(np.arange(len(foreground)), zcounts) plt.plot([zmean, zmean], [0, 5000], 'r-') plt.plot([zmean-zrange, zmean-zrange], [0, 5000], 'r--') plt.plot([zmean+zrange, zmean+zrange], [0, 5000], 'r--') plt.xlabel('zslice #') plt.ylabel('count') plt.title('zcounts') plt.show() zmin = zmean - zrange zmax = zmean + zrange zmin, zmax def sample_and_measure(zcenter): zlim = np.asarray([zcenter - nslices//2, zcenter + nslices//2]).astype(np.int) s = pseudoslice(zlim) return measure_pseudoslice(s) thickness = 100 # micron n_samples = 10000 nslices = thickness // voxelsize_down[0] zcenters = np.random.randint(zmin + nslices//2, zmax - nslices//2, n_samples) with mp.Pool(mp.cpu_count()) as pool: ms = list(tqdm(pool.imap(sample_and_measure, zcenters), total=len(zcenters))) df = pd.DataFrame(ms) df.head() %matplotlib inline for measurement in list(wholeorg.keys()): plt.figure(figsize=(4, 2)) sns.distplot(df[measurement], label='2D') plt.plot([wholeorg[measurement]], [0], 'r*', label='3D') plt.xlabel(measurement) plt.legend() plt.tight_layout() plt.show() ###Output _____no_output_____ ###Markdown We have an estimate of the population variance from this bootstrapped sampling procedure.For any of the measurements that are not systematically biased, we can estimate the sample size neededfor the mean to be expected to be within 5% of the true mean using the central limit theorem.$$\hat{\sigma} = \frac{\sigma}{\sqrt{n}} \Rightarrow n = (\frac{\sigma}{\hat{\sigma}})^2$$We need our expected sample mean to be within 5% of the true sample mean,$$2 \hat{\sigma} = 0.05 \mu \Rightarrow \hat{\sigma} = 0.025 \mu$$$$n = \frac{\sigma^2}{(0.025 \mu)^2} $$ ###Code measurement = 'tbr1 frequency' mu = wholeorg[measurement] sigma = df[measurement].std() n = sigma**2 / (0.025 * mu)**2 f'Minimum number of slices {np.ceil(n).astype(np.int)} to be within 5%' measurement = 'ventricle average diameter' mu = wholeorg[measurement] sigma = df[measurement].std() n = sigma**2 / (0.025 * mu)**2 f'Minimum number of slices {np.ceil(n).astype(np.int)} to be within 5%' f'Maximum possible slices in zrange: {((zmax-zmin)*voxelsize_down[0] / thickness).astype(np.int)}' # Save results df.to_excel(os.path.join(working_dir, 'pseudosections.xlsx')) df_wholeorg = pd.DataFrame(wholeorg, index=[0]) df_wholeorg.head() df_wholeorg.to_excel(os.path.join(working_dir, 'pseudosections_wholeorg.xlsx')) ###Output _____no_output_____ ###Markdown Aggregate all measurements ###Code working_dir = '/data/datasets/organoid_phenotyping/analysis/d35_vs_d60' analysis = pd.read_csv(os.path.join(working_dir, 'analysis.csv'), index_col=0) analysis.head() dfs = [] dfs_wholeorg = [] for org_idx, path in enumerate(analysis.index): folder = analysis['type'].loc[path] if folder != 'Lancaster_d35': continue df = pd.read_excel(os.path.join(working_dir, folder, path, 'dataset/pseudosections.xlsx'), index_col=0) df['org_idx'] = len(df) * [org_idx] df.index = np.arange(len(df)) + org_idx * len(df) df_wholeorg = pd.read_excel(os.path.join(working_dir, folder, path, 'dataset/pseudosections_wholeorg.xlsx'), index_col=0) dfs.append(df) dfs_wholeorg.append(df_wholeorg) df = pd.concat(dfs) df_wholeorg = pd.concat(dfs_wholeorg) df.head() df.tail() df_wholeorg.index = np.arange(len(df_wholeorg)) df_wholeorg.head() ###Output _____no_output_____ ###Markdown Pick out 3 slices, show slice variability in a simple bar chart ###Code slices = df.iloc[12:15].copy() wholeorg = df_wholeorg.iloc[0].copy() wholeorg['sample'] = 'Whole org' df_example = slices df_example['sample'] = ['Section 1', 'Section 2', 'Section 3'] df_example = df_example.append(wholeorg) df_example %matplotlib inline plt.figure(figsize=(6, 4)) plt.subplot(1, 3, 1) sns.barplot(x='sample', y='sox2 frequency', data=df_example, color='r') plt.ylim([0, 0.6]) plt.subplot(1, 3, 2) sns.barplot(x='sample', y='tbr1 frequency', data=df_example, color='g') plt.ylim([0, 0.6]) plt.subplot(1, 3, 3) sns.barplot(x='sample', y='dn frequency', data=df_example, color='b') plt.ylim([0, 0.6]) plt.tight_layout() sns.despine() plt.savefig(os.path.join(working_dir, 'example_slices.pdf'), bbox_inches='tight') plt.show() ###Output _____no_output_____ ###Markdown SOX2, TBR1, DN freq distributions intraorganoid vs interorganoid ###Code df_wholeorg df_wholeorg2 = df_wholeorg.drop([9, 11]) df2 = df#.loc[::1000] plt.figure(figsize=(3, 5)) plt.subplot(3, 1, 1) sns.distplot(df2['sox2 frequency'], bins=32, kde_kws={'bw': 0.02, 'shade': False}, hist=False, color='k', label='2D') sns.distplot(df_wholeorg2['sox2 frequency'], kde_kws={'bw': 0.02, 'shade': True}, hist=False, rug=True, color='r', label='3D') plt.xlim([0, 0.8]) plt.legend() # plt.ylabel('Density') plt.subplot(3, 1, 2) sns.distplot(df2['tbr1 frequency'], bins=32, kde_kws={'bw': 0.025, 'shade': False}, hist=False, color='k') sns.distplot(df_wholeorg2['tbr1 frequency'], kde_kws={'bw': 0.010, 'shade': True}, hist=False, rug=True, color='g') plt.xlim([0, 0.8]) plt.ylabel('Density') plt.subplot(3, 1, 3) sns.distplot(df2['dn frequency'], bins=32, kde_kws={'bw': 0.03, 'shade': False}, hist=False, color='k') sns.distplot(df_wholeorg2['dn frequency'], kde_kws={'bw': 0.03, 'shade': True}, hist=False, rug=True, color='b') plt.xlim([0, 0.8]) # plt.ylabel('Density') sns.despine() plt.tight_layout() plt.savefig(os.path.join(working_dir, 'pseudoslice_2d_vs_3d_dist.pdf'), bbox_inches='tight') plt.show() ###Output _____no_output_____ ###Markdown Use variance ratio to estimate the number of samples needed for slices to match whole org ###Code n = 1 n_sox2 = (df2['sox2 frequency'].std() / (df_wholeorg2['sox2 frequency'].std()/np.sqrt(n)))**2 n_tbr1 = (df2['tbr1 frequency'].std() / (df_wholeorg2['tbr1 frequency'].std()/np.sqrt(n)))**2 n_dn = (df2['dn frequency'].std() / (df_wholeorg2['dn frequency'].std()/np.sqrt(n)))**2 n_sox2, n_tbr1, n_dn df_sigma = pd.DataFrame({'celltype': 2 * ['SOX2', 'TBR1', 'DN'], 'sigma': [ df_wholeorg2['sox2 frequency'].std(), df_wholeorg2['tbr1 frequency'].std(), df_wholeorg2['dn frequency'].std(), df2['sox2 frequency'].std(), df2['tbr1 frequency'].std(), df2['dn frequency'].std() ], 'type': 3 * ['3D'] + 3 * ['2D']}) df_sigma plt.figure(figsize=(3, 4)) sns.barplot(x='celltype', y='sigma', hue='type', data=df_sigma) plt.tight_layout() plt.savefig(os.path.join(working_dir, 'pseudoslice_2d_vs_3d_sigma.pdf'), bbox_inches='tight') plt.show() ###Output _____no_output_____
Project2_Bacmman/0_making_selections.ipynb
###Markdown Dependencies ###Code %matplotlib inline %config InlineBackend.figure_format = 'retina' %gui qt import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import os from pybacmman.selections import saveAndOpenSelection ###Output _____no_output_____ ###Markdown Import Measurements from BACMMAN - The next command will read measurments exported from bacmman ###Code dsName = "test_run" # change to the actual name of the experiment objectClassIdx = 1 folder_path = "~/switchdrive/Biozentrum/Data/Bacmman_i2i/" # change this path so that it points to the folder containing experiment folders data = pd.read_csv(os.path.join(folder_path, dsName, f"{dsName}_{objectClassIdx}.csv"), sep=';') # 1 is for the object class #1 = bacteria data ax = data.GrowthRateArea.hist(bins=100, range=(-0.01, 0.05)) ax.set_xlabel("Growth Rate") ax.set_title("Bacteria MutH Growth Rate") ###Output _____no_output_____ ###Markdown Import Selections from BACMMAN - The next command will read selection exported from bacmman- See [here](https://github.com/jeanollion/bacmman/wiki/Selectionscreate-selections-from-python) on how to make selection - Task: make a selection only containing channels with cells - Hint: you can see if channels contain cells by selecting `Bacteria` in Displayed Objects` and then click one channel in the right panel - To export selection from BACMMAN select selections from the _data browsing_ tab and run the menu command _Run > Extract Selected Selections_ ###Code selection = pd.read_csv(os.path.join(folder_path, dsName, f"{dsName}_Selections.csv"), sep=';') # 1 is for the object class #1 = bacteria selection ###Output _____no_output_____ ###Markdown You can use this selection to subset a dataframe: use both _Position_ and _Indices_ columns to identify an object. ###Code from pybacmman.pandas import subsetByDataframe subset = subsetByDataframe(data, selection, on=["Position", "Indices"]) print(f"number of rows in data: {data.shape[0]}, selection: {selection.shape[0]} subset: {subset.shape[0]}") subset.head() ###Output number of rows in data: 2784, selection: 2784 subset: 2784 ###Markdown Export Selections To BACMMAN - The next command will create a subset of data containing only long cells, and save it as a selection directly into BACMMAN.- BACMMAN should be open before executing this command. ###Code data_subset = data[data.Length>8] print(f"number of objects: {data_subset.shape[0]}") saveAndOpenSelection(data_subset, dsName, 1, "long cells", address='127.0.0.1', port=25333, python_proxy_port=25334) ###Output number of objects: 1 ###Markdown - If an error occurs, if can be a problem of communication between java and python. BACMMAN includes a python gateway that is able to listen to queries from python. In the menu Misc> Python Gateway you can set the adress, port and python port and they must match with those set as argument of the _saveAndOpenSelection_ function. Manually edit segmentation and trackingIf needed you can manually edit segmentation and tracking using the Bacmman GUI, see [here](https://github.com/jeanollion/bacmman/wiki/Data-Curation) for instructions. You can also look [at this screencast](https://www.github.com/jeanollion/bacmman/wiki/resources/screencast/manual_correction_dataset2.webm) Using PandasLet's look in some more detail into the data structure. We can select the first frame and look at the table Note: you can remove `.head()` to look at the full table, or you can use `.tail()` to look at the end part ###Code data[data['Frame']==0].head(n=10) ###Output _____no_output_____ ###Markdown Now let's look at the last frame, and try to figure out how lineage info is stored and how cells are assigned id's ###Code data[data['Frame']==49].head(n=10) ###Output _____no_output_____ ###Markdown There is quite some info here, but it is a bit obscure:- `Position` is the name of the position (image)- `PositionIdx` is an integer keeping track of which position you are in - `Indices` corresponds to frame_nr - channel_nr - cell-nr- `Frame` is frame nr- `Idx` is cell nr (1 = mother cells)- `Bacteria` lineage keeps track of cell lineage (after each division a letter is added)Annoyingly there is no field for channel, so let's add it. > **Exercise** > > Think about how you could do this> > Hint: you can use python package [`re`](https://docs.python.org/3/library/re.html) to extract it from the `Indices` field ###Code #enter code here import re ChIdx = #make list/array with channel number for each row in data data['ChannelIdx'] = ChIdx data.head() ###Output _____no_output_____ ###Markdown Now let's look at the mother cell and first offspring in the first channel. Try to understand how lineages are connected.As you might notice lineages in different channels have the same BacteriaLineage code. Often it is very useful to have a unique lineage id, a number that is constant throughout a cell's life and that only occurs once within the data table. Can you come up with a good idea of how to implement this? ###Code data.loc[(data['Channel']==0) & (data['Idx']<2) & (data['Frame']<13)] ###Output _____no_output_____ ###Markdown To uniquely id a cell linage we need three pieces of info- `Position-idx`- `Channel-idx`- `Bacteria-Lineage`> **Exercise** > Add a unique lineage id to the dataframe ###Code data['LinIdx'] = # add code here data.head() ###Output _____no_output_____ ###Markdown Slight detour: [pandas dataframes](https://pandas.pydata.org) combined with [seaborn poltting library](https://seaborn.pydata.org) allow for some powerful data analysis.here two minor examples.First we plot the average life time of cells.Then we plot the length at birth vs length at division. ###Code life_time_cell = data.groupby('LinIdx').size() ax = sns.histplot(life_time_cell) ax.set_xlabel('life time of cell (in frames)') df_first_frame = data.groupby('LinIdx').first() df_last_frame = data.groupby('LinIdx').last() # df_last_frame includes cells that are lost, we should exclude them df_last_frame = df_last_frame.loc[(~np.isnan(df_last_frame['NextDivisionFrame']))] fig, axs = plt.subplots(1,3, figsize=(12,4)) sns.histplot(ax=axs[0], data=df_first_frame, x='Length') sns.histplot(ax=axs[1], data=df_last_frame, x='Length') sns.scatterplot(ax=axs[2], x=df_first_frame['Length'], y=df_last_frame['Length']) titles = ['length at birth', 'length at division', 'length at division vs length at birth'] for idx, title in enumerate(titles): axs[idx].set_title(title) ###Output _____no_output_____
dd_1/Part 4/Section 14 - Metaprogramming/09 - Metaclass Parameters.ipynb
###Markdown Metaclass Parameters When we use a metaclass we typically have something like this: ###Code class Metaclass(type): def __new__(mcls, name, bases, cls_dict): return super().__new__(mcls, name, bases, cls_dict) class MyClass(metaclass=Metaclass): pass type(MyClass), type(MyClass()) ###Output _____no_output_____ ###Markdown But is there a way to pass *additional* arguments to the metaclass `__new__` method? Starting in Python 3.6, the answer is yes. The restriction is that they **must** be passed as named arguments (positional args being used for specifying inheritance). First let's just try out a simple example to understand the syntax: ###Code class Metaclass(type): def __new__(mcls, name, bases, cls_dict, arg1, arg2, arg3=None): print(arg1, arg2, arg3) return super().__new__(mcls, name, bases, cls_dict) class MyClass(metaclass=Metaclass, arg1=10, arg2=20, arg3=30): pass class MyClass(metaclass=Metaclass, arg1=10, arg2=20): pass ###Output 10 20 None ###Markdown As you can see our metaclass `__new__` method received those arguments. Let's look at a more practical example of this: ###Code class AutoClassAttrib(type): def __new__(cls, name, bases, cls_dict, extra_attrs=None): if extra_attrs: print('Creating class with some extra attributes: ', extra_attrs) # here I'm going to things directly into the cls_dict namespace # but could also create the class first, then add using setattr for attr_name, attr_value in extra_attrs: cls_dict[attr_name] = attr_value return super().__new__(cls, name, bases, cls_dict) class Account(metaclass=AutoClassAttrib, extra_attrs=[('account_type', 'Savings'), ('apr', 0.5)]): pass vars(Account) ###Output _____no_output_____ ###Markdown As you can see the class now has these two extra attributes. We could also have just done it this way: ###Code class AutoClassAttrib(type): def __new__(cls, name, bases, cls_dict, extra_attrs=None): new_cls = super().__new__(cls, name, bases, cls_dict) if extra_attrs: print('Creating class with some extra attributes: ', extra_attrs) for attr_name, attr_value in extra_attrs: setattr(new_cls, attr_name, attr_value) return new_cls class Account(metaclass=AutoClassAttrib, extra_attrs=[('account_type', 'Savings'), ('apr', 0.5)]): pass vars(Account) ###Output _____no_output_____ ###Markdown Of course, we could just use `**kwargs` instead, to make it easier: ###Code class AutoClassAttrib(type): def __new__(cls, name, bases, cls_dict, **kwargs): new_cls = super().__new__(cls, name, bases, cls_dict) if kwargs: print('Creating class with some extra attributes: ', kwargs) for attr_name, attr_value in kwargs.items(): setattr(new_cls, attr_name, attr_value) return new_cls class Account(metaclass=AutoClassAttrib, account_type='Savings', apr=0.5): pass vars(Account) ###Output _____no_output_____
examples/basic/data/basic.ipynb
###Markdown Sidebar Controls ###Code VBox([Label(value='Parameter a:'), a_widget, Label(value='Parameter b:'), b_widget]) ###Output _____no_output_____ ###Markdown Column Output ###Code out ###Output _____no_output_____
aulas/eleicoes_2020.ipynb
###Markdown Conjuntos de dados disponíveis aqui:https://www.tse.jus.br/eleicoes/estatisticas/repositorio-de-dados-eleitorais-1/repositorio-de-dados-eleitorais **Importando os dados** ###Code import pandas as pd import seaborn as sns sns.set() cand_BRASIL = pd.read_csv("/content/drive/My Drive/Colab Datasets/eleicoes/consulta_cand_2020_BRASIL.csv", sep=';', encoding='iso-8859-1') cand_BRASIL cand_BRASIL.info() cand_BRASIL[cand_BRASIL['NM_URNA_CANDIDATO'].str.contains('BOLSONARO') == True] cand_BRASIL['ST_REELEICAO'].value_counts(normalize=True)*100 cand_BRASIL['DS_GRAU_INSTRUCAO'].value_counts(normalize=True) cand_BRASIL['DS_GRAU_INSTRUCAO'].value_counts(normalize=True).plot(kind='bar', title='Grau de Instrucao Candidatos 2020'); (100*cand_BRASIL['SG_PARTIDO'].value_counts(normalize=True)).plot(kind='bar', figsize=(12,6), title='Candidados por Partido 2020') cand_RJ = pd.read_csv("/content/drive/My Drive/Colab Datasets/eleicoes/consulta_cand_2020_RJ.csv", sep=';', encoding='iso-8859-1') cand_RJ cand_RJ.info() cand_RJ['ST_REELEICAO'].value_counts(normalize=True)*100 cand_RJ[cand_RJ['SG_PARTIDO']=='MDB']['DS_GRAU_INSTRUCAO'].value_counts(normalize=True)*100 cand_RJ[cand_RJ['SG_PARTIDO']=='PSOL']['DS_GRAU_INSTRUCAO'].value_counts(normalize=True)*100 cand_RJ[cand_RJ['SG_PARTIDO']=='NOVO']['DS_GRAU_INSTRUCAO'].value_counts(normalize=True)*100 perfil_eleitorado_2020 = pd.read_csv("/content/drive/My Drive/Colab Datasets/eleicoes/perfil_eleitorado_2020.csv", sep=';', encoding='iso-8859-1') perfil_eleitorado_2020.info() perfil_abstencao = pd.read_csv('/content/drive/My Drive/Colab Datasets/eleicoes/perfil_comparecimento_abstencao_2018.csv', sep=';', encoding='iso-8859-1') perfil_abstencao.info() perfil_abstencao['DS_GRAU_ESCOLARIDADE'].value_counts() perfil_abstencao['NR_ZONA'].value_counts() ###Output _____no_output_____
DL_PY/cap8.ipynb
###Markdown ![model](img/model.png) ###Code # create model model = Sequential() #entrada model.add(Dense(12, input_dim=8,kernel_initializer= "uniform" , activation= "relu" )) #capas profundas model.add(Dense(8, kernel_initializer= "uniform" , activation= "relu" )) #capa de salida, sigmoid por que arroja valores entre 0 y 1 model.add(Dense(1, kernel_initializer= "uniform" , activation= "sigmoid" )) model.compile(loss= "binary_crossentropy", optimizer= "adam" , metrics=[ "accuracy" ]) #model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10) model.fit(X_train, y_train, validation_data=(X_test,y_test),epochs=200, batch_size=10) scores = model.evaluate(X_test,y_test) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) import numpy as np import pandas as pd from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt import seaborn as sns logreg = LogisticRegression(solver="liblinear") logreg.fit(X_train, y_train) y_pred = logreg.predict(X_test) cnf_matrix = metrics.confusion_matrix(y_test,y_pred) cnf_matrix metrics.accuracy_score(y_test,y_pred) class_names = [0,1] fig, ax = plt.subplots() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names) plt.yticks(tick_marks, class_names) sns.heatmap(pd.DataFrame(cnf_matrix), annot = True, cmap="Blues_r", fmt="g") ax.xaxis.set_label_position("top") plt.tight_layout() plt.title("Matriz de confusion", y=1.1) plt.ylabel("Etiqueta Actual") plt.xlabel("Etiqueta de prediccion") ###Output _____no_output_____
Jupyter Notebooks/Ridge Classifier.ipynb
###Markdown Machine Learning Models for SCOPE: Ridge ClassifierModels will be coded here, but the official write up will be in the RMarkdown document. ###Code # load the data files import pandas as pd import numpy as np from pymodelutils import utils logs = pd.read_csv("data/metis_logs.csv") logs.head() # filter down to show the average opinion (0 means no alert, 1 means alert) logs['run_date'] = logs['run_date'].astype('datetime64[ns]') logs['is_alert'] = (np.where(logs['is_alert'] == 'f', 0, 1)) logs = logs.groupby(['series', 'kpi', 'run_date']).mean().round(0).reset_index() logs['is_campaign'] = np.where(logs['campaign_id'] > 0, 1, 0) logs = logs.drop(columns=['client_id', 'partner_id', 'campaign_id']) logs['is_alert'].describe() AS_data = pd.read_csv("data/python_AS.csv") AS_data.head() TS_data = pd.read_csv("data/python_TS.csv") TS_data.head() RexT_data = pd.read_csv("data/python_RexT.csv") RexT_data.head() ###Output _____no_output_____ ###Markdown Data PrepR has already filtered down the data to the days we are going to use and marked what is disqualified. We still have to handle the feature selection and one-hot encoding of select columns though. We also need to normalize it since out KPIs behave quite differently. ###Code # add column for AS to tell if it is campaign level or not AS_data['is_campaign'] = np.where(AS_data['campaign_id'] > 0, 1, 0) # drop the data we don't need for the model or for matching back to the logs AS_keep_columns = ['series', 'day', 'run_date', 'kpi', 'value', 'disqualified', 'is_campaign'] TS_keep_columns = ['series', 'day', 'run_date', 'site_type', 'event_name', 'kpi', 'value', 'disqualified'] RexT_drop_columns = ['ranking', 'day_of_week', 'day_of_month', 'month_of_year', 'day_of_year', 'week_of_year'] AS_data = AS_data[AS_keep_columns] TS_data = TS_data[TS_keep_columns] RexT_data = RexT_data.drop(columns=RexT_drop_columns) AS_data.head() TS_data.head() RexT_data.head() # add a new column to determine how many days before the run_date the day column entry is # this will enable us to pivot that data into separate columns for the features of our model utils.prep_dates(AS_data) utils.prep_dates(TS_data) utils.prep_dates(RexT_data) # inner joins to logs AS_data = pd.merge(AS_data, logs, on=['series', 'run_date', 'kpi', 'is_campaign'], how='inner') TS_data = pd.merge(TS_data, logs, on=['series', 'run_date', 'kpi'], how='inner') RexT_data = pd.merge(RexT_data, logs, on=['series', 'run_date', 'kpi'], how='inner') # filter out the disqualified data (AS and TS data only) AS_disqualified = AS_data[AS_data.disqualified] TS_disqualified = TS_data[TS_data.disqualified] # valid for model (AS and TS data only) valid_AS_raw = AS_data[~(AS_data.disqualified)] valid_TS_raw = TS_data[~(TS_data.disqualified)] # keep a copy of the raw RexT data RexT_data_raw = RexT_data.copy(deep=True) # final preparations to the data shape for use in the model valid_AS = utils.data_prep_pipeline(valid_AS_raw.copy(), indices=['series', 'run_date', 'kpi', 'is_campaign', 'is_alert'], cols=['kpi'], scaling_method=['standardize', 'min_max', 'percent_of_mean']) disqualified_AS = utils.data_prep_pipeline(AS_disqualified.copy(), indices=['series', 'run_date', 'kpi', 'is_campaign', 'is_alert'], cols=['kpi'], scaling_method=['standardize', 'min_max', 'percent_of_mean']) valid_TS = utils.data_prep_pipeline(valid_TS_raw.copy(), indices=['series', 'run_date', 'site_type', 'event_name', 'is_alert'], cols=['site_type', 'event_name'], scaling_method=['standardize', 'min_max', 'percent_of_mean']) disqualified_TS = utils.data_prep_pipeline(TS_disqualified.copy(), indices=['series', 'run_date', 'site_type', 'event_name', 'is_alert'], cols=['site_type', 'event_name'], scaling_method=['standardize', 'min_max', 'percent_of_mean']) valid_RexT = utils.data_prep_pipeline(utils.clean_regions(RexT_data), indices=['isCountry', 'isSubregion', 'isRegion', 'series', 'run_date', 'is_alert'], cols=['series'], scaling_method=['standardize', 'min_max', 'percent_of_mean']) # for the TS data we need to drop event_name_SITE LEVEL because it will always be the same as site_type_SITE LEVEL valid_TS = {key : value.drop(columns='event_name_SITE LEVEL') for key, value in valid_TS.items()} # add back missing columns for the disqualified data disqualified_TS['min_max']['time_delta_24'], disqualified_TS['min_max']['time_delta_25'] = (0,0) disqualified_TS['min_max']['site_type_SITE LEVEL'], disqualified_TS['min_max']['site_type_aios'] = (0,0) disqualified_TS['min_max']['time_delta_diff_23'], disqualified_TS['min_max']['time_delta_diff_24'] = (0,0) valid_AS['min_max'].head() valid_TS['percent_of_mean'].head() valid_RexT['standardize'].head() ###Output _____no_output_____ ###Markdown ModellingNow that all the data is prepped, we can start building some logistic regression models to test on. We also need to split our data into a test and train set being careful that we have an equal proportion of anomalies in each (because they are very few, we have to make sure we don't train or test the model on all the anomalies while the other gets none). Split Data into Train and Test Sets ###Code from sklearn.model_selection import train_test_split # scaling method to test AS_scaler = 'min_max' TS_scaler = 'min_max' RexT_scaler = 'min_max' # separate out data into feature matrices and target arrays AS_features = valid_AS[AS_scaler][[col for col in valid_AS[AS_scaler].columns if col not in ['series', 'run_date', 'is_alert']]] # this needs to be the model features AS_targets = valid_AS[AS_scaler]['is_alert'] # this needs to be the results from the logs (only) TS_features = valid_TS[TS_scaler][[col for col in valid_TS[TS_scaler].columns if col not in ['series', 'run_date', 'is_alert']]] TS_targets = valid_TS[TS_scaler]['is_alert'] RexT_features = valid_RexT[RexT_scaler][[col for col in valid_RexT[RexT_scaler].columns if col not in ['run_date', 'is_alert']]] RexT_targets = valid_RexT[RexT_scaler]['is_alert'] test_RexT_features = RexT_features.drop(columns=[col for col in RexT_features.columns if 'series' in col or col in ['isCountry', 'isSubregion', 'isRegion']]) # split into a train and test set without differences AS_X_train, AS_X_test, AS_y_train, AS_y_test = train_test_split(AS_features[[col for col in AS_features.columns if 'diff' not in col]], AS_targets, test_size=0.2, random_state=25) TS_X_train, TS_X_test, TS_y_train, TS_y_test = train_test_split(TS_features[[col for col in TS_features.columns if 'diff' not in col]], TS_targets, test_size=0.2, random_state=25) RexT_X_train, RexT_X_test, RexT_y_train, RexT_y_test = train_test_split(test_RexT_features[[col for col in test_RexT_features.columns if 'diff' not in col]], RexT_targets, test_size=0.5, random_state=25) # split into a train and test set with differences AS_X_train_diff, AS_X_test_diff, AS_y_train_diff, AS_y_test_diff = train_test_split(AS_features, AS_targets, test_size=0.2, random_state=25) TS_X_train_diff, TS_X_test_diff, TS_y_train_diff, TS_y_test_diff = train_test_split(TS_features, TS_targets, test_size=0.2, random_state=25) RexT_X_train_diff, RexT_X_test_diff, RexT_y_train_diff, RexT_y_test_diff = train_test_split(test_RexT_features, RexT_targets, test_size=0.5, random_state=25) ###Output _____no_output_____ ###Markdown Let's make sure that we have similar percentage of anomalies in our test and train sets. ###Code # AS print('Total alerts in training set: ' + str(AS_y_train.sum())) print('Total alerts in test set: ' + str(AS_y_test.sum())) pd.DataFrame({'train' : AS_y_train.value_counts(normalize=True), 'test' : AS_y_test.value_counts(normalize=True)}) # TS print('Total alerts in training set: ' + str(TS_y_train.sum())) print('Total alerts in test set: ' + str(TS_y_test.sum())) pd.DataFrame({'train' : TS_y_train.value_counts(normalize=True), 'test' : TS_y_test.value_counts(normalize=True)}) # RexT print('Total alerts in training set: ' + str(RexT_y_train.sum())) print('Total alerts in test set: ' + str(RexT_y_test.sum())) pd.DataFrame({'train' : RexT_y_train.value_counts(normalize=True), 'test' : RexT_y_test.value_counts(normalize=True)}) ###Output Total alerts in training set: 9.0 Total alerts in test set: 13.0 ###Markdown Ridge Classifier without Differences ###Code %%capture # ^ don't print errors about precision, recall, F1-score being 0 from sklearn.linear_model import RidgeClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer, f1_score, precision_score, recall_score, fbeta_score, zero_one_loss ridge = RidgeClassifier(normalize=False, random_state=42) parameters = {'alpha':[0.1, 0.5, 1, 5], 'fit_intercept' : [True, False], 'class_weight' : ['balanced', None]} scoring = {'auc': 'roc_auc', # only reports on alerts flagged 'precision_binary' : make_scorer(precision_score, average='binary'), # global count of everything like confusion matrix 'precision_micro' : make_scorer(precision_score, average='micro'), # same as macro but with a weighted average to account for imbalance of the classes 'precision_weighted' : make_scorer(precision_score, average='weighted'), 'recall_weighted' : make_scorer(recall_score, average='weighted'), 'recall_binary' : make_scorer(recall_score, average='binary'), 'recall_micro' : make_scorer(recall_score, average='micro'), 'f1_score_weighted' : make_scorer(f1_score, average='weighted'), 'f1_score_binary' : make_scorer(f1_score, average='binary'), 'f1_score_micro' : make_scorer(f1_score, average='micro'), # emphasize recall more 'f2_score_weighted' : make_scorer(fbeta_score, beta=2, average='weighted'), 'f2_score_binary' : make_scorer(fbeta_score, beta=2, average='binary'), 'f2_score_micro' : make_scorer(fbeta_score, beta=2, average='micro'), # emphasize precision more 'f0.5_score_weighted' : make_scorer(fbeta_score, beta=0.5, average='weighted'), 'f0.5_score_binary' : make_scorer(fbeta_score, beta=0.5, average='binary'), 'f0.5_score_micro' : make_scorer(fbeta_score, beta=0.5, average='micro'), # percent of misclassifications 'zero_one_loss_normalized' : make_scorer(zero_one_loss, greater_is_better=False), # number of misclassifications 'zero_one_loss_count' : make_scorer(zero_one_loss, greater_is_better=False, normalize=False), 'accuracy' : 'accuracy'} # pick '_weighted' if you want to be right on each class proportionally # ('macro' isn't really appropriate due to the class imbalance) # pick '_binary' if you want to perform best on the alert class # pick '_micro' to count globally all TP, FP, TN, FN (like confusion matrix) # so for our purposes 'f1_score' with one of the above is likely to be the best refit_AS = 'precision_micro' refit_TS = 'precision_micro' refit_RexT = 'auc' AS_ridge_grid = GridSearchCV(estimator=ridge, param_grid=parameters, scoring=scoring, refit=refit_AS, return_train_score=True) TS_ridge_grid = GridSearchCV(estimator=ridge, param_grid=parameters, scoring=scoring, refit=refit_TS, return_train_score=True) RexT_ridge_grid = GridSearchCV(estimator=ridge, param_grid=parameters, scoring=scoring, refit=refit_RexT, return_train_score=True) # fit the models to find the best version AS_ridge_model = AS_ridge_grid.fit(AS_X_train, AS_y_train) TS_ridge_model = TS_ridge_grid.fit(TS_X_train, TS_y_train) RexT_ridge_model = RexT_ridge_grid.fit(RexT_X_train, RexT_y_train) ###Output _____no_output_____ ###Markdown Best Models AS ###Code print(AS_ridge_model.best_estimator_) print(refit_AS + ' (Mean cross-validated score of the best_estimator): ' + \ str(AS_ridge_model.best_score_)) for col, coef in zip(AS_X_train.columns, AS_ridge_model.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=1, class_weight=None, copy_X=True, fit_intercept=False, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) precision_micro (Mean cross-validated score of the best_estimator): 0.7950985346134412 is_campaign 0.06 time_delta_01 0.1 time_delta_02 0.04 time_delta_03 0.02 time_delta_04 0.0 time_delta_05 0.0 time_delta_06 0.03 time_delta_07 -0.01 time_delta_08 -0.01 time_delta_09 0.0 time_delta_10 0.0 time_delta_11 0.0 time_delta_12 0.03 time_delta_13 0.01 time_delta_14 -0.02 time_delta_15 0.0 time_delta_16 -0.01 time_delta_17 -0.0 time_delta_18 0.02 time_delta_19 -0.0 time_delta_20 -0.01 time_delta_21 -0.01 time_delta_22 0.01 time_delta_23 -0.01 time_delta_24 -0.01 time_delta_25 -0.0 kpi_clicks -0.51 kpi_client_rext -0.64 kpi_conversions -0.66 kpi_cos -0.64 kpi_cr -0.68 kpi_ctr -0.81 kpi_displays -0.5 kpi_margin -1.11 kpi_order_value -0.64 kpi_rext_euro -0.96 kpi_spend -0.54 kpi_tac -0.96 ###Markdown TS ###Code print(TS_ridge_model.best_estimator_) print(refit_TS + ' (Mean cross-validated score of the best_estimator): ' + \ str(TS_ridge_model.best_score_)) for col, coef in zip(TS_X_train.columns, TS_ridge_model.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=0.1, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) precision_micro (Mean cross-validated score of the best_estimator): 0.9198706431908013 time_delta_01 0.09 time_delta_02 0.02 time_delta_03 -0.01 time_delta_04 -0.05 time_delta_05 0.0 time_delta_06 0.01 time_delta_07 -0.0 time_delta_08 -0.02 time_delta_09 -0.02 time_delta_10 0.01 time_delta_11 0.01 time_delta_12 0.02 time_delta_13 0.0 time_delta_14 -0.01 time_delta_15 0.0 time_delta_16 0.02 time_delta_17 -0.0 time_delta_18 0.03 time_delta_19 0.03 time_delta_20 0.04 time_delta_21 -0.02 time_delta_22 -0.02 time_delta_23 0.01 time_delta_24 0.03 time_delta_25 0.0 site_type_SITE LEVEL 0.02 site_type_aa 0.02 site_type_aios -0.05 site_type_d -0.04 site_type_m 0.05 site_type_t -0.0 event_name_basket -0.03 event_name_homepage -0.03 event_name_listing 0.01 event_name_product -0.01 event_name_sales -0.04 event_name_search 0.09 ###Markdown RexT ###Code print(RexT_ridge_model.best_estimator_) print(refit_RexT + ' (Mean cross-validated score of the best_estimator): ' + \ str(RexT_ridge_model.best_score_)) for col, coef in zip(RexT_X_train.columns, RexT_ridge_model.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=0.5, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) auc (Mean cross-validated score of the best_estimator): 0.937037037037037 time_delta_01 0.66 time_delta_02 -0.4 time_delta_03 0.01 time_delta_04 -0.07 time_delta_05 0.02 time_delta_06 0.03 time_delta_07 0.04 time_delta_08 -0.05 time_delta_09 -0.04 time_delta_10 -0.12 time_delta_11 0.07 time_delta_12 0.02 time_delta_13 0.07 time_delta_14 -0.17 time_delta_15 0.03 time_delta_16 -0.03 time_delta_17 0.15 time_delta_18 -0.11 time_delta_19 -0.07 time_delta_20 -0.09 time_delta_21 0.09 time_delta_22 -0.04 time_delta_23 0.09 time_delta_24 -0.16 time_delta_25 0.03 time_delta_26 0.24 time_delta_27 -0.14 time_delta_28 -0.08 time_delta_29 -0.06 time_delta_30 0.08 ###Markdown Model Evaluation ROC Curve ###Code from sklearn.metrics import roc_curve, auc AS_y_prob_fit = AS_ridge_model.decision_function(AS_X_test) TS_y_prob_fit = TS_ridge_model.decision_function(TS_X_test) RexT_y_prob_fit = RexT_ridge_model.decision_function(RexT_X_test) AS_ridge_roc_curve = roc_curve(AS_y_test, AS_y_prob_fit, pos_label=1) # returns tuple: fpr, tpr, thresholds AS_ridge_roc_curve_AUC = auc(AS_ridge_roc_curve[0], AS_ridge_roc_curve[1]) # needs fpr, tpr TS_ridge_roc_curve = roc_curve(TS_y_test, TS_y_prob_fit, pos_label=1) TS_ridge_roc_curve_AUC = auc(TS_ridge_roc_curve[0], TS_ridge_roc_curve[1]) RexT_ridge_roc_curve = roc_curve(RexT_y_test, RexT_y_prob_fit, pos_label=1) RexT_ridge_roc_curve_AUC = auc(RexT_ridge_roc_curve[0], RexT_ridge_roc_curve[1]) # ROC Curve without 1 period differences utils.model_roc_curves(roc_data_dict={'AS' : AS_ridge_roc_curve, 'TS' : TS_ridge_roc_curve, 'RexT' : RexT_ridge_roc_curve}, auc_dict={'AS' : AS_ridge_roc_curve_AUC, 'TS' : TS_ridge_roc_curve_AUC, 'RexT' : RexT_ridge_roc_curve_AUC}, method_name='Ridge Classifier') ###Output _____no_output_____ ###Markdown Confusion Matrix ###Code AS_threshold = 0.001 utils.confusion_matrix_visual(AS_y_test[AS_X_test.is_campaign == 0], AS_ridge_model.decision_function(AS_X_test[AS_X_test.is_campaign == 0]) \ >= AS_threshold, 'AS Client-level') utils.confusion_matrix_visual(AS_y_test[AS_X_test.is_campaign == 1], AS_ridge_model.decision_function(AS_X_test[AS_X_test.is_campaign == 1]) \ >= AS_threshold, 'AS Campaign-level') utils.confusion_matrix_visual(AS_y_test, AS_ridge_model.decision_function(AS_X_test) \ >= AS_threshold, 'AS Overall') TS_threshold = 0.0000001 utils.confusion_matrix_visual(TS_y_test, TS_ridge_model.decision_function(TS_X_test) \ >= TS_threshold, 'TS') RexT_threshold = 0.000000001 utils.confusion_matrix_visual(RexT_y_test, RexT_ridge_model.decision_function(RexT_X_test) \ >= RexT_threshold, 'RexT') ###Output TP to FP ratio: 2.0 ###Markdown On disqualified data. ###Code utils.confusion_matrix_visual(disqualified_AS['min_max']['is_alert'], AS_ridge_model.decision_function(disqualified_AS['min_max'].\ drop([col for col in disqualified_AS['min_max'].columns if 'diff' in col or col in ['run_date', 'series', 'is_alert']], axis=1)) \ >= AS_threshold, 'AS Overall') disqualified_TS['min_max']['time_delta_24'], disqualified_TS['min_max']['time_delta_25'] = (0,0) disqualified_TS['min_max']['site_type_SITE LEVEL'], disqualified_TS['min_max']['site_type_aios'] = (0,0) utils.confusion_matrix_visual(disqualified_TS['min_max']['is_alert'], TS_ridge_model.decision_function(disqualified_TS['min_max'].\ drop([col for col in disqualified_TS['min_max'].columns if 'diff' in col or col in ['run_date', 'series', 'is_alert']], axis=1)) \ >= TS_threshold, 'TS') ###Output TP to FP ratio: nan ###Markdown Metrics ###Code utils.classification_report_all(y_test_dict={'AS' : AS_y_test, 'TS' : TS_y_test, 'RexT' : RexT_y_test}, y_pred_dict={'AS' : AS_ridge_model.decision_function(AS_X_test) >= \ AS_threshold, 'TS' : TS_ridge_model.decision_function(TS_X_test) >= \ TS_threshold, 'RexT' : RexT_ridge_model.decision_function(RexT_X_test) >= \ RexT_threshold}) ###Output AS results precision recall f1-score support False 0.80 1.00 0.89 775 True 0.86 0.08 0.15 215 avg / total 0.81 0.80 0.73 990 Percent misclassified: 20.2% Count misclassified: 200 ------------------------------------------------------ TS results precision recall f1-score support False 0.92 1.00 0.96 638 True 0.50 0.02 0.03 58 avg / total 0.88 0.92 0.88 696 Percent misclassified: 8.33% Count misclassified: 58 ------------------------------------------------------ RexT results precision recall f1-score support False 0.89 0.99 0.93 86 True 0.67 0.15 0.25 13 avg / total 0.86 0.88 0.84 99 Percent misclassified: 12.12% Count misclassified: 12 ###Markdown Logistic Regression with Differences ###Code %%capture # ^ don't print errors about precision, recall, F1-score being 0 from sklearn.linear_model import RidgeClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer, f1_score, precision_score, recall_score, fbeta_score, zero_one_loss ridge_diff = RidgeClassifier(normalize=False, random_state=42) parameters = {'alpha':[0.1, 0.5, 1, 5], 'fit_intercept' : [True, False], 'class_weight' : ['balanced', None]} scoring = {'auc': 'roc_auc', 'precision_binary' : make_scorer(precision_score, average='binary'), 'precision_micro' : make_scorer(precision_score, average='micro'), 'precision_weighted' : make_scorer(precision_score, average='weighted'), 'recall_weighted' : make_scorer(recall_score, average='weighted'), 'recall_binary' : make_scorer(recall_score, average='binary'), 'recall_micro' : make_scorer(recall_score, average='micro'), 'f1_score_weighted' : make_scorer(f1_score, average='weighted'), 'f1_score_binary' : make_scorer(f1_score, average='binary'), 'f1_score_micro' : make_scorer(f1_score, average='micro'), 'f2_score_weighted' : make_scorer(fbeta_score, beta=2, average='weighted'), 'f2_score_binary' : make_scorer(fbeta_score, beta=2, average='binary'), 'f2_score_micro' : make_scorer(fbeta_score, beta=2, average='micro'), 'f0.5_score_weighted' : make_scorer(fbeta_score, beta=0.5, average='weighted'), 'f0.5_score_binary' : make_scorer(fbeta_score, beta=0.5, average='binary'), 'f0.5_score_micro' : make_scorer(fbeta_score, beta=0.5, average='micro'), 'zero_one_loss_normalized' : make_scorer(zero_one_loss, greater_is_better=False), 'zero_one_loss_count' : make_scorer(zero_one_loss, greater_is_better=False, normalize=False), 'accuracy' : 'accuracy'} # pick '_weighted' if you want to be right on each class proportionally # ('macro' isn't really appropriate due to the class imbalance) # pick '_binary' if you want to perform best on the alert class # pick '_micro' to count globally all TP, FP, TN, FN (like confusion matrix) # so for our purposes 'f1_score' with one of the above is likely to be the best refit_AS = 'precision_weighted' refit_TS = 'precision_micro' refit_RexT = 'auc' AS_ridge_diff_grid = GridSearchCV(estimator=ridge_diff, param_grid=parameters, scoring=scoring, refit=refit_AS, return_train_score=True) TS_ridge_diff_grid = GridSearchCV(estimator=ridge_diff, param_grid=parameters, scoring=scoring, refit=refit_TS, return_train_score=True) RexT_ridge_diff_grid = GridSearchCV(estimator=ridge_diff, param_grid=parameters, scoring=scoring, refit=refit_RexT, return_train_score=True) # fit the models to find the best version AS_ridge_model_diff = AS_ridge_diff_grid.fit(AS_X_train_diff, AS_y_train_diff) TS_ridge_model_diff = TS_ridge_diff_grid.fit(TS_X_train_diff, TS_y_train_diff) RexT_ridge_model_diff = RexT_ridge_diff_grid.fit(RexT_X_train_diff, RexT_y_train_diff) ###Output _____no_output_____ ###Markdown Best Models AS ###Code print(AS_ridge_model_diff.best_estimator_) print(refit_AS + ' (Mean cross-validated score of the best_estimator): ' + \ str(AS_ridge_model_diff.best_score_)) for col, coef in zip(AS_X_train_diff.columns, AS_ridge_model_diff.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=0.1, class_weight='balanced', copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) precision_weighted (Mean cross-validated score of the best_estimator): 0.7681255474122398 is_campaign 0.12 time_delta_01 0.1 time_delta_02 0.07 time_delta_03 0.03 time_delta_04 0.02 time_delta_05 0.01 time_delta_06 0.04 time_delta_07 0.0 time_delta_08 0.0 time_delta_09 -0.02 time_delta_10 0.02 time_delta_11 -0.01 time_delta_12 0.05 time_delta_13 -0.02 time_delta_14 0.01 time_delta_15 0.01 time_delta_16 -0.03 time_delta_17 -0.05 time_delta_18 0.09 time_delta_19 -0.02 time_delta_20 -0.04 time_delta_21 0.01 time_delta_22 0.05 time_delta_23 -0.02 time_delta_24 -0.05 time_delta_25 0.04 kpi_clicks 0.29 kpi_client_rext 0.14 kpi_conversions 0.13 kpi_cos 0.13 kpi_cr 0.06 kpi_ctr -0.09 kpi_displays 0.3 kpi_margin -0.65 kpi_order_value 0.12 kpi_rext_euro -0.33 kpi_spend 0.24 kpi_tac -0.33 time_delta_diff_24 0.18 time_delta_diff_23 -0.04 time_delta_diff_22 -0.05 time_delta_diff_21 0.07 time_delta_diff_20 0.13 time_delta_diff_19 0.02 time_delta_diff_18 -0.06 time_delta_diff_17 0.13 time_delta_diff_16 -0.02 time_delta_diff_15 -0.03 time_delta_diff_14 -0.03 time_delta_diff_13 0.12 time_delta_diff_12 -0.01 time_delta_diff_11 0.03 time_delta_diff_10 -0.05 time_delta_diff_09 0.02 time_delta_diff_08 -0.05 time_delta_diff_07 -0.03 time_delta_diff_06 -0.01 time_delta_diff_05 0.01 time_delta_diff_04 -0.04 time_delta_diff_03 -0.01 time_delta_diff_02 0.01 time_delta_diff_01 -0.0 ###Markdown TS ###Code print(TS_ridge_model_diff.best_estimator_) print(refit_TS + ' (Mean cross-validated score of the best_estimator): ' + \ str(TS_ridge_model_diff.best_score_)) for col, coef in zip(TS_X_train_diff.columns, TS_ridge_model_diff.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=0.1, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) precision_micro (Mean cross-validated score of the best_estimator): 0.9191519942508085 time_delta_01 0.08 time_delta_02 0.04 time_delta_03 -0.01 time_delta_04 0.0 time_delta_05 -0.07 time_delta_06 -0.03 time_delta_07 0.07 time_delta_08 -0.04 time_delta_09 -0.08 time_delta_10 0.04 time_delta_11 -0.07 time_delta_12 0.09 time_delta_13 0.01 time_delta_14 -0.01 time_delta_15 -0.05 time_delta_16 0.05 time_delta_17 -0.01 time_delta_18 0.0 time_delta_19 -0.01 time_delta_20 0.02 time_delta_21 0.01 time_delta_22 0.02 time_delta_23 0.01 time_delta_24 0.06 time_delta_25 -0.04 site_type_SITE LEVEL 0.03 site_type_aa 0.01 site_type_aios -0.05 site_type_d -0.03 site_type_m 0.05 site_type_t 0.0 event_name_basket -0.03 event_name_homepage -0.03 event_name_listing 0.01 event_name_product -0.02 event_name_sales -0.04 event_name_search 0.09 time_delta_diff_24 -0.07 time_delta_diff_23 -0.01 time_delta_diff_22 -0.02 time_delta_diff_21 0.06 time_delta_diff_20 0.11 time_delta_diff_19 0.08 time_delta_diff_18 0.03 time_delta_diff_17 0.01 time_delta_diff_16 -0.0 time_delta_diff_15 0.07 time_delta_diff_14 -0.03 time_delta_diff_13 -0.02 time_delta_diff_12 -0.0 time_delta_diff_11 0.12 time_delta_diff_10 -0.0 time_delta_diff_09 0.05 time_delta_diff_08 -0.06 time_delta_diff_07 -0.09 time_delta_diff_06 0.05 time_delta_diff_05 -0.02 time_delta_diff_04 -0.12 time_delta_diff_03 -0.03 time_delta_diff_02 -0.03 time_delta_diff_01 0.01 ###Markdown RexT ###Code print(RexT_ridge_model_diff.best_estimator_) print(refit_RexT + ' (Mean cross-validated score of the best_estimator): ' + \ str(RexT_ridge_model_diff.best_score_)) for col, coef in zip(RexT_X_train_diff.columns, RexT_ridge_model_diff.best_estimator_.coef_[0]): print(col + '\t' + str(round(coef, 2))) ###Output RidgeClassifier(alpha=5, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=42, solver='auto', tol=0.001) auc (Mean cross-validated score of the best_estimator): 0.9370370370370369 time_delta_01 0.28 time_delta_02 -0.02 time_delta_03 0.08 time_delta_04 -0.07 time_delta_05 0.01 time_delta_06 -0.02 time_delta_07 -0.01 time_delta_08 -0.03 time_delta_09 -0.02 time_delta_10 -0.07 time_delta_11 0.04 time_delta_12 -0.02 time_delta_13 0.01 time_delta_14 -0.06 time_delta_15 -0.01 time_delta_16 0.04 time_delta_17 0.01 time_delta_18 -0.08 time_delta_19 0.01 time_delta_20 -0.05 time_delta_21 0.03 time_delta_22 0.01 time_delta_23 -0.01 time_delta_24 -0.04 time_delta_25 -0.02 time_delta_26 0.07 time_delta_27 -0.01 time_delta_28 -0.02 time_delta_29 -0.05 time_delta_30 0.01 time_delta_diff_29 -0.05 time_delta_diff_28 -0.05 time_delta_diff_27 -0.04 time_delta_diff_26 0.07 time_delta_diff_25 -0.01 time_delta_diff_24 -0.09 time_delta_diff_23 0.06 time_delta_diff_22 -0.1 time_delta_diff_21 0.02 time_delta_diff_20 0.01 time_delta_diff_19 -0.04 time_delta_diff_18 0.1 time_delta_diff_17 0.06 time_delta_diff_16 -0.05 time_delta_diff_15 0.03 time_delta_diff_14 -0.03 time_delta_diff_13 0.07 time_delta_diff_12 0.02 time_delta_diff_11 -0.01 time_delta_diff_10 -0.05 time_delta_diff_09 -0.0 time_delta_diff_08 -0.02 time_delta_diff_07 -0.01 time_delta_diff_06 0.05 time_delta_diff_05 -0.08 time_delta_diff_04 -0.1 time_delta_diff_03 -0.08 time_delta_diff_02 -0.03 time_delta_diff_01 0.32 ###Markdown Model Evaluation ROC Curve ###Code from sklearn.metrics import roc_curve, auc AS_y_prob_fit_diff = AS_ridge_model_diff.decision_function(AS_X_test_diff) TS_y_prob_fit_diff = TS_ridge_model_diff.decision_function(TS_X_test_diff) RexT_y_prob_fit_diff = RexT_ridge_model_diff.decision_function(RexT_X_test_diff) AS_ridge_roc_curve_diff = roc_curve(AS_y_test_diff, AS_y_prob_fit_diff, pos_label=1) AS_ridge_roc_curve_AUC_diff = auc(AS_ridge_roc_curve_diff[0], AS_ridge_roc_curve_diff[1]) # needs fpr, tpr TS_ridge_roc_curve_diff = roc_curve(TS_y_test_diff, TS_y_prob_fit_diff, pos_label=1) TS_ridge_roc_curve_AUC_diff = auc(TS_ridge_roc_curve_diff[0], TS_ridge_roc_curve_diff[1]) RexT_ridge_roc_curve_diff = roc_curve(RexT_y_test_diff, RexT_y_prob_fit_diff, pos_label=1) RexT_ridge_roc_curve_AUC_diff = auc(RexT_ridge_roc_curve_diff[0], RexT_ridge_roc_curve_diff[1]) # ROC Curve utils.model_roc_curves(roc_data_dict={'AS' : AS_ridge_roc_curve_diff, 'TS' : TS_ridge_roc_curve_diff, 'RexT' : RexT_ridge_roc_curve_diff}, auc_dict={'AS' : AS_ridge_roc_curve_AUC_diff, 'TS' : TS_ridge_roc_curve_AUC_diff, 'RexT' : RexT_ridge_roc_curve_AUC_diff}, method_name='Ridge Classifier with Differences') ###Output _____no_output_____ ###Markdown Confusion Matrix ###Code AS_threshold = 0.4 utils.confusion_matrix_visual(AS_y_test_diff[AS_X_test_diff.is_campaign == 0], AS_ridge_model_diff.decision_function(AS_X_test_diff[AS_X_test_diff.is_campaign == 0]) \ >= AS_threshold, 'AS Client-level') utils.confusion_matrix_visual(AS_y_test_diff[AS_X_test_diff.is_campaign == 1], AS_ridge_model_diff.decision_function(AS_X_test_diff[AS_X_test_diff.is_campaign == 1]) \ >= AS_threshold, 'AS Campaign-level') utils.confusion_matrix_visual(AS_y_test_diff[AS_X_test_diff.is_campaign == 1], AS_ridge_model_diff.decision_function(AS_X_test_diff[AS_X_test_diff.is_campaign == 1]) \ >= AS_threshold, 'AS Overall') TS_threshold = 0.001 utils.confusion_matrix_visual(TS_y_test_diff, TS_ridge_model_diff.decision_function(TS_X_test_diff) \ >= TS_threshold, 'TS') RexT_threshold = 0.01 utils.confusion_matrix_visual(RexT_y_test_diff, RexT_ridge_model_diff.decision_function(RexT_X_test_diff) \ >= RexT_threshold, 'RexT') ###Output TP to FP ratio: inf ###Markdown On disqualified data. ###Code utils.confusion_matrix_visual(disqualified_AS['min_max']['is_alert'], AS_ridge_model_diff.decision_function(disqualified_AS['min_max'].\ drop([col for col in disqualified_AS['min_max'].columns if col in ['run_date', 'series', 'is_alert']], axis=1)) \ >= AS_threshold, 'AS Overall') utils.confusion_matrix_visual(disqualified_TS['min_max']['is_alert'], TS_ridge_model_diff.decision_function(disqualified_TS['min_max'].\ drop([col for col in disqualified_TS['min_max'].columns if col in ['run_date', 'series', 'is_alert']], axis=1)) \ >= TS_threshold, 'TS') ###Output TP to FP ratio: 0.0 ###Markdown Metrics ###Code utils.classification_report_all(y_test_dict={'AS' : AS_y_test_diff, 'TS' : TS_y_test_diff, 'RexT' : RexT_y_test_diff}, y_pred_dict={'AS' : AS_ridge_model_diff.decision_function(AS_X_test_diff) >= \ AS_threshold, 'TS' : TS_ridge_model_diff.decision_function(TS_X_test_diff) >= \ TS_threshold, 'RexT' : RexT_ridge_model_diff.decision_function(RexT_X_test_diff) >= \ RexT_threshold}) ###Output AS results precision recall f1-score support False 0.82 0.94 0.88 775 True 0.54 0.25 0.34 215 avg / total 0.76 0.79 0.76 990 Percent misclassified: 20.91% Count misclassified: 207 ------------------------------------------------------ TS results precision recall f1-score support False 0.92 1.00 0.96 638 True 0.67 0.03 0.07 58 avg / total 0.90 0.92 0.88 696 Percent misclassified: 8.19% Count misclassified: 57 ------------------------------------------------------ RexT results precision recall f1-score support False 0.89 1.00 0.94 86 True 1.00 0.15 0.27 13 avg / total 0.90 0.89 0.85 99 Percent misclassified: 11.11% Count misclassified: 11
notebooks/sklearn-mnist-viz.ipynb
###Markdown MNIST handwritten digits visualization with scikit-learnIn this notebook, we'll use some popular visualization techniques to visualize MNIST digits. This notebook is based on the scikit-learn embedding examples found [here](http://scikit-learn.org/stable/auto_examples/manifold/plot_lle_digits.html).First, the needed imports. ###Code %matplotlib inline from time import time from pml_utils import get_mnist import numpy as np import sklearn from sklearn import random_projection, decomposition, manifold, __version__ import matplotlib.pyplot as plt from distutils.version import LooseVersion as LV assert(LV(__version__) >= LV("0.20")), "Version >= 0.20 of sklearn is required." ###Output _____no_output_____ ###Markdown Then we load the MNIST data. First time it downloads the data, which can take a while.In this notebook, we only use 1024 first samples of the training data. This reduces the time needed to calculate the visualizations and makes the visualizations appear less crowded. ###Code X_train, y_train, X_test, y_test = get_mnist('MNIST') # Let's inspect only 1024 first training samples in this notebook X = X_train[:1024] y = y_train[:1024] print() print('MNIST data loaded:') print('X:', X.shape) print('y:', y.shape) ###Output _____no_output_____ ###Markdown Let's start by inspecting our data. For such a small dataset, we can actually draw all the samples at once: ###Code n_img_per_row = 32 # 32*32=1024 img = np.zeros((28 * n_img_per_row, 28 * n_img_per_row)) for i in range(n_img_per_row): ix = 28 * i for j in range(n_img_per_row): iy = 28 * j img[ix:ix + 28, iy:iy + 28] = X[i * n_img_per_row + j,:].reshape(28,28) img = np.max(img)-img plt.figure(figsize=(9, 9)) plt.imshow(img, cmap='gray') plt.title('1024 first MNIST digits') ax=plt.axis('off') ###Output _____no_output_____ ###Markdown Let's define a helper function to plot the different visualizations: ###Code def plot_embedding(X, title=None, time=None, show_digits=True): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure(figsize=(9,6)) plt.axis('off') if show_digits: for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Set1(int(y[i]) / 10.), fontdict={'weight': 'bold', 'size': 9}) else: s = plt.scatter(X[:, 0], X[:, 1], color=[plt.cm.Set1(int(yi) / 10.) for yi in y]) if title is not None: if t0 is not None: plt.title("%s (%.2fs)" % (title, time)) else: plt.title(title) ###Output _____no_output_____ ###Markdown 1. Random projectionA simple first visualization is a [random projection](http://scikit-learn.org/stable/modules/random_projection.htmlrandom-projection) of the data into two dimensions. ###Code t0 = time() rp = random_projection.SparseRandomProjection(n_components=2, random_state=42) X_projected = rp.fit_transform(X) t = time() - t0 plot_embedding(X_projected, "Random projection", t) ###Output _____no_output_____ ###Markdown The data can also be plotted with points instead of digit labels by setting `show_digits=False`: ###Code plot_embedding(X_projected, "Random projection", t, show_digits=False) ###Output _____no_output_____ ###Markdown 2. PCA[Principal component analysis](http://scikit-learn.org/stable/modules/decomposition.htmlpca) (PCA) is a standard method to decompose a high-dimensional dataset in a set of successive orthogonal components that explain a maximum amount of the variance. Here we project the data into two first principal components. The components have the maximal possible variance under the orthogonality constraint. ###Code t0 = time() pca = decomposition.PCA(n_components=2) X_pca = pca.fit_transform(X) t = time() - t0 plot_embedding(X_pca, "PCA projection", t) ###Output _____no_output_____ ###Markdown 3. MDS[Multidimensional scaling](http://scikit-learn.org/stable/modules/manifold.htmlmultidimensional-scaling) (MDS) seeks a low-dimensional representation of the data in which the distances try to respect the distances in the original high-dimensional space. ###Code t0 = time() mds = manifold.MDS(n_components=2, max_iter=500) X_mds = mds.fit_transform(X) t = time() - t0 plot_embedding(X_mds, "MDS embedding", t) ###Output _____no_output_____ ###Markdown 4. t-SNE[t-distributed Stochastic Neighbor Embedding](http://scikit-learn.org/stable/modules/manifold.htmlt-sne) (t-SNE) is a relatively new and popular tool to visualize high-dimensional data. t-SNE is particularly sensitive to local structure and can often reveal clusters in the data.t-SNE has an important tuneable parameter called `perplexity`, that can have a large effect on the resulting visualization, depending on the data. Typical values for perplexity are between 5 and 50. ###Code t0 = time() perplexity=30 tsne = manifold.TSNE(n_components=2, perplexity=perplexity) X_tsne = tsne.fit_transform(X) t = time() - t0 plot_embedding(X_tsne, "t-SNE embedding with perplexity=%d" % perplexity, t) ###Output _____no_output_____ ###Markdown 5. UMAP[Uniform Manifold Approximation and Projection](https://umap-learn.readthedocs.io/en/latest/index.html) (UMAP) is another recently published technique for data visualization and dimensionality reduction based on manifold learning and topological data analysis.UMAP is not included in scikit-learn but is available in PyPi as umap-learn. If not readily available, it can be installed with pip. ###Code # Uncomment (remove the "#") the next line to install: #!pip install umap-learn import umap ###Output _____no_output_____ ###Markdown The main hyperparameters of UMAP include `n_neighbors` and `min_dist`, which control the the size of the local neighborhood considered and how tightly the algorithm packs neighboring points together, respectively. The values of both hyperparameters have a significant impact on the resulting visualization. ###Code t0 = time() n_neighbors = 15 min_dist = 0.1 umapmodel = umap.UMAP(n_neighbors=n_neighbors, min_dist=min_dist) X_umap = umapmodel.fit_transform(X) t = time() - t0 plot_embedding(X_umap, "UMAP projection with n_neighbors=%d, min_dist=%.2f" % (n_neighbors, min_dist), t) ###Output _____no_output_____
docs/notebooks/round_trip_tear_sheet_example.ipynb
###Markdown Round Trip Tear Sheet Example When evaluating the performance of an investing strategy, it is helpful to quantify the frequency, duration, and profitability of its independent bets, or "round trip" trades. A round trip trade is started when a new long or short position is opened and then later completely or partially closed out.The intent of the round trip tearsheet is to help differentiate strategies that profited off a few lucky trades from strategies that profited repeatedly from genuine alpha. Breaking down round trip profitability by traded name and sector can also help inform universe selection and identify exposure risks. For example, even if your equity curve looks robust, if only two securities in your universe of fifteen names contributed to overall profitability, you may have reason to question the logic of your strategy.To identify round trips, pyfolio reconstructs the complete portfolio based on the transactions that you pass in. When you make a trade, pyfolio checks if shares are already present in your portfolio purchased at a certain price. If there are, we compute the PnL, returns and duration of that round trip trade. In calculating round trips, pyfolio will also append position closing transactions at the last timestamp in the positions data. This closing transaction will cause the PnL from any open positions to realized as completed round trips. ###Code import pyfolio as pf %matplotlib inline import gzip import os import pandas as pd # silence warnings import warnings warnings.filterwarnings('ignore') transactions = pd.read_csv(gzip.open('../tests/test_data/test_txn.csv.gz'), index_col=0, parse_dates=True) positions = pd.read_csv(gzip.open('../tests/test_data/test_pos.csv.gz'), index_col=0, parse_dates=True) returns = pd.read_csv(gzip.open('../tests/test_data/test_returns.csv.gz'), index_col=0, parse_dates=True, header=None)[1] # Optional: Sector mappings may be passed in as a dict or pd.Series. If a mapping is # provided, PnL from symbols with mappings will be summed to display profitability by sector. sect_map = {'COST': 'Consumer Goods', 'INTC':'Technology', 'CERN':'Healthcare', 'GPS':'Technology', 'MMM': 'Construction', 'DELL': 'Technology', 'AMD':'Technology'} ###Output _____no_output_____ ###Markdown The easiest way to run the analysis is to call `pyfolio.create_round_trip_tear_sheet()`. Passing in a sector map is optional. You can also pass `round_trips=True` to `pyfolio.create_full_tear_sheet()` to have this be created along all the other analyses. ###Code pf.create_round_trip_tear_sheet(returns, positions, transactions, sector_mappings=sect_map) ###Output _____no_output_____ ###Markdown Under the hood, several functions are being called. `extract_round_trips()` does the portfolio reconstruction and creates the round-trip trades. ###Code rts = pf.round_trips.extract_round_trips(transactions, portfolio_value=positions.sum(axis='columns') / (returns + 1)) rts.head() pf.round_trips.print_round_trip_stats(rts) ###Output _____no_output_____
Summer2020_Modules/module4_Kaleb_lesson.ipynb
###Markdown Intro to Image Processing: An Image as Numbers Purpose: To view an image from a computer's persepctive (as an array of numbers) Created by: Kaleb DeckerCreation Date: 7/30/2020 *Step 1: Necessary Imports* ###Code import numpy as np from skimage import io #importing a specific module from scikit-image import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown *Step 2: User Inputs* ###Code cell_im_location = r'C:\Users\Kaleb\Documents\GitHub\textile\example_data\ogd_cells.tif' ###Output _____no_output_____ ###Markdown *Step 3: Reading in the image* ###Code cell_im = io.imread(cell_im_location) ###Output _____no_output_____ ###Markdown *Step 4: Viewing the Image* ###Code cell_im cell_im.shape red_cell_im = cell_im[:,:,0] green_cell_im = cell_im[:,:,1] blue_cell_im = cell_im[:,:,2] red_cell_im blue_cell_im green_cell_im plt.imshow(cell_im) plt.imshow(red_cell_im, cmap='gray') fig, ax = plt.subplots(2,2) ax[0,0].imshow(red_cell_im, cmap = 'gray') ax[1,0].imshow(green_cell_im, cmap = 'gray') ax[0,1].imshow(blue_cell_im, cmap = 'gray') ax[1,1].imshow(cell_im) fig, ax = plt.subplots(2,2) ax[0,0].imshow(red_cell_im, cmap = 'gray') ax[0,0].get_xaxis().set_visible(False) ax[0,0].get_yaxis().set_visible(False) ax[0,0].set_title('Red Channel - PI') ax[1,0].imshow(green_cell_im, cmap = 'gray') ax[1,0].get_xaxis().set_visible(False) ax[1,0].get_yaxis().set_visible(False) ax[1,0].set_title('Green Channel - Iba1') ax[0,1].imshow(blue_cell_im, cmap = 'gray') ax[0,1].get_xaxis().set_visible(False) ax[0,1].get_yaxis().set_visible(False) ax[0,1].set_title('Blue Channel - Dapi') ax[1,1].imshow(cell_im) ax[1,1].get_xaxis().set_visible(False) ax[1,1].get_yaxis().set_visible(False) ax[1,1].set_title('All Channels') ###Output Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
ExamplePlot.ipynb
###Markdown This notebook allows to visualize a TSNE and PCA of the iris dataset Load data ###Code import numpy as np random_data = np.random.random(size=(50, 2)) ###Output _____no_output_____ ###Markdown Animation ###Code from transformation import Visualizer tv = Visualizer(random_data) tv.jupyter_visualize() tv.save_gif('images/random_ts.gif') ###Output _____no_output_____
2020/day08/main.ipynb
###Markdown Day 8: Handheld Haltinghttps://adventofcode.com/2020/day/8 Part 1 Op details (note to self)- `acc` increases or decreases a single global value called the accumulator by the value given in the argument. For example, `acc +7` would increase the accumulator by 7. The accumulator starts at 0. After an acc instruction, the instruction immediately below it is executed next.- `jmp` jumps to a new instruction relative to itself. The next instruction to execute is found using the argument as an offset from the jmp instruction; for example, `jmp +2` would skip the next instruction, `jmp +1` would continue to the instruction immediately below it, and `jmp -20` would cause the instruction 20 lines above to be executed next.- `nop` stands for **N**o **OP**eration - it does nothing. The instruction immediately below it is executed next. ###Code # Grab our data from pathlib import Path INPUTS = Path('input.txt').resolve().read_text().strip() instructions = [x.strip() for x in INPUTS.split('\n')] ###Output _____no_output_____ ###Markdown DetailsSo, we need to run consecutively through the commands, starting with `acc = 0`, and determine:1. the point at which any command is re-run; and2. what the value of `acc` is prior to that execution.Simple enough. We need to keep a running set of command lines that have been executed from the set of instructions, then continuously check if the current command index exists in that set. Meanwhile, we take the appropriate operation given the current command line instruction. ###Code def check_instructions(lines): curr = 0 accum = 0 seen = {curr} valid = True while True: accum_delta = 0 try: line = lines[curr] except IndexError: # We hit the end? break op, arg = line.split() if op == 'nop': delta = 1 elif op == 'acc': delta = 1 accum_delta = int(arg) elif op == 'jmp': delta = int(arg) if (curr + delta) in seen: valid = False break accum += accum_delta curr += delta seen.add(curr) return accum, valid accumulator, _ = check_instructions(instructions) print(f"Value of acc at the loop point: {accumulator}") ###Output Value of acc at the loop point: 2051 ###Markdown Part 2Similar to the first part, but this time need to determine what one instruction - either a `jmp` or `nop` - has to be swapped in order to generate a solution.I'll admit, I got stumped by this for a bit, then looked around for similar solutions made by others. Where it seems I got stuck was by initially assuming that the one instruction causing the loop in Part 1 was the same instruction that had to be swapped; but that's not necessarily true.Instead, we need to go through the code lines and swap `jmp`s to `nop`s and vice versa to test which set of full code lines can actually generate a good solution. ###Code for idx, line in enumerate(instructions): test_instructions = instructions[:] op, arg = line.split() # Do the op swap (doo, doo doo duh-doo duh-doo doo DOO!) if op == 'jmp': op = 'nop' elif op == 'nop': op = 'jmp' new_line = f"{op} {arg}" test_instructions[idx] = new_line accum, valid = check_instructions(test_instructions) if valid: break print(f"Valid accumulator is {accum}, with a swapped instruction at line {idx+1}") ###Output Valid accumulator is 2304, with a swapped instruction at line 322
Machine Learning/Query Optimization/notebooks/Appendix A - BM25 tuning.ipynb
###Markdown Appendix A: Tuning BM25 parameters for the MSMARCO Document datasetThe following shows a principled, data-driven approach to tuning BM25 parameters with a basic query, using the MSMARCO Document dataset. This assumes familiarity with basic query tuning as shown in the "Query tuning" notebooks.BM25 contains two parameters `k1` and `b`. Roughly speaking (very roughly), `k1` controls the amount of term saturation (at some point, more terms does not mean more relevant) and `b` controls the importance of document length. A deeper look into these parameters is beyond the scope of this notebook, but our [three part blog series on understanding BM25](https://www.elastic.co/blog/practical-bm25-part-1-how-shards-affect-relevance-scoring-in-elasticsearch) is very useful for that.Be aware that not all query types will see improvements with BM25 tuning. Sometimes it's more impactful to just tune query parameters. As always you try it out with your datasets first and get concrete measurements. We recommend customizing index settings/analyzers first, then do query parmeter tuning and get your baseline measurements. Next, try the best index settings/analyzers with BM25 tuning, then do query parameter tuning and see if it makes any improvement on your baseline. If there's no significant difference it's best to just stick with the default BM25 parameters for simplicty. ###Code %load_ext autoreload %autoreload 2 import importlib import os import sys from elasticsearch import Elasticsearch from skopt.plots import plot_objective # project library sys.path.insert(0, os.path.abspath('..')) import qopt importlib.reload(qopt) from qopt.notebooks import evaluate_mrr100_dev, optimize_bm25_mrr100 from qopt.optimize import Config, set_bm25_parameters # use a local Elasticsearch or Cloud instance (https://cloud.elastic.co/) es = Elasticsearch('http://localhost:9200') # set the parallelization parameter `max_concurrent_searches` for the Rank Evaluation API calls max_concurrent_searches = 10 index = 'msmarco-document' index_defaults = 'msmarco-document.defaults' template_id = 'combined_matches' # no query params query_params = {} # default Elasticsearch BM25 params default_bm25_params = {'k1': 1.2, 'b': 0.75} ###Output _____no_output_____ ###Markdown Baseline evaluationFor tuning the BM25 parameters, we're going to use just a `match` query per field, combined using a `bool` `should` query. This will search for query terms across the `url`, `title`, and `body` fields, and we'll be attempting to optimize the BM25 parameters that are used in the scoring function for each field. In theory, each field could have it's own BM25 [similarty](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-similarity.htmlbm25) and parameters, but we'll leave that as an exercise to the reader.Since BM25 parameters are actually index settings in Elasticsearch (they are theoretically query parameters, but they are implemented as index settings to be consistent with other similarity modules), we need to make sure to set the parameters before any evaluation step. At optimization time, we'lll do the same process: set the BM25 parameters to try, then run the rank evaluation API on the training query dataset. ###Code %%time set_bm25_parameters(es, index, **default_bm25_params) _ = evaluate_mrr100_dev(es, max_concurrent_searches, index, template_id, query_params) ###Output Evaluation with: MRR@100 Score: 0.2504 CPU times: user 1.8 s, sys: 436 ms, total: 2.23 s Wall time: 57.4 s ###Markdown That's the same baseline that we've seen in the "Query tuning" notebook, so we know we're setup correctly. OptimizationNow we're ready to run the optimization procedure and see if we can improve on that, while holding the default query parameters constant.We know that there's [roughly a standard range](https://www.elastic.co/blog/practical-bm25-part-3-considerations-for-picking-b-and-k1-in-elasticsearch) for each parameter, so we use those. We also set internally before running the optimization some static initial points to try, based on some well-known default parameter values: * Elasticsearch defaults: `k1`: `1.2`, `b`: `0.75` * Anserini [1] defaults: `k1`: `0.9`, `b`: `0.4` [1] [anserini](https://github.com/castorini/anserini) is a commonly used tool in academia for research into search systems ###Code %%time _, best_params, _, metadata = optimize_bm25_mrr100(es, max_concurrent_searches, index, template_id, query_params, config_space=Config.parse({ 'method': 'bayesian', 'num_iterations': 40, 'num_initial_points': 20, 'space': { 'k1': { 'low': 0.5, 'high': 5.0 }, 'b': { 'low': 0.3, 'high': 1.0 }, } })) ###Output Optimizing parameters - metric: MRR@100 - queries: data/msmarco-document-sampled-queries.1000.tsv - queries: data/msmarco/document/msmarco-doctrain-qrels.tsv - iteration 2 scored 0.2188 with: {'k1': 0.9, 'b': 0.4} - iteration 3 scored 0.2353 with: {'k1': 3.370604288950908, 'b': 0.6502501160664012} - iteration 4 scored 0.2350 with: {'k1': 4.019769356834095, 'b': 0.6559624038852268} - iteration 5 scored 0.2183 with: {'k1': 4.550172007175469, 'b': 0.36646469797122216} - iteration 6 scored 0.2197 with: {'k1': 4.510703804651055, 'b': 0.9990275259776924} - iteration 7 scored 0.2235 with: {'k1': 1.2557048044556212, 'b': 0.5681787231476463} - iteration 8 scored 0.2218 with: {'k1': 0.9492476027695534, 'b': 0.7428739712003931} - iteration 9 scored 0.2255 with: {'k1': 1.3366685724014589, 'b': 0.5938330471247484} - iteration 10 scored 0.2330 with: {'k1': 4.309783310447555, 'b': 0.7759034485189735} - iteration 11 scored 0.2195 with: {'k1': 1.5781739190991968, 'b': 0.3015016529905641} - iteration 12 scored 0.2347 with: {'k1': 2.321429376689379, 'b': 0.6884699589963544} - iteration 13 scored 0.2134 with: {'k1': 3.2448226638738626, 'b': 0.9900046900427262} - iteration 14 scored 0.2206 with: {'k1': 1.2433964265691286, 'b': 0.44356562662805726} - iteration 15 scored 0.2156 with: {'k1': 3.100612400611909, 'b': 0.9849404289368413} - iteration 16 scored 0.2257 with: {'k1': 4.248042138475732, 'b': 0.9035284880309848} - iteration 17 scored 0.2224 with: {'k1': 1.5765807997258139, 'b': 0.8720332943348184} - iteration 18 scored 0.2305 with: {'k1': 2.820111431030238, 'b': 0.5168856770938441} - iteration 19 scored 0.2224 with: {'k1': 2.1959597161860107, 'b': 0.9250145634446965} - iteration 20 scored 0.2257 with: {'k1': 4.442190681266682, 'b': 0.9260152008360161} - iteration 21 scored 0.2242 with: {'k1': 3.064655836349819, 'b': 0.3791113353101573} - iteration 22 scored 0.2187 with: {'k1': 3.5202769215682608, 'b': 0.9588940533178607} - iteration 23 scored 0.2325 with: {'k1': 5.0, 'b': 0.7043761223003595} - iteration 24 scored 0.2159 with: {'k1': 0.5095249433797535, 'b': 0.9952556818182101} - iteration 25 scored 0.2283 with: {'k1': 4.99733655784174, 'b': 0.5513516063009762} - iteration 26 scored 0.2353 with: {'k1': 3.0693561332209263, 'b': 0.7097705952925664} - iteration 27 scored 0.2302 with: {'k1': 4.997079968717751, 'b': 0.8338225591267308} - iteration 28 scored 0.2349 with: {'k1': 2.9298189101138057, 'b': 0.6705355989029556} - iteration 29 scored 0.2286 with: {'k1': 3.9017616725688504, 'b': 0.5275669866319284} - iteration 30 scored 0.2126 with: {'k1': 0.5083768089070996, 'b': 0.3051975488098463} - iteration 31 scored 0.2335 with: {'k1': 3.057438645555967, 'b': 0.7943805950296335} - iteration 32 scored 0.2356 with: {'k1': 3.4996216258157684, 'b': 0.7046625041391483} - iteration 33 scored 0.2130 with: {'k1': 4.988190005294321, 'b': 0.301967374589563} - iteration 34 scored 0.2157 with: {'k1': 0.511035678225668, 'b': 0.5863790923927636} - iteration 35 scored 0.2206 with: {'k1': 3.6684915070895987, 'b': 0.300110477096296} - iteration 36 scored 0.2205 with: {'k1': 4.989302876768119, 'b': 0.9832605278104865} - iteration 37 scored 0.2305 with: {'k1': 2.3444431239676398, 'b': 0.6014003085957186} - iteration 38 scored 0.2325 with: {'k1': 2.4639270689494523, 'b': 0.7717536517097305} - iteration 39 scored 0.2358 with: {'k1': 3.4589142889460534, 'b': 0.7043929438792035} - iteration 40 scored 0.2329 with: {'k1': 4.415526839360014, 'b': 0.6737248394761717} Best score: 0.2358 Best params: {'k1': 3.4589142889460534, 'b': 0.7043929438792035} Final params: {'k1': 3.4589142889460534, 'b': 0.7043929438792035} CPU times: user 37.3 s, sys: 9.16 s, total: 46.4 s Wall time: 7min 13s ###Markdown Here's a look at the parameter space, which is easy to plot here since there are just two parameters. ###Code _ = plot_objective(metadata, sample_source='result') %%time set_bm25_parameters(es, index, **best_params) _ = evaluate_mrr100_dev(es, max_concurrent_searches, index, template_id, query_params) ###Output Evaluation with: MRR@100 Score: 0.2594 CPU times: user 1.92 s, sys: 534 ms, total: 2.45 s Wall time: 34.2 s ###Markdown Interesting that we do see an improvement but it's not very significant. One hypothesis is that maybe our analyzers are doing work that means there's not much left to tune. Let's try this again but using the default analyzers with the index `msmarco-document.defaults`.First we set the baseline that we're comparing against. We expect it to be lower than the baseline with the custom analyzers. We saw this in the "Analyzers" notebook as well already. ###Code %%time set_bm25_parameters(es, index_defaults, **default_bm25_params) _ = evaluate_mrr100_dev(es, max_concurrent_searches, index_defaults, template_id, query_params) ###Output Evaluation with: MRR@100 Score: 0.2403 CPU times: user 2.19 s, sys: 687 ms, total: 2.88 s Wall time: 4min 12s ###Markdown Now let's optimize BM25. Before we do that, let's also increase the possible range of `k1` to make sure we really see a maximum score from somewhere within the range and not at a maximum or minumum value in the range. ###Code %%time _, best_params, _, metadata = optimize_bm25_mrr100(es, max_concurrent_searches, index_defaults, template_id, query_params, config_space=Config.parse({ 'method': 'bayesian', 'num_iterations': 50, 'num_initial_points': 25, 'space': { 'k1': { 'low': 0.5, 'high': 10.0 }, 'b': { 'low': 0.3, 'high': 1.0 }, } })) _ = plot_objective(metadata, sample_source='result') %%time set_bm25_parameters(es, index_defaults, **best_params) _ = evaluate_mrr100_dev(es, max_concurrent_searches, index_defaults, template_id, query_params) ###Output Evaluation with: MRR@100 Score: 0.2661 CPU times: user 2 s, sys: 651 ms, total: 2.65 s Wall time: 1min 6s ###Markdown That's a much larger improvement over the baseline, and actually this optimized version with the default analyzers beats the tuned version with the custom analyzers! Goes to show you that you can't make assumptions — you need to test your hypothesis! Conclusion Before we wrap up, it's good to set all the indices back to their default values, in case we use those indices for other experiments. ###Code set_bm25_parameters(es, index, **default_bm25_params) set_bm25_parameters(es, index_defaults, **default_bm25_params) ###Output _____no_output_____
Notebooks/CalebAssignment.ipynb
###Markdown QN1: Calculate the % GC and % AT content in the trna sequence ###Code def AT_GC_content(tRNA): GC = ((tRNA.count('C') + tRNA.count('G'))/len(tRNA))*100 AT = 100 - GC return print('GC content = ' + str(GC) + ' and the AT content = ' + str(AT)) AT_GC_content('AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA') ###Output GC content = 46.808510638297875 and the AT content = 53.191489361702125 ###Markdown QN2: Given the following amino acid sequence (MNKMDLVADVAEKTDLSKAKATEVIDAVFA), find the first, last and the 5th amino acids in the sequence ###Code def pos_seq(seq): pos = print(seq[0] + seq[4] + seq[-1]) return pos pos_seq('MNKMDLVADVAEKTDLSKAKATEVIDAVFA') ###Output MDA ###Markdown QN3: The above amino acid is a bacterial restriction enzyme that recognizes "TCCGGA". Find the first restriction site in the following sequence: AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA ###Code def first_rest(dna,pattern): pos = dna.find(pattern) if pos == -1: return print('substring not found') else: return print('The pattern is between index ' + str(pos)+ ' : ' + str(pos+len(pattern))) sample_dna = 'AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA' sample_pattern = 'TCCGGA' first_rest(sample_dna,sample_pattern) ###Output The pattern is between index 27 : 33 ###Markdown QN4: Using strings, lists, tuples and dictionaries concepts, find the reverse complement of AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA ###Code dnaseq= "AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA" def rev_comp(dna): mycomp1=dna.replace('A','t') mycomp2=mycomp1.replace('T','a') mycomp3=mycomp2.replace('G','c') mycomp4=mycomp3.replace('C','g') mycomp5=mycomp4.upper() reverse = mycomp5[::-1] return reverse rev_comp(dnaseq) ###Output _____no_output_____ ###Markdown QN5: Write a program to manage bank withdrawals at the ATM. Expand the script in the previous cell to also manage ATM deposits ###Code def ATMCHECK(pin): acountbal = 50000 choice = input("Please enter 'b' to check balance or 'w' to withdraw or 'd' to deposit: ") while choice != 'q': if choice.lower() in ('w','b','d'): if choice.lower() == 'b': print("Your balance is: %d" % acountbal) print("Anything else?") choice = input("Enter b for balance, w to withdraw or q to quit: ") print(choice.lower()) elif choice.lower() == 'd': deposit = float(input('please enter the amount you want to deposit: ')) acountbal = acountbal + deposit print(choice.lower()) print("Anything else?") choice = input("Enter b for balance, w to withdraw or q to quit: ") print(choice.lower()) else: withdraw = float(input("Enter amount to withdraw: ")) if withdraw <= acountbal: print("here is your: %.2f" % withdraw) acountbal = acountbal - withdraw print("Anything else?") choice = input("Enter b for balance, w to withdraw or q to quit: ") #choice = 'q' else: print("You have insufficient funds: %.2f" % acountbal) else: print('wrong choice') choice = input("Please enter 'b' to check balance or 'w' to withdraw: ") return acountbal ATMCHECK(7878) ###Output _____no_output_____ ###Markdown QN7: Create a while loop that starts with x = 0 and increments x until x is equal to 5. Each iteration should print to the console. ###Code def print5num(num): i = 0 while i < num: i = i+1 return (i print5num(5) ###Output _____no_output_____ ###Markdown QN8: Repeat the previous problem, but the loop will skip printing x = 5 to the console but will print values of x from 6 to 10. ###Code def print_num2(num): i = 0 while i < num: i = i+1 if i == 5: continue print(i) print_num2(10) ###Output 1 2 3 4 6 7 8 9 10 ###Markdown QN9: Create a for loop that prints values from 4 to 10 to the console. ###Code def print_num(num): i = 0 for i in range(3,num): i = i+1 print(i) print_num(10) ###Output 4 5 6 7 8 9 10 ###Markdown QN10: Write a function percentageGC that calculates the GC content of a DNA sequenceThe function should return the %GC content The Function should return a message if the provided sequence is not DNA (This should be checked by a different function, called by your function) ###Code mydna = "CAGTGATGATGACGAT" yourdna = "ACGATCGAGACGTAGTA" testdna = "ATFRACGATTGHAHYAK" def VALIDITY(dna): nucleotide = {'A', 'C', 'G', 'T'} #valid bases myseq = set(mydna) if myseq == nucleotide: print("Valid") else: print("invalid, The program can't calculate PerGC") VALIDITY(mydna) def percentageGC(dna): GC = (dna.count('C') + dna.count('G'))/len(dna)*100 print("The percentage GC is",GC) return GC percentageGC(mydna) ###Output The percentage GC is 43.75 ###Markdown QN11: Write a function the reads the file (humchr.txt) and writes to another file (gene_names.txt) a clean list of gene names. ###Code import urllib.request import urllib.request url = "https://www.uniprot.org/docs/humchrx.txt" destination_filename = "../Data/humchrx.txt" urllib.request.urlretrieve(url, destination_filename) def write2file(gene_list, out_file): """ Takes a gene list and writes the output to file """ with open(out_file, 'w') as outfile: outfile.write('\n'.join(gene_list)) def remove_empty(gene_list): """ Given a gene list, removes items that start with dash (empty) """ tag = True while tag: try: gene_list.remove('-') except ValueError: tag = False return gene_list def clean_genes(input_file, out_file): """ Given a chromosome annotation file, extract the genes and write them to another file """ gene_list = [] tag = False with open(input_file, 'r') as humchrx: for line in humchrx: if line.startswith('Gene'): tag=True if line == '\n': tag = False if tag: gene_list.append(line.split()[0]) #clean the gene list gene_list.pop(2) gene_list[0] = gene_list[0]+"_"+gene_list[1] gene_list.pop(1) gene_list = remove_empty(gene_list) ## Writing to file write2file(gene_list, out_file) clean_genes('../Data/humchrx.txt', 'testing.txt') ###Output _____no_output_____ ###Markdown QN12: Convert the function you wrote in exercise 1 into a python module. Then, import the module and use the function to read humchrx.txt file and create a gene list file.1. Convert the function you wrote in exercise 1 into a python module. Then, import the module and use the function to read humchrx.txt file and create a gene list file.2. Create a stand-alone script that does all the above. ###Code import write_to_file write_to_file.clean_genes('../Data/humchrx.txt', 'genes.txt') ###Output _____no_output_____ ###Markdown QN13: Using the same concept, convert your script in exercise 1 to take command line arguments (input and output files) ###Code pw ls import sys if len(sys.argv)!=3: print("enter the script, inputfile and output file respectively") sys.exit() inputfile = sys.argv[1] outputfile = sys.argv[2] def write2file(gene_list, out_file): """ Takes a gene list and writes the output to file """ with open("/home/eanbit7/Python4Bioinformatics2020/Notebooks/out_file", 'w') as out_file2: out_file2.write('\n'.join(gene_list)) def remove_empty(gene_list): """ Given a gene list, removes items that start with dash (empty) """ tag = True while tag: try: gene_list.remove('-') except ValueError: tag = False return gene_list def clean_genes(input_file, out_file2): """ Given a chromosome annotation file, extract the genes and write them to another file """ gene_list = [] tag = False with open("/home/eanbit7/Desktop/Python4Bioinformatics2019/Data/humchrx.txt", 'r') as humchrx: for line in humchrx: if line.startswith('Gene'): tag=True if line == '\n': tag = False if tag: gene_list.append(line.split()[0]) #clean the gene list gene_list.pop(2) gene_list[0] = gene_list[0]+"_"+gene_list[1] gene_list.pop(1) gene_list = remove_empty(gene_list) ## Writing to file write2file(gene_list, out_file2) clean_genes('/home/eanbit7/Desktop/Python4Bioinformatics2019/Data/humchrx.txt', '/home/eanbit7/Python4Bioinformatics2020/Notebooks/testing.txt1') print('bye') import trial ###Output bye ###Markdown QN14: Using a DNA sequence read from file, answer the following questions:1. Show that the DNA string contains only four letters.2. In the DNA string there are regions that have a repeating letter. What is the letter and length of the longest repeating region?3. How many ’ATG’s are in the DNA string? ###Code bases = 'ATGC' dna = 'AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA' def num_bases(sequence): my_list = list(sequence) set_dna = set(my_list) return set_dna num_bases(dna) def count_ATG(dna): if dna.find('ATG')== -1: return 'Pattern not found' else: return dna.count('ATG') count_ATG(mydna) cd='AAAGGGCTTAGCTTAATTAAAGTGGCTGATTTGCCCCCGTTCAGTTGATTTGCAGAGTGGGGTTTTGCAGTCCTTA' def longest_repeating_nucleotide(): dna_seq = input('please enter the DNA sequence') A_list = [] # initialize an empty list to store repeating nucleotides tag = False As = [] # initialize an empty list to store repeating nucleotides that will be appended to initialized A_list above for nuc in dna_seq: for dna in dna_seq: if dna == nuc: tag = True As.append(dna) else: if len(As) > 1: A_list.append(As) As = [] tag = False len_list = [len(x) for x in A_list] long_index = len_list.index(max(len_list)) print('*'*100) print('%s is the longest repeating letter, repeat %d times' %(A_list[long_index][0], len(A_list[long_index]))) longest_repeating_nucleotide() ###Output _____no_output_____
examples/ruGPT3XL_ILM.ipynb
###Markdown Install lib ###Code %%bash rm -rf /usr/local/cuda ln -s /usr/local/cuda-10.1 /usr/local/cuda !nvcc --version !stat /usr/local/cuda !pip uninstall -y triton !pip uninstall -y torch %%bash export LD_LIBRARY_PATH=/usr/lib/ !apt-get install clang-9 llvm-9 llvm-9-dev llvm-9-tools !pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html %%writefile setup.sh git clone https://github.com/NVIDIA/apex cd apex pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ !sh setup.sh !pip install triton==0.2.3 # !pip uninstall -y typing !pip install cpufeature !DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 pip install deepspeed==0.3.7 !ds_report import deepspeed.ops.sparse_attention.sparse_attn_op %cd /content/ !rm -rf rugpt3xl_ilm !cat /content/rugpt3xl_ilm/requirements.txt !git clone https://github.com/lauberto/rugpt3xl_ilm.git # TODO: add path to requirements.txt and install requirements (make sure to use the requirements necessary both for ILM and RUGP3XL) %%writefile ilm_requirements.txt boto3==1.13.16 botocore==1.16.16 certifi==2020.4.5.1 chardet==3.0.4 click==7.1.2 docutils==0.15.2 filelock==3.0.12 idna==2.9 jmespath==0.10.0 joblib==0.15.1 nltk==3.4.5 numpy==1.18.2 python-dateutil==2.8.1 regex==2020.5.14 requests==2.23.0 s3transfer==0.3.3 sacremoses==0.0.43 sentencepiece==0.1.91 six==1.15.0 tokenizers==0.5.2 tqdm==4.46.0 transformers==2.7.0 urllib3==1.25.9 # %cd /content/rugpt3xl_ilm ! pip install -r ilm_requirements.txt ! python -c "import nltk; nltk.download('punkt')" !pip install transformers==3.5.1 !cp /content/rugpt3xl_ilm/src_utils/trainer_pt_utils.py /usr/local/lib/python3.7/dist-packages/transformers/trainer_pt_utils.py ###Output _____no_output_____ ###Markdown Test model Load model ###Code import warnings warnings.filterwarnings("ignore") import sys sys.path.append("rugpt3xl_ilm/") import os os.environ["USE_DEEPSPEED"] = "1" ###Output _____no_output_____ ###Markdown ILM ###Code from google.colab import drive drive.mount('/content/gdrive') %cd gdrive/My Drive/RUGPT3XL # TODO: upload data to gdrive # TODO: use the right path for the script below !! python3 /content/rugpt3xl_ilm/train_ilm.py \ experiment \ /content/gdrive/RUGPT3XL/model_Economics \ /content/gdrive/RUGPT3XL/data/Economics_char_masks/ \ --seed 0 \ --train_examples_tag train \ --data_loader_num_workers 8 \ --eval_examples_tag valid \ --eval_max_num_examples 512 \ --tokenizer_name RUGPT3XL \ --model_name sberbank-ai/rugpt3xl 2>&1 | tee rugpt3xl_TrainerLog.txt !cat /content/rugpt3xl_ilm/ilm/official_gpt2_encoder/encoder.py ###Output _____no_output_____ ###Markdown Install lib ###Code %%bash rm -rf /usr/local/cuda ln -s /usr/local/cuda-10.1 /usr/local/cuda !nvcc --version !stat /usr/local/cuda !pip uninstall -y triton !pip uninstall -y torch %%bash export LD_LIBRARY_PATH=/usr/lib/ !apt-get install clang-9 llvm-9 llvm-9-dev llvm-9-tools !pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html %%writefile setup.sh git clone https://github.com/NVIDIA/apex cd apex pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ !sh setup.sh !pip install triton==0.2.3 # !pip uninstall -y typing !pip install cpufeature !DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 pip install deepspeed==0.3.7 !ds_report import deepspeed.ops.sparse_attention.sparse_attn_op %cd /content/ !rm -rf rugpt3xl_ilm !cat /content/rugpt3xl_ilm/requirements.txt !git clone https://github.com/lauberto/rugpt3xl_ilm.git # TODO: add path to requirements.txt and install requirements (make sure to use the requirements necessary both for ILM and RUGP3XL) %%writefile ilm_requirements.txt boto3==1.13.16 botocore==1.16.16 certifi==2020.4.5.1 chardet==3.0.4 click==7.1.2 docutils==0.15.2 filelock==3.0.12 idna==2.9 jmespath==0.10.0 joblib==0.15.1 nltk==3.4.5 numpy==1.18.2 python-dateutil==2.8.1 regex==2020.5.14 requests==2.23.0 s3transfer==0.3.3 sacremoses==0.0.43 sentencepiece==0.1.91 six==1.15.0 tokenizers==0.5.2 tqdm==4.46.0 urllib3==1.25.9 # %cd /content/rugpt3xl_ilm ! pip install -r ilm_requirements.txt ! python -c "import nltk; nltk.download('punkt')" !pip install transformers==3.5.1 !cp /content/rugpt3xl_ilm/src_utils/trainer_pt_utils.py /usr/local/lib/python3.7/dist-packages/transformers/trainer_pt_utils.py ###Output _____no_output_____ ###Markdown Test model Load model ###Code import warnings warnings.filterwarnings("ignore") import sys sys.path.append("rugpt3xl_ilm/") import os os.environ["USE_DEEPSPEED"] = "1" ###Output _____no_output_____ ###Markdown ILM ###Code from google.colab import drive drive.mount('/content/gdrive') %cd gdrive/My Drive/RUGPT3XL # TODO: upload data to gdrive # TODO: use the right path for the script below !! python3 /content/rugpt3xl_ilm/train_ilm.py \ experiment \ /content/gdrive/RUGPT3XL/model_Economics \ /content/gdrive/RUGPT3XL/data/Economics_char_masks/ \ --seed 0 \ --train_examples_tag train \ --data_loader_num_workers 8 \ --eval_examples_tag valid \ --eval_max_num_examples 512 \ --tokenizer_name RUGPT3XL \ --model_name sberbank-ai/rugpt3xl 2>&1 | tee rugpt3xl_TrainerLog.txt !cat /content/rugpt3xl_ilm/ilm/official_gpt2_encoder/encoder.py ###Output """Byte pair encoding utilities""" import os import json import regex as re from functools import lru_cache from ilm.tokenize_util import Tokenizer from ilm.paths import OFFICIAL_GPT2_ENCODER_DIR, OFFICIAL_RUGPT3_ENCODER_DIR @lru_cache() def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. """ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8+n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs)) def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs class Encoder: def __init__(self, encoder, bpe_merges, errors='replace'): self.encoder = encoder self.decoder = {v:k for k,v in self.encoder.items()} self.errors = errors # how to handle errors in decoding self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v:k for k, v in self.byte_encoder.items()} self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) self.cache = {} # Should haved added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") def bpe(self, token): if token in self.cache: return self.cache[token] word = tuple(token) pairs = get_pairs(word) if not pairs: return token while True: bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if word[i] == first and i < len(word)-1 and word[i+1] == second: new_word.append(first+second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = ' '.join(word) self.cache[token] = word return word def encode(self, text): bpe_tokens = [] for token in re.findall(self.pat, text): token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) return bpe_tokens def decode(self, tokens): text = ''.join([self.decoder[token] for token in tokens]) text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors) return text def get_encoder(tokenizer): if tokenizer == Tokenizer.RUGPT3XL: models_dir = OFFICIAL_RUGPT3_ENCODER_DIR with open(os.path.join(models_dir, 'vocab.json'), 'r') as f: encoder = json.load(f) with open(os.path.join(models_dir, 'merges.txt'), 'r', encoding="utf-8") as f: bpe_data = f.read() bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:-1]] return Encoder( encoder=encoder, bpe_merges=bpe_merges, ) elif tokenizer == Tokenizer.GPT2: models_dir = OFFICIAL_GPT2_ENCODER_DIR with open(os.path.join(models_dir, 'encoder.json'), 'r') as f: encoder = json.load(f) with open(os.path.join(models_dir, 'vocab.bpe'), 'r', encoding="utf-8") as f: bpe_data = f.read() bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:-1]] return Encoder( encoder=encoder, bpe_merges=bpe_merges, ) else: raise NotImplementedError("Only GPT2 and RUGPT3XL tokenizer-wrapping is supported.")
tegridy-tools/notebooks/MIDI_MIR_Statistics.ipynb
###Markdown MIDI MIR Statistics Notebook (ver 1.0) *** View detailed info and stats for the specified MIDI file *** Project Los Angeles Tegridy Code 2021 ###Code #@title Install all dependencies !git clone https://github.com/asigalov61/tegridy-tools !pip install mido !pip install visual_midi !pip install pypianoroll !git clone https://github.com/sniperwrb/python-midi !apt-get install swig %cd /content/python-midi !python setup.py install %cd /content/ !mkdir /content/midis/ #@title Import needed modules import os import numpy as np import mido import string import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.colors import colorConverter import sys, math, time import midi from pypianoroll import Multitrack, Track from mido import MidiFile from operator import itemgetter from visual_midi import Plotter from visual_midi import Preset from pretty_midi import PrettyMIDI import midi from midi.constants import NOTE_NAME_MAP_SHARP import argparse import networkx as nx #@title Specify the input MIDI file to analyze MIDI_file_to_analyze = "/content/tegridy-tools/tegridy-tools/seed.mid" #@param {type:"string"} #@title visual_midi Bokeh Plot preset = Preset(plot_width=850) plotter = Plotter(preset, plot_max_length_bar=4) pm = PrettyMIDI(MIDI_file_to_analyze) plotter.show_notebook(pm) #@title Plot Piano Roll # inherit the origin mido class class MidiFile(mido.MidiFile): def __init__(self, filename): mido.MidiFile.__init__(self, filename) self.sr = 10 self.meta = {} self.events = self.get_events() def get_events(self): mid = self print(mid) # There is > 16 channel in midi.tracks. However there is only 16 channel related to "music" events. # We store music events of 16 channel in the list "events" with form [[ch1],[ch2]....[ch16]] # Lyrics and meta data used a extra channel which is not include in "events" events = [[] for x in range(16)] # Iterate all event in the midi and extract to 16 channel form for track in mid.tracks: for msg in track: try: channel = msg.channel events[channel].append(msg) except AttributeError: try: if type(msg) != type(mido.UnknownMetaMessage): self.meta[msg.type] = msg.dict() else: pass except: print("error",type(msg)) return events def get_roll(self): events = self.get_events() # Identify events, then translate to piano roll # choose a sample ratio(sr) to down-sample through time axis sr = self.sr # compute total length in tick unit length = self.get_total_ticks() # allocate memory to numpy array roll = np.zeros((16, 128, length // sr), dtype="int8") # use a register array to save the state(no/off) for each key note_register = [int(-1) for x in range(128)] # use a register array to save the state(program_change) for each channel timbre_register = [1 for x in range(16)] for idx, channel in enumerate(events): time_counter = 0 volume = 100 # Volume would change by control change event (cc) cc7 & cc11 # Volume 0-100 is mapped to 0-127 print("channel", idx, "start") for msg in channel: if msg.type == "control_change": if msg.control == 7: volume = msg.value # directly assign volume if msg.control == 11: volume = volume * msg.value // 127 # change volume by percentage # print("cc", msg.control, msg.value, "duration", msg.time) if msg.type == "program_change": timbre_register[idx] = msg.program #print("channel", idx, "pc", msg.program, "time", time_counter, "duration", msg.time) if msg.type == "note_on": #print("on ", msg.note, "time", time_counter, "duration", msg.time, "velocity", msg.velocity) note_on_start_time = time_counter // sr note_on_end_time = (time_counter + msg.time) // sr intensity = volume * msg.velocity // 127 # When a note_on event *ends* the note start to be play # Record end time of note_on event if there is no value in register # When note_off event happens, we fill in the color if note_register[msg.note] == -1: note_register[msg.note] = (note_on_end_time,intensity) else: # When note_on event happens again, we also fill in the color old_end_time = note_register[msg.note][0] old_intensity = note_register[msg.note][1] roll[idx, msg.note, old_end_time: note_on_end_time] = old_intensity note_register[msg.note] = (note_on_end_time,intensity) if msg.type == "note_off": try: #print("off", msg.note, "time", time_counter, "duration", msg.time, "velocity", msg.velocity) note_off_start_time = time_counter // sr note_off_end_time = (time_counter + msg.time) // sr note_on_end_time = note_register[msg.note][0] intensity = note_register[msg.note][1] # fill in color roll[idx, msg.note, note_on_end_time:note_off_end_time] = intensity note_register[msg.note] = -1 # reinitialize register except: continue time_counter += msg.time # TODO : velocity -> done, but not verified # TODO: Pitch wheel # TODO: Channel - > Program Changed / Timbre catagory # TODO: real time scale of roll # if there is a note not closed at the end of a channel, close it for key, data in enumerate(note_register): if data != -1: note_on_end_time = data[0] intensity = data[1] # print(key, note_on_end_time) note_off_start_time = time_counter // sr roll[idx, key, note_on_end_time:] = intensity note_register[idx] = -1 return roll def get_roll_image(self): roll = self.get_roll() plt.ioff() K = 16 transparent = colorConverter.to_rgba('black') colors = [mpl.colors.to_rgba(mpl.colors.hsv_to_rgb((i / K, 1, 1)), alpha=1) for i in range(K)] cmaps = [mpl.colors.LinearSegmentedColormap.from_list('my_cmap', [transparent, colors[i]], 128) for i in range(K)] for i in range(K): cmaps[i]._init() # create the _lut array, with rgba values # create your alpha array and fill the colormap with them. # here it is progressive, but you can create whathever you want alphas = np.linspace(0, 1, cmaps[i].N + 3) cmaps[i]._lut[:, -1] = alphas fig = plt.figure(figsize=(12, 9)) a1 = fig.add_subplot(111) a1.axis("equal") a1.set_facecolor("black") array = [] for i in range(K): try: img = a1.imshow(roll[i], interpolation='nearest', cmap=cmaps[i], aspect='auto') array.append(img.get_array()) except IndexError: pass return array def draw_roll(self): roll = self.get_roll() # build and set fig obj plt.ioff() fig = plt.figure(figsize=(12, 9)) a1 = fig.add_subplot(111) a1.axis("equal") a1.set_facecolor("black") # change unit of time axis from tick to second tick = self.get_total_ticks() second = mido.tick2second(tick, self.ticks_per_beat, self.get_tempo()) #print(second) if second > 10: x_label_period_sec = second // 10 else: x_label_period_sec = second / 10 # ms #print(x_label_period_sec) x_label_interval = mido.second2tick(x_label_period_sec, self.ticks_per_beat, self.get_tempo()) / self.sr #print(x_label_interval) plt.xticks([int(x * x_label_interval) for x in range(20)], [round(x * x_label_period_sec, 2) for x in range(20)]) # change scale and label of y axis plt.yticks([y*16 for y in range(8)], [y*16 for y in range(8)]) # build colors channel_nb = 16 transparent = colorConverter.to_rgba('black') colors = [mpl.colors.to_rgba(mpl.colors.hsv_to_rgb((i / channel_nb, 1, 1)), alpha=1) for i in range(channel_nb)] cmaps = [mpl.colors.LinearSegmentedColormap.from_list('my_cmap', [transparent, colors[i]], 128) for i in range(channel_nb)] # build color maps for i in range(channel_nb): cmaps[i]._init() # create your alpha array and fill the colormap with them. alphas = np.linspace(0, 1, cmaps[i].N + 3) # create the _lut array, with rgba values cmaps[i]._lut[:, -1] = alphas # draw piano roll and stack image on a1 for i in range(channel_nb): try: a1.imshow(roll[i], origin="lower", interpolation='nearest', cmap=cmaps[i], aspect='auto') except IndexError: pass # draw color bar colors = [mpl.colors.hsv_to_rgb((i / channel_nb, 1, 1)) for i in range(channel_nb)] cmap = mpl.colors.LinearSegmentedColormap.from_list('my_cmap', colors, 16) a2 = fig.add_axes([0.05, 0.80, 0.9, 0.15]) cbar = mpl.colorbar.ColorbarBase(a2, cmap=cmap, orientation='horizontal', ticks=list(range(16))) # show piano roll plt.draw() plt.ion() plt.show(block=True) #plt.savefig('test.jpg', dpi=300) def get_tempo(self): try: return self.meta["set_tempo"]["tempo"] except: return 500000 def get_total_ticks(self): max_ticks = 0 for channel in range(16): ticks = sum(msg.time for msg in self.events[channel]) if ticks > max_ticks: max_ticks = ticks return max_ticks mid = MidiFile(MIDI_file_to_analyze) # get the list of all events # events = mid.get_events() # get the np array of piano roll image roll = mid.get_roll() # draw piano roll by pyplot mid.draw_roll() #@title MIDI Stats 1 # https://github.com/LiuFang816/SALSTM_py_data/blob/d494b3041069d377d6a7a9c296a14334f2fa5acc/python/olofmogren_c-rnn-gan/c-rnn-gan-master/midi_statistics.py # https://github.com/gbramleysimmons/musictransformers def msg2dict(msg): result = dict() if 'note_on' in msg: on_ = True elif 'note_off' in msg: on_ = False else: on_ = None result['time'] = int(msg[msg.rfind('time'):].split(' ')[0].split('=')[1].translate( str.maketrans({a: None for a in string.punctuation}))) if on_ is not None: for k in ['note', 'velocity']: result[k] = int(msg[msg.rfind(k):].split(' ')[0].split('=')[1].translate( str.maketrans({a: None for a in string.punctuation}))) return [result, on_] def switch_note(last_state, note, velocity, on_=True): # piano has 88 notes, corresponding to note id 21 to 108, any note out of this range will be ignored result = [0] * 88 if last_state is None else last_state.copy() if 21 <= note <= 108: result[note-21] = velocity if on_ else 0 return result def get_new_state(new_msg, last_state): new_msg, on_ = msg2dict(str(new_msg)) new_state = switch_note(last_state, note=new_msg['note'], velocity=new_msg['velocity'], on_=on_) if on_ is not None else last_state return [new_state, new_msg['time']] def track2seq(track): # piano has 88 notes, corresponding to note id 21 to 108, any note out of the id range will be ignored result = [] last_state, last_time = get_new_state(str(track[0]), [0]*88) for i in range(1, len(track)): new_state, new_time = get_new_state(track[i], last_state) if new_time > 0: result += [last_state]*new_time last_state, last_time = new_state, new_time return result def mid2arry(mid, min_msg_pct=0.1): tracks_len = [len(tr) for tr in mid.tracks] min_n_msg = max(tracks_len) * min_msg_pct # convert each track to nested list all_arys = [] for i in range(len(mid.tracks)): if len(mid.tracks[i]) > min_n_msg: ary_i = track2seq(mid.tracks[i]) all_arys.append(ary_i) # make all nested list the same length max_len = max([len(ary) for ary in all_arys]) for i in range(len(all_arys)): if len(all_arys[i]) < max_len: all_arys[i] += [[0] * 88] * (max_len - len(all_arys[i])) all_arys = np.array(all_arys) all_arys = all_arys.max(axis=0) # trim: remove consecutive 0s in the beginning and at the end sums = all_arys.sum(axis=1) ends = np.where(sums > 0)[0] return all_arys[min(ends): max(ends)] def print_array(midi_array): plt.plot(range(midi_array.shape[0]), np.multiply(np.where(midi_array > 0, 1, 0), range(1, 89)), marker='.', markersize=1, linestyle='') #plt.show() plt.savefig('MIDI Stats Graph.png', dpi=300) def main(): # Need to change filepath to midi path filepath = MIDI_file_to_analyze midi_file = mido.MidiFile(filepath, clip=True) midi_array = mid2arry(midi_file) print_array(midi_array) if __name__ == '__main__': main() #@title MIDI Stats 2 # Tools to load and save midi files for the rnn-gan-project. # https://github.com/LiuFang816/SALSTM_py_data/blob/d494b3041069d377d6a7a9c296a14334f2fa5acc/python/olofmogren_c-rnn-gan/c-rnn-gan-master/midi_statistics.py # # https://github.com/TimStroup/Classical-Music-Generator/blob/847a410acb7e993c33e2116af45a7ccdb6b1a9e9/midi_statistics.py # # Written by Olof Mogren, http://mogren.one/ # # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== GENRE = 0 COMPOSER = 1 SONG_DATA = 2 # INDICES IN BATCHES: LENGTH = 0 FREQ = 1 VELOCITY = 2 TICKS_FROM_PREV_START = 3 # INDICES IN SONG DATA (NOT YET BATCHED): BEGIN_TICK = 3 CHANNEL = 4 debug = '' #debug = 'overfit' base_tones = {'C': 0, 'C#': 1, 'D': 2, 'D#': 3, 'E': 4, 'F': 5, 'F#': 6, 'G': 7, 'G#': 8, 'A': 9, 'A#': 10, 'B': 11} scale = {} #Major scale: scale['major'] = [0,2,4,5,7,9,11] #(W-W-H-W-W-W-H) #(2 2 1 2 2 2 1) #Natural minor scale: scale['natural_minor'] = [0,2,3,5,7,8,10] #(W-H-W-W-H-W-W) #(2 1 2 2 1 2 2) #Harmonic minor scale: scale['harmonic_minor'] = [0,2,3,5,7,8,11] #(W-H-W-W-H-WH-H) #(2 1 2 2 1 3 1) tone_names = {} for tone_name in base_tones: tone_names[base_tones[tone_name]] = tone_name def get_tones(midi_pattern): """ returns a dict of statistics, keys: [scale_distribution, """ tones = [] for track in midi_pattern: for event in track: if type(event) == midi.events.SetTempoEvent: pass # These are currently ignored elif (type(event) == midi.events.NoteOffEvent) or \ (type(event) == midi.events.NoteOnEvent and \ event.velocity == 0): pass # not needed here elif type(event) == midi.events.NoteOnEvent: tones.append(event.data[0]) return tones def detect_beat(midi_pattern): """ returns a dict of statistics, keys: [scale_distribution, """ abs_ticks = [] # Tempo: ticks_per_quarter_note = float(midi_pattern.resolution) for track in midi_pattern: abs_tick=0 for event in track: abs_tick += event.tick if type(event) == midi.events.SetTempoEvent: pass # These are currently ignored elif (type(event) == midi.events.NoteOffEvent) or \ (type(event) == midi.events.NoteOnEvent and \ event.velocity == 0): pass elif type(event) == midi.events.NoteOnEvent: abs_ticks.append(abs_tick) stats = {} for quarter_note_estimate in range(int(ticks_per_quarter_note), int(0.75*ticks_per_quarter_note), -1): #print('est: {}'.format(quarter_note_estimate)) avg_ticks_off = [] for begin_tick in range(quarter_note_estimate): ticks_off = [] for abs_tick in abs_ticks: #print('abs_tick: {} % {}'.format(abs_tick, quarter_note_estimate/4)) sixteenth_note_estimate = quarter_note_estimate/4 ticks_off_sixteenths = int((begin_tick+abs_tick)%sixteenth_note_estimate) if ticks_off_sixteenths > sixteenth_note_estimate/2: # off, but before beat ticks_off_sixteenths = -(ticks_off_sixteenths-sixteenth_note_estimate) #print('ticks_off: {}'.format(ticks_off_sixteenths)) ticks_off.append(ticks_off_sixteenths) avg_ticks_off.append(float(sum(ticks_off))/float(len(ticks_off))) #print('avg_ticks_off: {}. min: {}.'.format(avg_ticks_off, min(avg_ticks_off))) stats[quarter_note_estimate] = min(avg_ticks_off) return stats def get_abs_ticks(midi_pattern): abs_ticks = [] for track in midi_pattern: abs_tick=0 for event in track: abs_tick += event.tick if type(event) == midi.events.SetTempoEvent: pass # These are currently ignored elif (type(event) == midi.events.NoteOffEvent) or \ (type(event) == midi.events.NoteOnEvent and \ event.velocity == 0): pass elif type(event) == midi.events.NoteOnEvent: abs_ticks.append(abs_tick) abs_ticks.sort() return abs_ticks def get_top_k_intervals(midi_pattern, k): """ returns a fraction of the noteon events in midi_pattern that are polyphonous (several notes occurring at the same time). Here, two note on events are counted as the same event if they occur at the same time, and in this case it is considered a polyphonous event. """ intervals = {} abs_ticks = get_abs_ticks(midi_pattern) accumulator = 0 last_abs_tick = 0 for abs_tick in abs_ticks: interval = abs_tick-last_abs_tick if interval not in intervals: intervals[interval] = 0 intervals[interval] += 1 accumulator += 1 last_abs_tick = abs_tick intervals_list = [(interval, intervals[interval]/float(accumulator)) for interval in intervals] intervals_list.sort(key=lambda i: i[1], reverse=True) return intervals_list[:k] def get_polyphony_score(midi_pattern): """ returns a fraction of the noteon events in midi_pattern that are polyphonous (several notes occurring at the same time). Here, two note on events are counted as the same event if they occur at the same time, and in this case it is considered a polyphonous event. """ abs_ticks = get_abs_ticks(midi_pattern) monophonous_events = 0 polyphonous_events = 0 last_abs_tick = 0 tones_in_current_event = 0 for abs_tick in abs_ticks: if abs_tick == last_abs_tick: tones_in_current_event += 1 else: if tones_in_current_event == 1: monophonous_events += 1 elif tones_in_current_event > 1: polyphonous_events += 1 tones_in_current_event = 1 last_abs_tick = abs_tick if tones_in_current_event == 1: monophonous_events += 1 elif tones_in_current_event > 1: polyphonous_events += 1 if polyphonous_events == 0: return 0.0 return float(polyphonous_events)/(polyphonous_events+monophonous_events) def get_rhythm_stats(midi_pattern): """ returns a dict of statistics, keys: [scale_distribution, """ abs_ticks = [] # Tempo: ticks_per_quarter_note = float(midi_pattern.resolution) # Multiply with output_ticks_pr_input_tick for output ticks. for track in midi_pattern: abs_tick=0 for event in track: abs_tick += event.tick if type(event) == midi.events.SetTempoEvent: pass # These are currently ignored elif (type(event) == midi.events.NoteOffEvent) or \ (type(event) == midi.events.NoteOnEvent and \ event.velocity == 0): pass elif type(event) == midi.events.NoteOnEvent: abs_ticks.append(abs_tick) stats = {} for abs_tick in abs_ticks: ticks_since_quarter_note = int(abs_tick%ticks_per_quarter_note) if ticks_since_quarter_note not in stats: stats[ticks_since_quarter_note] = 1 else: stats[ticks_since_quarter_note] += 1 return stats def get_intensities(midi_pattern): """ returns a dict of statistics, keys: [scale_distribution, """ intensities = [] for track in midi_pattern: abs_tick=0 for event in track: abs_tick += event.tick if type(event) == midi.events.SetTempoEvent: pass # These are currently ignored elif (type(event) == midi.events.NoteOffEvent) or \ (type(event) == midi.events.NoteOnEvent and \ event.velocity == 0): pass elif type(event) == midi.events.NoteOnEvent: intensities.append(event.velocity) return (min(intensities), max(intensities)) def get_midi_pattern(filename): try: return midi.read_midifile(filename) except: print ('Error reading {}'.format(filename)) return None def tones_to_scales(tones): """ Midi to tone name (octave: -5): 0: C 1: C# 2: D 3: D# 4: E 5: F 6: F# 7: G 8: G# 9: A 10: A# 11: B Melodic minor scale is ignored. One octave is 12 tones. """ counts = {} for base_tone in base_tones: counts[base_tone] = {} counts[base_tone]['major'] = 0 counts[base_tone]['natural_minor'] = 0 counts[base_tone]['harmonic_minor'] = 0 if not len(tones): frequencies = {} for base_tone in base_tones: frequencies[base_tone] = {} for scale_label in scale: frequencies[base_tone][scale_label] = 0.0 return frequencies for tone in tones: for base_tone in base_tones: for scale_label in scale: if tone%12-base_tones[base_tone] in scale[scale_label]: counts[base_tone][scale_label] += 1 frequencies = {} for base_tone in counts: frequencies[base_tone] = {} for scale_label in counts[base_tone]: frequencies[base_tone][scale_label] = float(counts[base_tone][scale_label])/float(len(tones)) return frequencies def repetitions(tones): rs = {} #print(tones) #print(len(tones)/2) for l in range(2, min(len(tones)/2, 10)): #print (l) rs[l] = 0 for i in range(len(tones)-l*2): for j in range(i+l,len(tones)-l): #print('comparing \'{}\' and \'{}\''.format(tones[i:i+l], tones[j:j+l])) if tones[i:i+l] == tones[j:j+l]: rs[l] += 1 rs2 = {} for r in rs: if rs[r]: rs2[r] = rs[r] return rs2 def tone_to_tone_name(tone): """ Midi to tone name (octave: -5): 0: C 1: C# 2: D 3: D# 4: E 5: F 6: F# 7: G 8: G# 9: A 10: A# 11: B One octave is 12 tones. """ base_tone = tone_names[tone%12] octave = tone/12-5 return '{} {}'.format(base_tone, octave) def max_likelihood_scale(tones): scale_statistics = tones_to_scales(tones) stat_list = [] for base_tone in scale_statistics: for scale_label in scale_statistics[base_tone]: stat_list.append((base_tone, scale_label, scale_statistics[base_tone][scale_label])) stat_list.sort(key=lambda e: e[2], reverse=True) return (stat_list[0][0]+' '+stat_list[0][1], stat_list[0][2]) def tone_to_freq(tone): """ returns the frequency of a tone. formulas from * https://en.wikipedia.org/wiki/MIDI_Tuning_Standard * https://en.wikipedia.org/wiki/Cent_(music) """ return math.pow(2, ((float(tone)-69.0)/12.0)) * 440.0 def freq_to_tone(freq): """ returns a dict d where d['tone'] is the base tone in midi standard d['cents'] is the cents to make the tone into the exact-ish frequency provided. multiply this with 8192 to get the midi pitch level. formulas from * https://en.wikipedia.org/wiki/MIDI_Tuning_Standard * https://en.wikipedia.org/wiki/Cent_(music) """ if freq == 0.0: return None float_tone = (69.0+12*math.log(float(freq)/440.0, 2)) int_tone = int(float_tone) cents = int(1200*math.log(float(freq)/tone_to_freq(int_tone), 2)) return {'tone': int_tone, 'cents': cents} def cents_to_pitchwheel_units(cents): return int(40.96*(float(cents))) def get_all_stats(midi_pattern): stats = {} if not midi_pattern: print('Failed to read midi pattern.') return None tones = get_tones(midi_pattern) if len(tones) == 0: print('This is an empty song.') return None stats['num_tones'] = len(tones) stats['tone_min'] = min(tones) stats['freq_min'] = tone_to_freq(min(tones)) stats['tone_max'] = max(tones) stats['freq_max'] = tone_to_freq(max(tones)) stats['tone_span'] = max(tones)-min(tones) stats['freq_span'] = tone_to_freq(max(tones))-tone_to_freq(min(tones)) stats['tones_unique'] = len(set(tones)) rs = repetitions(tones) for r in range(2,10): if r in rs: stats['repetitions_{}'.format(r)] = rs[r] else: stats['repetitions_{}'.format(r)] = 0 ml = max_likelihood_scale(tones) stats['scale'] = ml[0] stats['scale_score'] = ml[1] beat_stats = detect_beat(midi_pattern) minval = float(midi_pattern.resolution) argmin = -1 for beat in beat_stats: #print('Looking at beat: {}. Avg ticks off: {}.'.format(beat, beat_stats[beat])) if beat_stats[beat] < minval: minval = beat_stats[beat] argmin = beat stats['estimated_beat'] = argmin stats['estimated_beat_avg_ticks_off'] = minval (min_int, max_int) = get_intensities(midi_pattern) stats['intensity_min'] = min_int stats['intensity_max'] = max_int stats['intensity_span'] = max_int-min_int stats['polyphony_score'] = get_polyphony_score(midi_pattern) stats['top_10_intervals'] = get_top_k_intervals(midi_pattern, 10) stats['top_2_interval_difference'] = 0.0 if len(stats['top_10_intervals']) > 1: stats['top_2_interval_difference'] = abs(stats['top_10_intervals'][1][0]-stats['top_10_intervals'][0][0]) stats['top_3_interval_difference'] = 0.0 if len(stats['top_10_intervals']) > 2: stats['top_3_interval_difference'] = abs(stats['top_10_intervals'][2][0]-stats['top_10_intervals'][0][0]) return stats def get_gnuplot_line(midi_patterns, i, showheader=True): stats = [] print('#getting stats...') stats_time = time.time() for p in midi_patterns: stats.append(get_all_stats(p)) print('done. time: {}'.format(time.time()-stats_time)) #print(stats) stats_keys_string = ['scale'] stats_keys = ['scale_score', 'tone_min', 'tone_max', 'tone_span', 'freq_min', 'freq_max', 'freq_span', 'tones_unique', 'repetitions_2', 'repetitions_3', 'repetitions_4', 'repetitions_5', 'repetitions_6', 'repetitions_7', 'repetitions_8', 'repetitions_9', 'estimated_beat', 'estimated_beat_avg_ticks_off', 'intensity_min', 'intensity_max', 'intensity_span', 'polyphony_score', 'top_2_interval_difference', 'top_3_interval_difference', 'num_tones'] gnuplotline = '' if showheader: gnuplotline = '# global-step {} {}\n'.format(' '.join([s.replace(' ', '_') for s in stats_keys_string]), ' '.join(stats_keys)) gnuplotline += '{} {} {}\n'.format(i, ' '.join(['{}'.format(stats[0][key].replace(' ', '_')) for key in stats_keys_string]), ' '.join(['{:.3f}'.format(sum([s[key] for s in stats])/float(len(stats))) for key in stats_keys])) return gnuplotline def main(): if len(sys.argv) > 2 and sys.argv[1] == '--gnuplot': #number = sys.argv[2] patterns = [] for i in range(3,len(sys.argv)): #print(i) filename = sys.argv[i] print('#File: {}'.format(filename)) #patterns.append(get_midi_pattern(filename)) print(get_gnuplot_line([get_midi_pattern(filename)], i, showheader=(i==0))) else: for i in range(1,len(sys.argv)): #filename = sys.argv[i] filename = MIDI_file_to_analyze print('File: {}'.format(filename)) midi_pattern = get_midi_pattern(filename) stats = get_all_stats(midi_pattern) if stats is None: print('Could not extract stats.') else: print ('ML scale estimate: {}: {:.2f}'.format(stats['scale'], stats['scale_score'])) print ('Min tone: {}, {:.1f} Hz.'.format(tone_to_tone_name(stats['tone_min']), stats['freq_min'])) print ('Max tone: {}, {:.1f} Hz.'.format(tone_to_tone_name(stats['tone_max']), stats['freq_max'])) print ('Span: {} tones, {:.1f} Hz.'.format(stats['tone_span'], stats['freq_span'])) print ('Unique tones: {}'.format(stats['tones_unique'])) for r in range(2,10): print('Repetitions of len {}: {}'.format(r, stats['repetitions_{}'.format(r)])) print('Estimated beat: {}. Avg ticks off: {:.2f}.'.format(stats['estimated_beat'], stats['estimated_beat_avg_ticks_off'])) print('Intensity: min: {}, max: {}.'.format(stats['intensity_min'], stats['intensity_max'])) print('Polyphonous events: {:.2f}.'.format(stats['polyphony_score'])) print('Top intervals:') for interval,score in stats['top_10_intervals']: print('{}: {:.2f}.'.format(interval,score)) print('Top 2 interval difference: {}.'.format(stats['top_2_interval_difference'])) print('Top 3 interval difference: {}.'.format(stats['top_3_interval_difference'])) if __name__ == "__main__": main() #@title MIDI Stats 3 (Ground Truth) # https://github.com/mbereket/music-transcription # Comverts MIDI file pattern to representation of notes events in absolute time class NoteEvents: def __init__(self, pattern, note_tracks=None, start_on_note=True): self._event_list = [] self.note_time_list = [] pattern.make_ticks_abs() self.pattern = pattern self.ticks_per_beat = pattern.resolution self.numNotes = 88 # offset between note index and MIDI note number self.noteOffset = 9 # list of track names to include notes from self.note_tracks = note_tracks self.names = self._name_tracks() self.start_on_note = start_on_note self._parse_events() def _name_tracks(self): names = [None] * len(self.pattern) for i in range(len(self.pattern)): for event in self.pattern[i]: if type(event) == midi.events.TrackNameEvent: names[i] = event.text break return names def _parse_events(self): for i in range(len(self.pattern)): for event in self.pattern[i]: if type(event) in (midi.events.NoteOnEvent, midi.events.NoteOffEvent): if self.note_tracks == None or self.names[i] in self.note_tracks: self._event_list.append(event) elif type(event) == midi.events.SetTempoEvent: self._event_list.append(event) elif type(event) == midi.events.EndOfTrackEvent and event.tick != 0: self._event_list.append(event) self._event_list = sorted(self._event_list, key=lambda x: x.tick) self._event_list_timed() def _event_list_timed(self): assert(type(self._event_list[0]) == midi.events.SetTempoEvent) microseconds_per_beat = self._event_list[0].get_mpqn() prev_time = 0 prev_tick = 0 microseconds_per_tick = float(microseconds_per_beat) / self.ticks_per_beat for event in self._event_list: tick_diff = event.tick - prev_tick curr_time = prev_time + (tick_diff * microseconds_per_tick) if type(event) != midi.events.SetTempoEvent: self.note_time_list.append((event, curr_time)) prev_time = curr_time prev_tick = event.tick else: prev_time = curr_time prev_tick = event.tick microseconds_per_beat = event.get_mpqn() microseconds_per_tick = float(microseconds_per_beat) / self.ticks_per_beat start_time = self.note_time_list[0][1] if self.start_on_note: for i, tup in enumerate(self.note_time_list): self.note_time_list[i] = (tup[0],tup[1]-start_time) self._last_event_time = self.note_time_list[-1][1] def _note_off(self, note_event): return ((type(note_event) == midi.events.NoteOnEvent) and (note_event.get_velocity() == 0)) \ or type(note_event) == midi.events.NoteOffEvent # returns index of first slice at or after given time # time in microseconds def time_to_slice(self, t, slices_per_second): microseconds_per_slice = 1e6 / slices_per_second return np.ceil(float(t) / microseconds_per_slice).astype(int) # duration in seconds def get_ground_truth(self, slices_per_second, duration=None): microseconds_per_slice = 1e6 / slices_per_second number_slices = np.ceil(self._last_event_time / microseconds_per_slice).astype(int) ground_truth = np.zeros(self.numNotes * number_slices).reshape(self.numNotes, number_slices) template = np.zeros(self.numNotes).reshape(self.numNotes,1) prev_time = 0 for note, curr_time in self.note_time_list: if prev_time != curr_time: prev_time_slice = self.time_to_slice(prev_time, slices_per_second) curr_time_slice = self.time_to_slice(curr_time, slices_per_second) #make all slices in [prev_time, curr_time) equal to current template ground_truth[:,prev_time_slice:curr_time_slice] = template.repeat(curr_time_slice - prev_time_slice, axis=1) if type(note) == midi.events.EndOfTrackEvent: break pitch_index = note.get_pitch() - self.noteOffset if pitch_index >= 0 and pitch_index < self.numNotes: if self._note_off(note): template[pitch_index] = 0 else: template[pitch_index] = 1 prev_time = curr_time if duration != None: ground_truth = ground_truth[:,:self.time_to_slice(1e6 * duration, slices_per_second)] return ground_truth if __name__ == '__main__': pattern = midi.read_midifile(MIDI_file_to_analyze) events = NoteEvents(pattern) truth = events.get_ground_truth(31.25, 15) plt.matshow(truth) plt.show() #@title MIDI Stats 4 # https://github.com/Astner/exjobb/blob/1abc750a7a4d9af52e273ef24c2c32d0e431e1a6/concepts-master/experimental/higherorder/formats/midi/miditocontext/midiutils.py # # Copyright 2015 Daniel Gillblad ([email protected]). # 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 # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Selecte active channels # Here, all channels except 10 are used, as this MIDI channel is used for percussion only # in General MIDI files (note that we index channels from 0, not 1) activeChannels = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15) # Time during which events are considered simultaneous simTimeLimit = 50 # Fraction of time notes need to be overlapping to be considered played together overlapFracLimit = 0.95 # Print info on specified MIDI file def printMidiFileInfo(midifile): mid = MidiFile(midifile) print("File:", os.path.basename(midifile), "Type:", mid.type, "Length: ", end = "") if mid.type < 2: print(mid.length) else: print("N/A") # Print messages in MIDI file def printMidiMessages(midifile): mid = MidiFile(midifile) for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) for message in track: print(message) # Simple class for representing current note state, # given a series of messages given in order to the update method. class NoteState: nstate = [-1] * 128 def printState(self): print('|', end = '') for i in self.nstate[22:116]: if i >= 0: print('*', end = '') else: print('-', end = '') print('|') def update(self, message, time = 0): if message.type == 'all_notes_off': self.nstate = [-1] * 128 elif message.type == 'note_off' or (message.type == 'note_on' and message.velocity <= 0): rmsg = [(self.nstate[message.note], time, message.note)] self.nstate[message.note] = -1 return rmsg elif message.type == 'note_on': self.nstate[message.note] = time return [] return [] # Determines if a message is a "note" message: note on, note off, or all notes off def isNoteMessage(msg): if msg.type == 'note_on' or msg.type == 'note_off' or msg.type == 'all_notes_off': return True else: return False # Determines if a message is a "note" message on a specific channel def isNoteMessageOnChannel(msg, ch): if isNoteMessage(msg) and msg.channel == ch: return True else: return False # Convert a MIDI file to a list of note events, each note given by # (start-time, end-time, note number). Returns a nested list with # one list per channel per track. def fileToNoteList(midifile): mid = MidiFile(midifile) allnotes = [] for i, track in enumerate(mid.tracks): tracknotes = [] for channel in activeChannels: channelnotes = [] state = NoteState() cTime = 0 for message in track: cTime += message.time if isNoteMessageOnChannel(message, channel): channelnotes += state.update(message, cTime) if len(channelnotes) >= 1: tracknotes += [sorted(channelnotes, key=itemgetter(0,1))] if len(tracknotes) >= 1: allnotes += [tracknotes] return allnotes # Convert a note list to a list of notes played together. def playedTogether(notelist): together = [] for i, note in enumerate(notelist): # Find overlaps for fnote in notelist[i + 1:]: if fnote[0] > note[1]: break overlap_a = (note[1] - fnote[0]) / (note[1] - note[0]) overlap_b = (fnote[1] - note[1]) / (fnote[1] - fnote[0]) if overlap_a >= overlapFracLimit or overlap_b >= overlapFracLimit: together += [[note[2], fnote[2]]] return together # Find all notes played together in midifile, separated by track and channel def allNotesPlayedTogether(midifile): notelists = fileToNoteList(midifile) alltogether = [] for t in notelists: for c in t: alltogether += playedTogether(c) return alltogether # Print a graphic representation of all note messages in a MIDI file # on a (reasonable) easy to read format. def printNoteMessages(midifile): mid = MidiFile(midifile) for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) for channel in activeChannels: print('Channel:', channel) state = NoteState() cTime = 0 simTime = 0 for message in track: cTime += message.time if isNoteMessageOnChannel(message, channel): # If message is outside what would be considered simultaneous, # emit last state and reset simultaneous time counter if (simTime + message.time) >= simTimeLimit: print(cTime, end = '') state.printState() simTime = 0 else: simTime += message.time state.update(message, cTime) # Print a graphic representation of all note messages in a MIDI file # on a (reasonable) easy to read format, grouping near simultaneous note events # for readability. def printGroupedNoteOnMessages(midifile): mid = MidiFile(midifile) for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) for channel in activeChannels: print('Channel:', channel) cTime = 0 gTime = 0 nSet = set() for message in track: cTime += message.time if message.type == 'note_on' and message.velocity > 0 and message.channel == channel: if (cTime - gTime) >= simTimeLimit: print(cTime, nSet) gTime = cTime nSet.clear() nSet.add(message.note) else: nSet.add(message.note) # Collect a set of statistics for a specified MIDI file object. def collectMidiNoteStatistics(midifileobj, channel_activity, played_notes, note_offs, running_status, all_notes_off): for i, track in enumerate(midifileobj.tracks): for channel in activeChannels: for message in track: if(isNoteMessage(message)): channel_activity[message.channel] += 1 if message.type == 'note_on' and message.velocity > 0: played_notes[message.note] += 1 if message.type == 'note_off': note_offs[message.channel] += 1 if message.type == 'note_on' and message.velocity <= 0: running_status[message.channel] += 1 if message.type == 'all_notes_off': all_notes_off[message.channel] += 1 # Print MIDI file statistics compiled for all MIDI files found in the specified directory # and all sub-directories recursively. def printMidiFileStatistics(root_dir): nr_files = 0 nr_file_types = [0] * 3 nr_length_files = 0 total_length = 0 channel_activity = [0] * 16 played_notes = [0] * 127 note_offs = [0] * 16 # Per channel running_status = [0] * 16 # Per channel all_notes_off = [0] * 16 # Per channel mid = MidiFile(MIDI_file_to_analyze) nr_files += 1 nr_file_types[mid.type] += 1 if mid.type < 2: nr_length_files += 1 total_length += mid.length collectMidiNoteStatistics(mid, channel_activity, played_notes, note_offs, running_status, all_notes_off) print('--------------------------------------------------------------------------') print('Number of .mid files:', nr_files, ' Type 0:', nr_file_types[0], ' Type 1:', nr_file_types[1], ' Type 2:', nr_file_types[2]) print('Average length: {:.1f}'.format(total_length / nr_length_files)) print('--------------------------------------------------------------------------') print('Note on messages: ', sum(played_notes)) print('Note off messages: ', sum(note_offs)) print('Running status off: ', sum(running_status)) print('All notes off: ', sum(all_notes_off)) print('--------------------------------------------------------------------------') print('Channel activity distribution:') total_activity = sum(channel_activity) for i, act in enumerate(channel_activity): if act > 0: print('{:2d}: {:.1%} '.format(i + 1, act / total_activity)) print('--------------------------------------------------------------------------') print('Note distribution:') total_notes = sum(played_notes) for i, nt in enumerate(played_notes): if nt > 0: print('{:2d}: {:.2%} '.format(i, nt / total_notes)) print('--------------------------------------------------------------------------') # Visit files recursively from a root directory. def visitFilesRecursively(root_dir, extension, apply_func, verbose = True): base_dir = os.path.abspath(root_dir) for root, subdirs, files in os.walk(base_dir): if verbose: print('# Directory: ' + root) for filename in files: if os.path.splitext(filename)[1] == extension: if verbose: print(' - %s ' % (filename)) file_path = os.path.join(root, filename) res = apply_func(file_path) printMidiFileStatistics('/content/') #@title Time varying key of a MIDI file # Identifies the time varying key of a MIDI file # Hilary Mogul # [email protected] # May 2014 # Version 0.0.1 from pretty_midi import PrettyMIDI import numpy as np import midi import os import sys def make_chroma_vector(chroma_slice): """Returns chroma vector of sums from starting time to ending time""" chroma_vector = np.zeros((12,1)) chroma_vector[0] = np.sum(chroma_slice[11,]) for i in range(1,12): chroma_vector[i] = np.sum(chroma_slice[11-i]) return chroma_vector def get_approx_key(chroma_vector, keys): """Returns index of approximated key, and the score that this approximated key got""" chroma_vector = chroma_vector[:] scores = [] end = keys.shape[0] -1 for i in range(0,end): key_vector = keys[i,:] score = np.dot(key_vector,chroma_vector) scores.append(score) key_index = scores.index(max(scores)) arr = np.array([[key_index, max(scores)]]) return arr def get_key_score(chroma_vector, keys, key_index): """Returns the score of an approximated key, given the index of the key weights to try out""" chroma_vector = np.rot90(chroma_vector,3) chroma_vector = chroma_vector[0,:] key_vector = keys[key_index,:] score = np.dot(key_vector,chroma_vector) return score def load_keys(): """ Returns arrays of the weighted keys, and the corresponding names of them """ #Building of weighted vectors if not os.path.exists("key_base_info.npz"): print("Building default array- major keys only") key_weight = np.array([[ 3, -1, 1, -1, 2, 1, -1, 2, -1, 1, -1, 2]]) key_weight = np.vstack((key_weight,np.array([[2, 3, -1, 1, -1, 2, 1, -1, 2, -1, 1, -1]]))) key_weight = np.vstack((key_weight,np.array([[-1, 2, 3, -1, 1, -1, 2, 1, -1, 2, -1, 1]]))) key_weight = np.vstack((key_weight,np.array([[1, -1, 2, 3, -1, 1, -1, 2, 1, -1, 2, -1]]))) key_weight = np.vstack((key_weight,np.array([[-1, 1, -1, 2, 3, -1, 1, -1, 2, 1, -1, 2]]))) key_weight = np.vstack((key_weight,np.array([[2, -1, 1, -1, 2, 3, -1, 1, -1, 2, 1, -1]]))) key_weight = np.vstack((key_weight,np.array([[-1, 2, -1, 1, -1, 2, 3, -1, 1, -1, 2, 1]]))) key_weight = np.vstack((key_weight,np.array([[1, -1, 2, -1, 1, -1, 2, 3, -1, 1, -1, 2]]))) key_weight = np.vstack((key_weight,np.array([[2, 1, -1, 2, -1, 1, -1, 2, 3, -1, 1, -1]]))) key_weight = np.vstack((key_weight,np.array([[-1, 2, 1, -1, 2, -1, 1, -1, 2, 3, -1, 1]]))) key_weight = np.vstack((key_weight,np.array([[1, -1, 2, 1, -1, 2, -1, 1, -1, 2, 3, -1]]))) key_weight = np.vstack((key_weight,np.array([[-1, 1, -1, 2, 1, -1, 2, -1, 1, -1, 2, 3]]))) names = np.array([['C-Maj', 'C#-Maj', 'D-Maj', 'D#-Maj', 'E-Maj', 'F-Maj','F#-Maj','G-Maj','G#-Maj', 'A-Maj', 'A#-Maj','B-Maj']]) np.savez("key_base_info", key_weight, names) npzfile = np.load("key_base_info.npz") key_weight = npzfile['arr_0'] names = npzfile['arr_1'] #vector of key names (This version will use only major keys) return key_weight, names #Main function of program: def identify_key(midi_filename, command_line_print = True, save_results = True, measure_value = 1): """ Runs key identification algorithm :parameters: - midi_filename : String of name of existing midi file to process. - command_line_print : Boolean to allow for printing results to command line. - save_results : Boolean to allow saving the approximated key and the names of those keys to a .npz file matching the midi files name - measure_value : int > 0 that sets how many beats the program will process per approximation. """ song = PrettyMIDI((midi_filename)) #get beat locations for slices beats = song.get_beats() #output is an np.ndarray times = beats.flatten() sectionBeats = True #create slices of chroma data to process including summing them up #output: every "measure" of beats if measure_value< 1 or measure_value >times.size or measure_value == None: sectionBeats = False print ("WARNING: measure_value selected less than 1 or greater than beat size. Will do one approximation for the whole song.") key_weight, names = load_keys() #get Chroma features chroma = song.get_chroma() #normalize chroma features chroma /= (chroma.max( axis = 0 ) + (chroma.max( axis = 0 ) == 0)) # first case if sectionBeats: chroma_slice = chroma[:,0:round(times[0])*100] else: chroma_slice = chroma # Sum rows to find intensity of each note. vec = np.sum(chroma_slice, axis=1) keys_approx = get_approx_key(vec, key_weight) #for each slice, get approximated key and score into 2 column array (key, score) #possiblymay need to use indices of key names instead of actual keys #chroma time indices have a resolution of 10 ms times_used = np.array([[times[0]]]) if sectionBeats: for t in range(1, times.size-1,measure_value): #make chroma slice based on time if times.size -t < measure_value: chroma_slice = chroma[:,round(times[t]*100):round(times[t+1]*100)] # print chroma_slice # vec = make_chroma_vector(chroma_slice) vec = np.sum(chroma_slice, axis=1) # vec = vec[::-1] else: chroma_slice = chroma[:,round(times[t]*100):round(times[t+1]*100)] # print chroma_slice # vec = make_chroma_vector(chroma_slice) vec = np.sum(chroma_slice, axis=1) # vec = vec[::-1] apr = get_approx_key(vec, key_weight) #if the score isn't 0 (which happens in silence), add the approximated key to the list if not apr[0,1] == 0: keys_approx = np.vstack((keys_approx, apr)) times_used = np.vstack((times_used, np.array([[times[t]]]))) # DUMMIED OUT CODE FOR FUTURE IMPLEMENTATION # final_keys = np.array([ [ keys_approx[0,0],times[0,0] ] ]) #mark first # print final_keys # # #iterate through rows of array- if there is a change, get % difference in scores for each key and use threshold to figure # #if it is a key change. mark key change in final 2 column array of (key, time start) # threshold = .15 #experimental value # # if times.size > 1: # print "going thru removal loop" # for t in range (1, keys_approx.shape[0]): # current = keys_approx[t,0] # prev = keys_approx[t-1,0] # if not current == prev: #if not equal to previous, check % difference of scores # print "In key change check" # score1 = keys_approx[t,1] #score of key of this time slice # # print score1 # vec = make_chroma_vector(chroma, round(times[0,t])*100,round(times[0,t+1])*100 ) # # print vec # score2 = get_key_score(vec, key_weight, prev) #score it would have gotten with last input key # # print score2 # diff = abs(score1-score2)/(score1+score2) # print diff # if diff > threshold: # arr = np.array([[keys_approx[t,0], times[t,0] ]]) # # print arr # print "Key change at index: ", times[t,0] # final_keys = np.vstack((final_keys, arr)) # else: # print "difference not large enough to constitute key change " #keys_approx = final_keys e = keys_approx.shape[0] if command_line_print: for i in range(0, e): key_int = int(keys_approx[i,0]) print("In key: ",names[0,key_int],"at time: ", times_used[i,0]) if save_results: filename = os.path.basename(midi_filename) filename_raw = os.path.splitext(filename)[0] # if not os.path.exists(directory): dirname = "Results_of_key_approximation" if not os.path.exists(dirname): os.makedirs(dirname) np.savez(dirname+"/"+filename_raw+"_key_approx-vars", keys_approx = keys_approx, names = names) file_results = open(dirname+"/"+filename_raw+"_key_approx-text_form.txt",'w') file_results.write(filename_raw+"\n") for i in range(0, e): key_int = int(keys_approx[i,0]) file_results.write("In key: "+names[0,key_int]+" at time: "+ str(times_used[i,0])+"\n") file_results.close() return keys_approx, names x = identify_key(MIDI_file_to_analyze) #@title Detailed chords analysis %cd /content/ # https://github.com/realbchan/MidiAnalysis import bisect from collections import defaultdict import matplotlib.pyplot as plt import numpy as np class Utils: # initialize, build mapping from a note number to a note letter def __init__(self): self.number_to_letter_mappings = dict() self.pattern = ['A', 'A#/Bb', 'B', 'C', 'C#/Db', 'D', 'D#/Eb', 'E', 'F', 'F#/Gb', 'G', 'G#/Ab'] self.build_number_letter_mapping() # this method maps a number to a note letter and it's octave # notes on my keyboard is from note=21 to note=108 == 88 keys # I dont think the piano can represent anything out of this range def build_number_letter_mapping(self): octave = 0 for num_note in range(21, 109): letter = self.pattern[(num_note - 21) % len(self.pattern)] if letter == 'C': octave += 1 note = (self.pattern[(num_note - 21) % len(self.pattern)], octave) self.number_to_letter_mappings[num_note] = note # get method, retrieve note letter from note number def note_number_to_letter(self, num_note): return self.number_to_letter_mappings[num_note] # each note or chord is considered a "Tone" # This is the parent class for Note and Chord class Tone: def __init__(self): # this threshold limit determines how "close" # a note is to another note in seconds, this can be tuned self.threshold_limit = .25 def is_note(self): return False def is_chord(self): return False # must be implemented in Note and Chord def is_close(self, other_note): raise NotImplementedError("To be implemented") # I define a Note to be a single musical note played # If there are 1 or 2 notes "close" by, it is considered a Chord class Note(Tone): # takes in parameters from message, calculates duration def __init__(self, absoluteStart, absoluteStop, notePlayed, velocityStart, velocityStop): super().__init__() self.absoluteStart = absoluteStart self.absoluteStop = absoluteStop self.duration = self.absoluteStop - self.absoluteStart self.notePlayed = notePlayed self.velocityStart = velocityStart self.velocityStop = velocityStop # def __key(self): # return (self.notePlayed[0], self.notePlayed[1]) # def __hash__(self): # return hash(self.__key()) def __lt__(self, other_note): note_letter, note_octave = self.notePlayed[0], self.notePlayed[1] other_note_letter, other_note_octave = other_note.notePlayed[0], other_note.notePlayed[1] if note_octave < other_note_octave: return True elif note_octave == other_note_octave: return other_note_letter < note_letter else: return False def __str__(self): return str(self.notePlayed) def __repr__(self): return self.__str__() def is_note(self): return True # uses self.threshold to determine if a note is close def is_close(self, other_note): start_difference = abs(self.absoluteStart - other_note.absoluteStart) stop_difference = abs(self.absoluteStop - other_note.absoluteStop) if start_difference <= self.threshold_limit and stop_difference <= self.threshold_limit: return True return False # a chord is considered 1 or 2 notes that are close by class Chord(Tone): # we need to keep track of the average parameters of a chord def __init__(self): super().__init__() self.notes_in_chord = tuple() self.num_chords = 0 self.average_duration = 0 self.average_start_time = 0 self.average_stop_time = 0 def __str__(self): return str(self.notes_in_chord) # def __key(self): # return tuple(note.__hash__() for note in self.notes_in_chord) # def __hash__(self): # return hash(self.__key()) def is_chord(self): return True # on adding a note, recalculate averages def add_note(self, note): self.average_duration = self.get_new_average(self.average_duration, note.duration) self.average_start_time = self.get_new_average(self.average_start_time, note.absoluteStart) self.average_stop_time = self.get_new_average(self.average_stop_time, note.absoluteStop) self.num_chords += 1 note_letter, note_octave = note.notePlayed list_notes_in_chord = list(self.notes_in_chord) if len(self.notes_in_chord) > 0: bisect.insort_left(list_notes_in_chord, note) else: list_notes_in_chord.append(note) self.notes_in_chord = tuple(list_notes_in_chord) # print(self.notes_in_chord) # calculate new arbitrary average def get_new_average(self, previous_cumulation, next_number): previous_sum = previous_cumulation * self.num_chords current_sum = previous_sum + next_number return current_sum / (self.num_chords + 1) # similar to is_close for Note def is_close(self, other_note): start_difference = abs(self.average_start_time - other_note.absoluteStart) stop_difference = abs(self.average_stop_time - other_note.absoluteStop) if start_difference <= self.threshold_limit and stop_difference <= self.threshold_limit: return True return False # a Song is a list of Tones # it represents a midi track as a whole class Song: def __init__(self): self.tones = list() def __str__(self): return ''.join(str(tone) for tone in self.tones) # sorts tones by start def sort_by_start_of_tone(self): # sorting comparator, probably could refactor def get_start(tone): if tone.is_note(): return tone.absoluteStart else: return tone.average_start_time self.tones.sort(key=get_start) # add note to song, will detect if needs to make a chord def add_note(self, note): if len(self.tones) == 0: self.tones.append(note) else: for previous_tone in self.tones[::-1]: # retrieve previous tone's end, chord or note previous_tone_end = None if previous_tone.is_chord(): previous_tone_end = previous_tone.average_stop_time else: previous_tone_end = previous_tone.absoluteStop # check if the previous' end time is close to current note # if it's not in threshold, this is just a singular note if abs(previous_tone_end - note.absoluteStop) <= note.threshold_limit: # current note's end is close to previous end, check if both start # and end are close if previous_tone.is_close(note): # in the event that we need to make a new chord, # we need to save the index of the previous_tone, #create a chord, and insert it back to original position if previous_tone.is_note(): chord = Chord() chord.add_note(previous_tone) chord.add_note(note) saveIndex = self.tones.index(previous_tone) self.tones.pop(saveIndex) self.tones.insert(saveIndex, chord) break else: previous_tone.add_note(note) break continue else: self.tones.append(note) break class ToneFrequency: def __init__(self, song): self.song = song self.frequency_of_all_notes = self.get_all_note_frequency() self.frequency_of_only_chords = self.get_frequency_only_chords() self.plot_get_frequency_only_chords() def get_all_note_frequency(self): frequencies = defaultdict(int) for tone in self.song.tones: if tone.is_note(): frequencies[tone.notePlayed] += 1 else: for note in tone.notes_in_chord: frequencies[note.notePlayed] += 1 return frequencies def get_frequency_only_chords(self): frequencies = defaultdict(int) for tone in self.song.tones: if tone.is_chord(): notes = tuple(note.notePlayed for note in tone.notes_in_chord) frequencies[notes] += 1 return frequencies def plot_get_frequency_only_chords(self): D = self.frequency_of_only_chords plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) # # for python 2.x: # plt.bar(range(len(D)), D.values(), align='center') # python 2.x # plt.xticks(range(len(D)), D.keys()) # in python 2.x plt.show() from mido import MidiFile from mido.midifiles.units import tempo2bpm, bpm2tempo, tick2second, second2tick # from midiUtils import Utils, Tone, Note, Chord, Song #from toneFrequency import ToneFrequency util = Utils() mid = MidiFile(MIDI_file_to_analyze) # mid = MidiFile('./whenTheSaintsLeftHandMelody/wtsgmi5.mid') print((mid.ticks_per_beat)) # print(mid.ticks_per_beat, 1000) # print(mid.tracks) # exit() tempoPerMinute = 500000 totalNotes = list() song = Song() for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) cumulative_time = 0 currently_played_notes = dict() for msg in track: try: if not msg.is_meta: cumulative_time += tick2second(msg.time, mid.ticks_per_beat, tempoPerMinute) message_note = util.note_number_to_letter(msg.note) if message_note in currently_played_notes: absoluteStart, velocityStart = currently_played_notes.pop(message_note) note = Note(absoluteStart, cumulative_time, message_note, velocityStart, msg.velocity) song.add_note(note) else: currently_played_notes[message_note] = (cumulative_time, msg.velocity) except: continue # print(len(song.tones)) # song.sort_by_start_of_tone() for tone in song.tones: print(tone) frequencies = ToneFrequency(song) print(frequencies.frequency_of_all_notes) print(frequencies.frequency_of_only_chords) #@title Pydot Graph pattern = midi.read_midifile(MIDI_file_to_analyze) notes = {NOTE_NAME_MAP_SHARP[name]: name.replace('s', '#').replace('_', '') for name in NOTE_NAME_MAP_SHARP} l = pattern[0] tracks = [] for track in pattern: x = list() y = list() t = 0 for ev in track: t += ev.tick if type(ev) == midi.events.NoteOnEvent: pitch, vel = ev.data if vel > 0: y.append(pitch) x.append(t) if len(x) > 0: tracks.append((x, y)) colors = ['orange', 'green', 'red'] n = 0 for track in tracks: G = nx.DiGraph() for i in range(len(track[1])-1): G.add_edge(notes[track[1][i]], notes[track[1][i+1]], color=colors[n]) G.add_node(notes[track[1][i]], color=colors[n]) G.add_node(notes[track[1][i+1]], color=colors[n]) nx.drawing.nx_pydot.write_dot(G, "g%s.dot" % n) n += 1 nx.draw_networkx(G) #plt.figure(figsize=(19, 10), dpi=300) plt.savefig('Dot_Graph.jpg') #@title Generate and plot MIDI file's Parson's code and contour. length_of_the_code_and_contour_in_notes = 70 #@param {type:"slider", min:10, max:2000, step:10} code_and_contour_start_offset_in_notes = 0 #@param {type:"slider", min:0, max:1000, step:10} #!/usr/bin/env python # https://github.com/snus-kin/parsons-code """ Take a midi file and convert it to parsons code, with a limit and offset """ def midi_to_parsons(midifile, limit=code_and_contour_start_offset_in_notes + length_of_the_code_and_contour_in_notes, offset=code_and_contour_start_offset_in_notes): """ Input: midifile (string) = A midi file path limit (int) = How long is the parsons code offset (int) = How many notes in do we start Output: parsons (string) = A string containing a parsons code length limit at an offset from the start of the file """ count = 0 parsons = "" for message in mido.MidiFile(midifile): if "note_on" in str(message) and offset == 0: if parsons == "": # initialise list prev = message.note parsons += "*" # simple comparison elif message.note > prev: parsons += "U" prev = message.note elif message.note < prev: parsons += "D" prev = message.note elif message.note == prev: parsons += "R" prev = message.note #increment count count += 1 if count >= limit: break elif "note_on" in str(message): offset -= 1 return parsons code = midi_to_parsons(MIDI_file_to_analyze) #print(code) """ Parsons code to contour plot """ def contour(code): print('Song Parson Code is:') print(code) print('') if code[0] != "*": raise ValueError("Parsons Code must start with '*'") contour_dict = {} pitch = 0 index = 0 maxp = 0 minp = 0 contour_dict[(pitch, index)] = "*" for point in code: if point == "R": index += 1 contour_dict[(pitch, index)] = "-" index += 1 contour_dict[(pitch, index)] = "*" elif point == "U": index += 1 pitch -= 1 contour_dict[(pitch, index)] = "/" index += 1 pitch -= 1 contour_dict[(pitch, index)] = "*" if pitch < maxp: maxp = pitch elif point == "D": index += 1 pitch += 1 contour_dict[(pitch, index)] = "\\" index += 1 pitch += 1 contour_dict[(pitch, index)] = "*" if pitch > minp: minp = pitch for pitch in range(maxp, minp+1): line = [" " for _ in range(index + 1)] for pos in range(index + 1): if (pitch, pos) in contour_dict: line[pos] = contour_dict[(pitch, pos)] print("".join(line)) contour(code) ###Output _____no_output_____
Lectures notebooks/(Lectures notebooks) coursera Mathematics and Python/12.sample distribution evaluation/sample_distribution_evaluation.ipynb
###Markdown Дискретное распределение Сгенерируем выборку объёма 100 из дискретного распределения с шестью равновероятными исходами. ###Code sample = np.random.choice([1,2,3,4,5,6], 100) ###Output _____no_output_____ ###Markdown Представим теперь, что эта выборка была получена не искусственно, а путём подбрасывания симметричного шестигранного кубика 100 раз. Оценим вероятности выпадения каждой из сторон с помощью частот: ###Code # посчитаем число выпадений каждой из сторон: from collections import Counter c = Counter(sample) print("Число выпадений каждой из сторон:") print(c) # теперь поделим на общее число подбрасываний и получим вероятности: print("Вероятности выпадений каждой из сторон:") print({k: v/100.0 for k, v in c.items()}) ###Output Число выпадений каждой из сторон: Counter({1: 24, 2: 17, 4: 16, 3: 15, 5: 15, 6: 13}) Вероятности выпадений каждой из сторон: {1: 0.24, 2: 0.17, 3: 0.15, 4: 0.16, 5: 0.15, 6: 0.13} ###Markdown Это и есть оценка функции вероятности дискретного распределения. Непрерывное распределение Сгенерируем выборку объёма 100 из стандартного нормального распределения (с $\mu=0$ и $\sigma^2=1$): ###Code norm_rv = sts.norm(0, 1) sample = norm_rv.rvs(100) ###Output _____no_output_____ ###Markdown Эмпирическая функция распределения для полученной выборки: ###Code x = np.linspace(-4,4,100) cdf = norm_rv.cdf(x) plt.plot(x, cdf, label='theoretical CDF') # для построения ECDF используем библиотеку statsmodels from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(sample) plt.step(ecdf.x, ecdf.y, label='ECDF') plt.ylabel('$f(x)$') plt.xlabel('$x$') plt.legend(loc='upper left') ###Output _____no_output_____ ###Markdown Гистограмма выборки: ###Code plt.hist(sample, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$') ###Output _____no_output_____ ###Markdown Попробуем задавать число карманов гистограммы вручную: ###Code plt.hist(sample, bins=3, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$') plt.hist(sample, bins=40, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$') ###Output _____no_output_____ ###Markdown Эмпирическая оценка плотности, построенная по выборке с помощью ядерного сглаживания: ###Code # для построения используем библиотеку Pandas: df = pd.DataFrame(sample, columns=['KDE']) ax = df.plot(kind='density') # на том же графике построим теоретическую плотность распределения: x = np.linspace(-4,4,100) pdf = norm_rv.pdf(x) plt.plot(x, pdf, label='theoretical pdf', alpha=0.5) plt.legend() plt.ylabel('$f(x)$') plt.xlabel('$x$') ###Output _____no_output_____
projects/TwoStream/notebooks/vae_inference.ipynb
###Markdown Inference/Sampling of the Image and Mask VAEs ###Code import numpy as np import torch import torch.nn as nn from matplotlib import pyplot as plt from connectomics.data.utils import readh5 from connectomics.config import get_cfg_defaults import sys sys.path.append("../") from twostream.vae import VAE from twostream.config import add_twostream_config from twostream.dataset import VolumeDatasetCenterPatch from twostream.utils import collate_fn_patch # Load configs and build model cfg_base = '../configs/JWR15/JWR15-VAE-2D-Base.yaml' cfg_file_img = '../configs/JWR15/JWR15-VAE-2D-Image.yaml' cfg_file_mask = '../configs/JWR15/JWR15-VAE-2D-Mask.yaml' def get_config(cfg_base, cfg_file): cfg = get_cfg_defaults() add_twostream_config(cfg) cfg.merge_from_file(cfg_base) cfg.merge_from_file(cfg_file) return cfg cfg_img = get_config(cfg_base, cfg_file_img) cfg_mask = get_config(cfg_base, cfg_file_mask) from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid def show(image, cmap='viridis', title='Test Title', interpolation=None): num_imgs = image.shape[-3] # c (optional), z, y, x fig = plt.figure(figsize=(20., 3.)) fig.suptitle(title, fontsize=14) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols=(1, num_imgs), # creates 2x2 grid of axes axes_pad=0.1, # pad between axes in inch. ) image_list = np.split(image, num_imgs, -3) for ax, im in zip(grid, [np.squeeze(x) for x in image_list]): # Iterating over the grid returns the Axes. if im.ndim == 3: im = im.transpose(1,2,0) ax.imshow(im, cmap=cmap, interpolation=interpolation) ax.axis('off') plt.show() def build_model(cfg, device, checkpoint): kwargs = { # defaults in pytorch-connectomics "img_channels": cfg.MODEL.IN_PLANES, "act_mode": cfg.MODEL.ACT_MODE, "norm_mode": cfg.MODEL.NORM_MODE, # unique ones in two-stream project "latent_dim": cfg.TWOSTREAM.LATENT_DIM, "hidden_dims": cfg.TWOSTREAM.HIDDEN_DIMS, "width": cfg.TWOSTREAM.WIDTH, } model = VAE(**kwargs) gpu_device_ids = list(range(torch.cuda.device_count())) model = nn.DataParallel(model, device_ids=gpu_device_ids) model = model.to(device) checkpoint = torch.load(checkpoint) model.module.load_state_dict(checkpoint['state_dict']) return model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") vae_img = build_model(cfg_img, device, "../../../outputs/JWR15_Syn_VAE_Image/checkpoint_400000.pth.tar") vae_mask = build_model(cfg_mask, device, "../../../outputs/JWR15_Syn_VAE_Mask/checkpoint_400000.pth.tar") ###Output _____no_output_____ ###Markdown 1. Random Sampling ###Code with torch.no_grad(): sampled_img = vae_img.module.sample(10, device) sampled_mask = vae_mask.module.sample(10, device) show(sampled_img.cpu().numpy().transpose(1,0,2,3), title=None, cmap='gray') show(sampled_mask.cpu().numpy().transpose(1,0,2,3), title=None, cmap='gray') ###Output _____no_output_____ ###Markdown 2. Inference and Interpolation ###Code # load volumes img = readh5("../../../datasets/synapse/img.h5") syn = readh5("../../../datasets/synapse/syn.h5") ds = VolumeDatasetCenterPatch([syn], [img], label_type='syn', sample_size=128, mode='test') loader = torch.utils.data.DataLoader(ds, batch_size=10, shuffle=False, pin_memory=False, collate_fn=collate_fn_patch, num_workers=1) loader = iter(loader) sample = next(loader) img, seg = sample.img, sample.seg show(img.numpy().transpose(1,0,2,3), title=None, cmap='gray') show(seg.numpy().transpose(1,0,2,3), title=None, cmap='gray') with torch.no_grad(): mu, log_var = vae_img.module.encode(img.to(device)) print(f"Shape of the image embedding: {mu.shape}") result = vae_img.module.decode(mu).detach().cpu() show(result.numpy().transpose(1,0,2,3), title=None, cmap='gray') mu, log_var = vae_mask.module.encode(seg.to(device)) print(f"Shape of the mask embedding: {mu.shape}") result = vae_mask.module.decode(mu).detach().cpu() show(result.numpy().transpose(1,0,2,3), title=None, cmap='gray') def interpolate(start, end, model): weights = np.linspace(0.0, 1.0, 10) with torch.no_grad(): mu1, _ = model.module.encode(start) mu2, _ = model.module.encode(end) interpolated = [(1.0-a)*mu1 + a*mu2 for a in weights] interpolated = torch.cat(interpolated, 0) result = model.module.decode(interpolated).detach().cpu() show(result.numpy().transpose(1,0,2,3), title=None, cmap='gray') interpolate(img[0:1].to(device), img[1:2].to(device), vae_img) interpolate(seg[1:2].to(device), seg[4:5].to(device), vae_mask) ###Output _____no_output_____
python/algorithms/tree.ipynb
###Markdown Tree Data Structure Tree TraversalResources:- [Blog: Demystifying Depth-First Search](https://medium.com/basecs/demystifying-depth-first-search-a7c14cccf056)- [Blog: Breaking Down Breadth-First Search](https://medium.com/basecs/breaking-down-breadth-first-search-cebe696709d9) SummaryThere are two main ways to traverse through a tree. By traversing, we essentially mean we try to walk through the tree without repeating ourselves.- For **depth first search (DFS)**, we start down a path and we won't stop until we get to the end. In other words, we traverse through one branch of the tree until we get to a leaf and only then will we work back up to the trunk of the tree.- In **breadth first search (BFS)**, we would search through the nodes from one level to the next, and traverse through all the children of a node before moving on to visit the grandchildren nodes ImplementationResources:- [Blog: How to Implement Breadth-First Search in Python](https://pythoninwonderland.wordpress.com/2017/03/18/how-to-implement-breadth-first-search-in-python/)- [Blog: Depth-First Search and Breadth-First Search in Python](http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/)From an implementation standpoint, the difference between the two is that the breadth first search uses a queue, while depth first search uses a stack.**Breadth First Search (BFS)**We will use a graph that has 7 nodes and 7 edges as our example. The edges are undirected and unweighted. Distance between two nodes will be measured based on the number of edges separating two vertices.When using BFS to traverse through all the nodes in the graph, the algorithm follows the following steps:- Check the starting node and add its neighbours to the queue.- Mark the starting node as explored.- Get the first node from the queue / remove it from the queue.- Check if node has already been visited.- If not, go through the neighbours of the node.- Add the neighbour nodes to the queue.- Mark the node as explored.- Loop through steps 3 to 7 until the queue is empty. ###Code # adjacency list can be efficiently represented as # a python dictionary, where the nodes are the keys # and the nodes that they are connected to are stored # as a list of values graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} from collections import deque def bfs(graph, start): """Graph traversal using Breadth First Searh""" # keep track of all visited nodes visited = set() # keep track nodes to be checked queue = deque(start) while queue: node = queue.popleft() if node not in visited: visited.add(node) neighbors = graph[node] for neighbor in neighbors: queue.append(neighbor) return visited start = 'A' bfs(graph, start) ###Output _____no_output_____ ###Markdown For depth first search, the list of actions to perform upon each visit to a node:- Mark the current vertex as being visited.- Explore each adjacent vertex that is not included in the visited set. ###Code def dfs(graph, start): """Graph traversal using Depth First Searh""" visited = set() stack = [start] while stack: node = stack.pop() if node not in visited: visited.add(node) neighbors = graph[node] for neighbor in neighbors: stack.append(neighbor) return visited start = 'A' dfs(graph, start) ###Output _____no_output_____
notebooks/SU-2015-7-LogistickaRegresija.ipynb
###Markdown Sveučilište u ZagrebuFakultet elektrotehnike i računarstva Strojno učenjehttp://www.fer.unizg.hr/predmet/suAk. god. 2015./2016. Bilježnica 7: Logistička regresija(c) 2015 Jan ŠnajderVerzija: 0.2 (2015-11-16) ###Code import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt import pandas as pd %pylab inline ###Output Populating the interactive namespace from numpy and matplotlib ###Markdown Sadržaj:* Model logističke regresije* Gubitak unakrsne entropije* Minimizacija pogreške* Poveznica s generativnim modelom* Usporedba linearnih modela* Sažetak Model logističke regresije Podsjetnik: poopćeni linearni modeli$$h(\mathbf{x}) = \color{red}{f\big(}\mathbf{w}^\intercal\tilde{\mathbf{x}}\color{red}{\big)}$$* $f : \mathbb{R}\to[0,1]$ ili $f : \mathbb{R}\to[-1,+1]$ je **aktivacijska funkcija*** Linearna granica u ulaznom prostoru (premda je $f$ nelinearna) * Međutim, ako preslikavamo s $\boldsymbol\phi(\mathbf{x})$ u prostor značajki, granica u ulaznom prostoru može biti nelinearna* Model nelinearan u parametrima (jer je $f$ nelinearna) * Komplicira optimizaciju (nema rješenja u zatvorenoj formi) Podsjetnik: klasifikacija regresijom* Model:$$ h(\mathbf{x}) = \mathbf{w}^\intercal\boldsymbol{\phi}(\mathbf{x}) \qquad (f(\alpha)=\alpha)$$* [Skica]* Funkcija gubitka: kvadratni gubitak* Optimizacijski postupak: izračun pseudoinverza (rješenje u zatvorenoj formi)* Prednosti: * Uvijek dobivamo rješenje * Nedostatci: * Nerobusnost: ispravno klasificirani primjeri utječu na granicu $\Rightarrow$ pogrešna klasifikacija čak i kod linearno odvojivih problema * Izlaz modela nije probabilistički Podsjetnik: perceptron* Model:$$h(\mathbf{x}) = f\big(\mathbf{w}^\intercal\boldsymbol\phi(\mathbf{x})\big)\qquad f(\alpha) = \begin{cases}+1 & \text{ako $\alpha\geq0$}\\-1 & \text{inače}\end{cases}$$* [Skica]* Funkcija gubitka: količina pogrešne klasifikacije $$\mathrm{max}(0,-\tilde{\mathbf{w}}^\intercal\boldsymbol{\phi}(\mathbf{x})y)$$* Optimizacijski postupak: gradijentni spust* Prednosti: * Ispravno klasificirani primjeri ne utječu na granicu $\Rightarrow$ ispravna klasifikacija linearno odvojivih problema* Nedostatci: * Aktivacijska funkcija nije derivabilna $\Rightarrow$ funkcija gubitka nije derivabilna $\Rightarrow$ gradijent funkcije pogreške nije nula u točki minimuma $\Rightarrow$ postupak ne konvergira ako primjeri nisu linearno odvojivi * Decizijska granica ovisi o početnom izboru težina * Izlaz modela nije probabilistički Logistička regresija* Ideja: upotrijebiti aktivacijsku funkciju s izlazima $[0,1]$ ali koja jest derivabilna* **Logistička (sigmoidalna) funkcija**:$$ \sigma(\alpha) = \frac{1}{1 + \exp(-\alpha)}$$ ###Code def sigm(x): return 1 / (1 + sp.exp(-x)) xs = sp.linspace(-10, 10) plt.plot(xs, sigm(xs)); ###Output _____no_output_____ ###Markdown * Nagib sigmoide može se regulirati množenjem ulaza određenim faktorom: ###Code plt.plot(xs, sigm(0.5*xs), 'r'); plt.plot(xs, sigm(xs), 'g'); plt.plot(xs, sigm(2*xs), 'b'); ###Output _____no_output_____ ###Markdown * Derivacija sigmoidalne funkcije: $$\frac{\partial\sigma(\alpha)}{\partial\alpha} = \frac{\partial}{\partial\alpha}\big(1 + \exp(-\alpha)\big) =\sigma(\alpha)\big(1 - \sigma(\alpha)\big)$$ * Model **logističke regresije**:$$ h(\mathbf{x}|\mathbf{w}) = \sigma\big(\mathbf{w}^\intercal\boldsymbol{\phi}(\mathbf{x})\big) = \frac{1}{1+\exp(-\mathbf{w}^\intercal\boldsymbol{\phi}(\mathbf{x}))}$$* **NB:** Logistička regresija je klasifikacijski model (unatoč nazivu)! Probabilistički izlaz* $h(\mathbf{x})\in[0,1]$, pa $h(\mathbf{x})$ možemo tumačiti kao **vjerojatnost** da primjer pripada klasi $\mathcal{C}_1$ (klasi za koju $y=1$):$$h(\mathbf{x}|\mathbf{w}) = \sigma\big(\mathbf{w}^\intercal\mathbf{\phi}(\mathbf{x})\big) = \color{red}{P(y=1|\mathbf{x})}$$* Vidjet ćemo kasnije da postoji i dublje opravdanje za takvu interpretaciju Funkcija logističkog gubitka* Definirali smo model, trebamo još definirati **funkciju gubitka** i **optimizacijski postupak*** Logistička funkcija koristi **gubitak unakrsne entropije** Definicija* Funkcija pokriva dva slučajeva (kada je oznaka primjera $y=1$ i kada je $y=0$):$$L(h(\mathbf{x}),y) =\begin{cases}- \ln h(\mathbf{x}) & \text{ako $y=1$}\\- \ln \big(1-h(\mathbf{x})\big) & \text{ako $y=0$}\end{cases}$$* Ovo možemo napisati sažetije:$$L(h(\mathbf{x}),y) = - y \ln h(\mathbf{x}) - (1-y)\ln \big(1-h(\mathbf{x})\big)$$ ###Code xs = linspace(0, 1) plt.plot(xs, -sp.log(xs)); plt.plot(xs, 1 - sp.log(1 - xs)); ###Output _____no_output_____ ###Markdown * Ako $y=1$, funkcija kažnjava model to više što je njegov izlaz manji od jedinice. Slično, ako $y=0$, funkcija kažnjava model to više što je njegov izlaz veći od nule* Intutivno se ovakva funkcija čini u redu, ali je pitanje kako smo do nje došli Izvod* Funkciju gubitka izvest ćemo iz **funkcije pogreške** * Podsjetnik: funkcija pogreške = očekivanje funkcije gubitka * Budući da logistička regresija daje vjerojatnosti oznaka za svaki primjer, možemo izračunati kolika je vjerojatnost označenog skupa primjera $\mathcal{D}$ pod našim modelom, odnosno kolika je izglednost parametra $\mathbf{w}$ modela* Želimo da ta izglednost bude što veća, pa ćemo funkciju pogreške definirati kao **negativnu log-izglednost** parametara $\mathbf{w}$:$$E(\mathbf{w}|\mathcal{D}) = -\ln\mathcal{L}(\mathbf{w}|\mathcal{D})$$* Želimo maksimizirati log-izglednost, tj. minimizirati ovu pogrešku* Log-izglednost:$$\begin{align*}\ln\mathcal{L}(\mathbf{w}|\mathcal{D})&= \ln p(\mathcal{D}|\mathbf{w})= \ln\prod_{i=1}^N p(\mathbf{x}^{(i)}, y^{(i)}|\mathbf{w})\\&= \ln\prod_{i=1}^N P(y^{(i)}|\mathbf{x}^{(i)},\mathbf{w})p(\mathbf{x}^{(i)})\\&= \sum_{i=1}^N \ln P(y^{(i)}|\mathbf{x}^{(i)},\mathbf{w}) + \underbrace{\color{gray}{\sum_{i=1}^N \ln p(\mathbf{x}^{(i)})}}_{\text{ne ovisi o $\mathbf{w}$}}\end{align*}$$* $y^{(i)}$ je oznaka $i$-tog primjera koja može biti 0 ili 1 $\Rightarrow$ **Bernoullijeva varijabla*** Budući da $y^{(i)}$ Bernoullijeva varijabla, njezina distribucija je:$$P(y^{(i)}) = \mu^{y^{(i)}}(1-\mu)^{y^{(i)}}$$gdje je $\mu$ vjerojatnost da $y^{(i)}=1$* Naš model upravo daje vjerojatnost da primjer $\mathcal{x}^{(i)}$ ima oznaku $y^{(i)}=1$, tj.:$$\mu = P(y^{(i)}=1|\mathbf{x}^{(i)},\mathbf{w}) = \color{red}{h(\mathbf{x}^{(i)} | \mathbf{w})}$$* To znači da vjerojatnost oznake $y^{(i)}$ za dani primjer $\mathbf{x}^{i}$ možemo napisati kao:$$P(y^{(i)}|\mathbf{x}^{(i)},\mathbf{w}) = \color{red}{h(\mathbf{x}^{(i)}|\mathbf{w})}^{y^{(i)}}\big(1-\color{red}{h(\mathbf{x}^{(i)}|\mathbf{w})}\big)^{1-y^{(i)}}$$* Nastavljamo s izvodom log-izglednosti:$$\begin{align*}\ln\mathcal{L}(\mathbf{w}|\mathcal{D}) &= \sum_{i=1}^N \ln P(y^{(i)}|\mathbf{x}^{(i)},\mathbf{w}) \color{gray}{+ \text{konst.}}\\&\Rightarrow \sum_{i=1}^N\ln \Big(h(\mathbf{x}^{(i)}|\mathbf{w})^{y^{(i)}}\big(1-h(\mathbf{x}^{(i)}|\mathbf{w})\big)^{1-y^{(i)}}\Big) \\& = \sum_{i=1}^N \Big(y^{(i)} \ln h(\mathbf{x}^{(i)}|\mathbf{w})+ (1-y^{(i)})\ln\big(1-h(\mathbf{x}^{(i)}|\mathbf{w})\big)\Big)\end{align*}$$* Empirijsku pogrešku definiramo kao negativnu log-izglednost (do na konstantu):$$E(\mathbf{w}|\mathcal{D}) = \sum_{i=1}^N \Big(-y^{(i)} \ln h(\mathbf{x}^{(i)}|\mathbf{w}) - (1-y^{(i)})\ln \big(1-h(\mathbf{x}^{(i)}|\mathbf{w})\big)\Big)$$* Alternativno (kako ne bi ovisila o broju primjera):$$E(\mathbf{w}|\mathcal{D}) = \color{red}{\frac{1}{N}} \sum_{i=1}^N\Big( - y^{(i)} \ln h(\mathbf{x}^{(i)}|\mathbf{w})- (1-y^{(i)})\ln \big(1-h(\mathbf{x}^{(i)}|\mathbf{w})\big)\Big)$$$\Rightarrow$ **pogreška unakrsne entropije** (engl. *cross-entropy error*)* Iz pogreške možemo iščitati funkciju gubitka:$$L(h(\mathbf{x}),y) = - y \ln h(\mathbf{x}) - (1-y)\ln \big(1-h(\mathbf{x})\big)$$$\Rightarrow$ **gubitak unakrsne entropije** (engl. *cross-entropy loss*)* **NB:** Izraz kompaktno definira grananje za dva slučaja (za $y=1$ i za $y=0$) ###Code def cross_entropy_loss(h_x, y): return -y * sp.log(h_x) - (1 - y) * sp.log(1 - h_x) xs = linspace(0, 1) plt.plot(xs, cross_entropy_loss(xs, 0), label='y=0') plt.plot(xs, cross_entropy_loss(xs, 1), label='y=1') plt.ylabel('$L(h(\mathbf{x}),y)$') plt.xlabel('$h(\mathbf{x}) = \sigma(w^\intercal\mathbf{x}$)') plt.legend() plt.show() ###Output _____no_output_____ ###Markdown * **Q:** Koliki je gubitak na primjeru $\mathbf{x}$ za koji model daje $h(\mathbf{x})=P(y=1|\mathbf{x})=0.7$, ako je stvarna oznaka primjera $y=0$? Koliki je gubitak ako je stvarna oznaka $y=1$?* Gubitaka nema jedino onda kada je primjer savršeno točno klasificiran ($h(x)=1$ za $y=1$ odnosno $h(x)=0$ za $y=0$)* U svim drugim slučajevima postoji gubitak: čak i ako je primjer ispravno klasificiran (na ispravnoj strani granice) postoji malen gubitak, ovisno o pouzdanosti klasifikacije* Ipak, primjeri na ispravnoj strani granice ($h(\mathbf{x})\geq 0.5$ za $y=1$ odnosno $h(\mathbf{x})< 0.5$ za $y=0$) nanose puno manji gubitak od primjera na pogrešnoj strani granice ###Code #TODO: konkretan primjer u ravnini ###Output _____no_output_____ ###Markdown Minimizacija pogreške$$\begin{align*}E(\mathbf{w}) &=\sum_{i=1}^N L\big(h(\mathbf{x}^{(i)}|\mathbf{w}),y^{(i)}\big)\\L(h(\mathbf{x}),y) &= - y \ln h(\mathbf{x}) - (1-y)\ln \big(1-h(\mathbf{x})\big)\\h(\mathbf{x}) &= \sigma(\mathbf{w}^\intercal\mathbf{x}) = \frac{1}{1 + \exp(-\mathbf{w}^\intercal\mathbf{x})}\end{align*}$$* Ne postoji rješenje u zatvorenoj formi (zbog nelinearnosti funkcije $\sigma$)* Minimiziramo **gradijentnim spustom**:$$ \nabla E(\mathbf{w}) =\sum_{i=1}^N \nabla L\big(h(\mathbf{x}^{(i)}|\mathbf{w}),y^{(i)}\big)$$* Prisjetimo se:$$\frac{\partial\sigma(\alpha)}{\partial\alpha} = \sigma(\alpha)\big(1 - \sigma(\alpha)\big)$$* Dobivamo: $$\nabla L\big(h(\mathbf{x}),y\big) = \Big(-\frac{y}{h(\mathbf{x})} + \frac{1-y}{1-h(\mathbf{x})}\Big)h(\mathbf{x})\big(1-h(\mathbf{x})\big)\tilde{\mathbf{x}} = \big(h(\mathbf{x})-y\big)\tilde{\mathbf{x}}$$* Gradijent-vektor pogreške:$$ \nabla E(\mathbf{w}) = \sum_{i=1}^N \big(h(\mathbf{x}^{(i)})-y^{(i)}\big)\tilde{\mathbf{x}}^{(i)}$$ Gradijentni spust (*batch*)> $\mathbf{w} \gets (0,0,\dots,0)$> **ponavljaj** do konvergencije> $\quad \Delta\mathbf{w} \gets (0,0,\dots,0)$> $\quad$ **za** $i=1,\dots, N$> $\qquad h \gets \sigma(\mathbf{w}^\intercal\tilde{\mathbf{x}}^{(i)})$> $\qquad \Delta \mathbf{w} \gets \Delta\mathbf{w} + (h-y^{(i)})\, \tilde{\mathbf{x}}^{(i)}$> $\quad \mathbf{w} \gets \mathbf{w} - \eta \Delta\mathbf{w} $ Stohastički gradijentni spust (*on-line*)> $\mathbf{w} \gets (0,0,\dots,0)$> **ponavljaj** do konvergencije> $\quad$ (slučajno permutiraj primjere u $\mathcal{D}$)> $\quad$ **za** $i=1,\dots, N$> $\qquad$ $h \gets \sigma(\mathbf{w}^\intercal\tilde{\mathbf{x}}^{(i)})$> $\qquad$ $\mathbf{w} \gets \mathbf{w} - \eta (h-y^{(i)})\tilde{\mathbf{x}}^{(i)}$ ###Code #TODO kod + primjer ###Output _____no_output_____
Day_5(Python).ipynb
###Markdown Dictionary Syntax: > {key1:value1, key2: value2,...} ###Code {'id':13, 'name':"Haseeb", "course":"A.I"} dict1 = {'id':13, 'name':"Haseeb", "course":"A.I"} dict1 d1 = {} d1['id'] = 13 d1['name'] = "Haseeb" d1['Course'] = "A.I" d1 ###Output _____no_output_____ ###Markdown dict ( ) The dict() constructor builds dictionaries directly from sequences of key-value pairs: ###Code {'sape': 4139, 'guido': 4127, 'jack': 4098} dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) dict(sape = 4139,guido = 4127, jack = 4098) ###Output _____no_output_____ ###Markdown .clear() ###Code d1 = {'id': 123, 'name': 'Haseeb', 'course': 'A.I'} print(d1) d1.clear() # In Memory Function, Empty Dictionary... print(d1) d1 = {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} print(d1) del(d1) # Destory the variable also... print(d1) ###Output {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} ###Markdown .copy() ###Code d1 = {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} print(d1) d2 = d1 #Shallow Copy d2['id'] = 0 print(d1) print(d2) d1 = {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} print(d1) d2 = d1.copy() #Deep Copy d2['id'] = 0 print(d1) print(d2) ###Output {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} {'id': 200, 'name': 'Haseeb', 'course': 'A.I'} {'id': 0, 'name': 'Haseeb', 'course': 'A.I'} ###Markdown .fromkeys() Signature: dict.fromkeys(iterable, value=None, /) Create a new dictionary with keys from iterable and values set to value. ###Code l1 = ['id', 'name', 'course', 'address'] dict_formkeys = dict.fromkeys(l1) #value = None by default dict_formkeys l1 = ['id', 'name', 'course', 'address'] val = "NAN" dict_formkeys = dict.fromkeys(l1,val) dict_formkeys #What? if we don't have fromkeys() a = input('Enter keys for dictionary: ') a = a.split(',') print(a) dict3 = {} print(dict3) for i in a: dict3[i] = None dict3 # using fromkeys() to set key values as input from user for dict... a = input('Enter keys for dictionary: ').split(',') dict.fromkeys(a) # setting key and values as input from user in dict... keys = input("Enter KEys For Dictionary: ").split(",") val = input("Enter Value for Dictionary: ").split(",") d4 = {} for i in range(len(val)): d4[keys[i]] = val[i] d4 ids = [1,2,3] name = ['Haseeb', 'Raza', 'Yasir'] course = ['ds', 'cnc', 'web'] zip_variable = zip(ids,name,course) list(zip_variable) zip_variable = zip(ids,name) dict(zip_variable) #dict(list(zip_variable)) zip_variable = zip(ids,zip(name,course)) print(dict(zip_variable)) #print(dict(zip_variable)[2]) #print(dict(zip_variable)[2][0]) dict2 = { 'id': input('Enter id: '), 'name': input('Enter name: '), 'skills': input('Enter skills: ').split(',') } dict2 ###Output Enter id: 013 Enter name: Haseeb Enter skills: Python, Numpy, Pandas, PHP ###Markdown .get() ###Code dict1 = {"id" : 13, "name": "Haseeb"} dict1["id"] dict1["course"] #We use get method to get value of key... it allow us to show message as per need if value not found... dict1.get("course", "Not Available") ###Output _____no_output_____ ###Markdown .items() ###Code dic = {'id': '0', 'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} dic.items() ###Output _____no_output_____ ###Markdown .key() ###Code dic.keys() ###Output _____no_output_____ ###Markdown .values() ###Code dic.values() a_dict = {'color': 'blue', 'fruit': 'apple', 'pet':'dog'} for key in a_dict: # by default it picks keys print(key) a_dict = {'color': 'blue', 'fruit': 'apple', 'pet':'dog'} keys = a_dict.keys() print(keys) print() for key in a_dict.keys(): # selecting keys print(key) a_dict = {'color': 'blue', 'fruit': 'apple', 'pet':'dog'} values = a_dict.values() print(values) print() for value in a_dict.values(): # selecting values print(value) a_dict = {'one': 1, 'two':2, 'three':3, 'four':4} new_dict = {} for key, value in a_dict.items(): if value <= 2: new_dict[key] = value print(new_dict) print(a_dict) a_dict = {'one': 1, 'two':2, 'three':3, 'four':4} new_dict = {} for key, value in a_dict.items(): new_dict[value] = key print(a_dict) print(new_dict) incomes = {'apples': 5600.0, 'orange': 3500.0, 'banana':5000.0} total_cost = 0.0 for value in incomes.values(): total_cost += value print(f'total price is {total_cost}') sum(incomes.values()) ###Output _____no_output_____ ###Markdown .pop() ###Code prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25} for key in prices.keys(): if key == 'orange': del prices[key] prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25} del prices["orange"] # pop specified key and don't return value prices # to tackle dictionary changed size during iteration problem dic = {'id': '0', 'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} print(dic) print(dic.pop('id')) # pop specified key and return value print(dic) # to tackle dictionary changed size during iteration problem dic = {'id': '0', 'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} print(dic) a = dic.pop('id') print(a) # return value print(dic) ###Output {'id': '0', 'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} 0 {'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} ###Markdown .popitem() ###Code dic = {'id': '0', 'name': 'qasim', 'skills': ['pyhton', 'numpy', 'pandas']} print(dic) print(dic.popitem()) # pop last item and return it as well print(dic) a_dict = {'color': 'blue', 'fruit': 'apple', 'pet':'dog'} print(a_dict) while True: try: print(f'Dictionary length: {len(a_dict)}') item = a_dict.popitem() print(f'Removed : {item}') except KeyError: print('The dictionary has no item now..!!!') break ###Output {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} Dictionary length: 3 Removed : ('pet', 'dog') Dictionary length: 2 Removed : ('fruit', 'apple') Dictionary length: 1 Removed : ('color', 'blue') Dictionary length: 0 The dictionary has no item now..!!! ###Markdown .setdefault() ###Code dic = {'id': '0', 'name': 'Haseeb', 'skills': ['pyhton', 'numpy', 'pandas']} print(dic) print(dic.setdefault('id', '13')) # can't make already avaliable key to default print(dic) dic = {'id': '0', 'name': 'qasim', 'skills': ['pyhton', 'numpy', 'pandas']} print(dic) print(dic.setdefault('course', 'DS')) # add new key, value pair as default print(dic) ###Output {'id': '0', 'name': 'qasim', 'skills': ['pyhton', 'numpy', 'pandas']} DS {'id': '0', 'name': 'qasim', 'skills': ['pyhton', 'numpy', 'pandas'], 'course': 'DS'} ###Markdown .update() ###Code d1 = {'age1':10, 'age2':20, 'age3':30} d2 = {'age1':15, 'age2':25, 'age3':35, 'age4':5} d1.update(d2) d1 #sorting key wise d1 = { 'a':200, 'c':300, 'b':600, 'd':400 } d2={} for key in sorted(d1.keys()): d2[key] = d1[key] print(d2) #sorting key wise by default d1 = { 'a':200, 'c':300, 'b':600, 'd':400 } d2={} for key,val in sorted(d1.items()): d2[key] = d1[key] print(d2) moon = {} scores = {'a':200,'c':300,'b':600,'d':400} for key,value in sorted(scores.items(),key = lambda kv:kv[1]): #kv[1] sort by vlaue moon[key] = value print(moon) moon = {} scores = {'a':200,'c':300,'b':600,'d':400} for key,value in sorted(scores.items(),key = lambda kv:kv[0]): #kv[1] sort by keys moon[key] = value print(moon) scores = {'a':200,'c':300,'b':600,'d':400} {k:v for k, v in sorted(scores.items(), key=lambda x:x[1], reverse=True)} moon = {} scores = {'b':100, 'c':200, 'a':300} for key,value in sorted(scores.items(), reverse=True): # sort by keys moon[key] = value print(moon) l1 = [] run = True while run: choice = input('press n/N to stop and y/Y to run: ') if choice == 'n' or choice == 'N': run = False elif choice == 'y' or choice == 'Y': d1 = {'id': input('Enter your id: '), 'name': input('Enter your name: '), 'course': input('Enter course name: ')} l1.append(d1) print(l1) # display list of dictionaries ###Output press n/N to stop and y/Y to run: y Enter your id: 013 Enter your name: Haseeb Enter course name: DS press n/N to stop and y/Y to run: Y Enter your id: 014 Enter your name: Kamran Enter course name: CNC press n/N to stop and y/Y to run: n [{'id': '013', 'name': 'Haseeb', 'course': 'DS'}, {'id': '014', 'name': 'Kamran', 'course': 'CNC'}] ###Markdown Dictionary comprehension ###Code objects = ['blue', 'apple', 'dog'] categories = ['color', 'fruit', 'animal'] new_dic = { key : value for key, value in zip(categories, objects)} print(new_dic) d = {'color': 'blue', 'fruit': 'apple', 'animal': 'dog'} new_d = { value : key for key,value in d.items()} print(new_d) a_dict = {'one': 1, 'two':2, 'three':3, 'four':4} new_dict = {k : v for k, v in a_dict.items() if v <= 2} print(new_dict) ###Output {'one': 1, 'two': 2} ###Markdown Iteration through dictionnaries using some python builtin functions map() filter() ChainMap() itertools() chain() cycle() map()use to mapy/appl a function on dictionary... ###Code prices = {'apples': 0.45, 'orange': 0.35, 'banana':0.25} def discount(current_prices): return (current_prices[0], round(current_prices[1]*0.95, 2)) # 0.95 means applying 5% discount new_prices = dict(map(discount, prices.items())) new_prices prices = {'apples': 0.45, 'orange': 0.35, 'banana':0.25} def has_low_price(price): return prices[price] < 0.4 #print(filter(has_low_price, prices.keys())) ---> return object so converting object into list low_price = list(filter(has_low_price, prices.keys())) print(low_price) from collections import ChainMap fruit_prices = {'apple': 0.40, 'orange': 0.35} vegetable_prices = {'pepper': 0.20, 'onion':0.55} chained_dict = ChainMap(fruit_prices, vegetable_prices) print(chained_dict) # for key in chained_dict: # print(key , '-->', chained_dict[key]) for key,value in chained_dict.items(): print(key, '-->', value) from itertools import cycle fruit_prices = {'apple': 0.40, 'orange': 0.35} times = 3 total_items = times * len(fruit_prices) for item in cycle(fruit_prices.items()): # print(total_items) if not total_items: break total_items -=1 print(item) from itertools import chain fruit_prices = {'apple': 0.40, 'orange': 0.35} vegetable_prices = {'pepper': 0.20, 'onion':0.55} for item in chain(fruit_prices.items(),vegetable_prices.items()): print(item) ###Output ('apple', 0.4) ('orange', 0.35) ('pepper', 0.2) ('onion', 0.55) ###Markdown Using the dictionary unpacking operaor(**) ###Code fruit_prices = {'apple': 0.40, 'orange': 0.35} vegetable_prices = {'pepper': 0.20, 'onion':0.55} print({**vegetable_prices, **fruit_prices}) for k , v in {**vegetable_prices, **fruit_prices}.items(): print(k, '-->', v) # the apple key is present in both dictionaries. after you merger them, the fruit_price va;ue for apple(0.40) prevailed, # becuase fruit price is the right mosrt dictionary fruit_prices = {'apple': 0.40, 'orange': 0.35} vegetable_prices = {'pepper': 0.20, 'onion':0.55, 'apple': 0.30} print({**vegetable_prices, **fruit_prices}) x = {'a':1, 'b':2} y = {'b':3, 'c': 4} {**x, **y} ###Output _____no_output_____
health/Ashley/v2-2018.06.13/Health Data - Elizabeth Ashley Flack.ipynb
###Markdown Health Data - Elizabeth Ashley FlackOriginal data is available on [Google Sheets](https://docs.google.com/spreadsheets/d/1vaXOXPluOg_lg0uqKC-qLBt6odL0GPFPcYzOP2vbaiM/editgid=1309334105). ###Code # Juptyer Notebook Settings options(repr.plot.width=5, repr.plot.height=5) # plot size, inches ###Output _____no_output_____ ###Markdown I. Load Semi-Raw DataThis data has already been somewhat wrangled in that secondary variables (namespaced as `Indicator.SECONDARY_VARIABLE_NAME`) have been created. ###Code dat = read.csv("data/Health Data - Elizabeth Ashley Flack.csv", header = TRUE) tail(dat) # See last 6 obs # head(dat) # See first 6 obs ###Output _____no_output_____ ###Markdown II. Explore Semi-Raw Data ###Code summary(dat) sapply(dat, typeof) # Check types of all fields, using "simple apply" to apply typeof() to all fields in "dat". ###Output _____no_output_____ ###Markdown III. Clean Data III.1 Convert read.csv() List to Data Frame ###Code df <- data.frame(dat) # Better for data analysis ###Output _____no_output_____ ###Markdown III.2 Drop unneeded columns ###Code tail(df, n=1)$Notes.Unstructured drops <- c("Notes.Unstructured") # Create vector of fields to drop df <- df[ , !(names(df) %in% drops)] # Creates a new data frame from the first one, including any fields that aren't in list of fields to filter out. tail(df, n=1)$Notes.Unstructured ###Output _____no_output_____ ###Markdown III.3 Remove any rows with missing values ###Code nrow(df) # Number of original rows # str() makes for much more concise, truncated output str(colSums(is.na(df))) # shows total number of observations w/ any "na's", i.e. missing values, in columns str(colSums(!is.na(df))) # shows total obs w/ any non-"na's" df <- df[complete.cases(df), ] nrow(df) # Number of rows left after filtering rows with any missing values ###Output _____no_output_____ ###Markdown IV.4 Streamline Data Types ###Code c('Original type and class of Date field, followed by an example value: ') typeof(df$Date) class(df$Date) df$Date[1] df$Date <- as.Date(df$Date, format='%m/%d/%Y') c('New type ,class, and example after applying date formatting: ') typeof(df$Date) class(df$Date) df$Date[1] ###Output _____no_output_____ ###Markdown IV. Explore Clean Data ###Code summary(df) ###Output _____no_output_____ ###Markdown V. Analyses V.1 Simple Plots Data Visualization Reference Info Ggplot2Tutorial: http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2)/Options for `geom_line()`- Line type, e.g. `linetype='dashed'`- Line color, e.g. `color='red'` Presence of any headache on weekday for timespan of entire dataset ###Code lm1 <- lm(Symptom.1 ~ Weekday, data=df) plot(df$Weekday, df$Symptom.1) ###Output _____no_output_____ ###Markdown Health over time ###Code # For this section, I should comment out certain lines. library(ggplot2) # imports ggplot2 var <- df$Indicator.Health # y-axis time <- df$Date # x-axis options(repr.plot.width=7, repr.plot.height=4.5) # Sets Jupyter Notebook plot size, inches # aes() means "aesthetics". for y-axis, I flipped it an magnified by 10. ggplot(data=df, aes(x=time, y=-10*(var), colour=(-10*var), color=qsec, group=1)) + geom_line() + # draws line between points geom_point() + # adds dots for data points theme(plot.title = element_text(hjust = 0.5)) + # centers title scale_color_gradient(low="#AA4444", high="#ff0000") + # line color, reflected by legend scale_x_date(date_breaks='1 month', date_labels="%b '%y") + # otherwise labels didn't show year stat_smooth(method='lm', col='#2e64ba') + # draws linear model, i.e. regression line with confidence bands labs(x='Time', y='Adverse Health Measure (AHM)', title='Adverse Health Measure (AHM), Daily', colour='AHM') options(repr.plot.width=7, repr.plot.height=7) # (1) Resets Jupyter Notebook plot size back to default a_lm <- lm(Indicator.Health ~ Date, data=df) plot(df$Date, df$Indicator.Health) lines(df$Date, a_lm$fitted) ###Output _____no_output_____ ###Markdown V.2 Linear Models ###Code a_lm <- lm(Indicator.Utility ~ Date, data=df) plot(df$Date, df$Indicator.Utility) lines(df$Date, a_lm$fitted) a_lm <- lm(Indicator.Health ~ Date, data=df) plot(df$Date, df$Indicator.Health) lines(df$Date, a_lm$fitted) a_lm <- lm(Indicator.Wellbeing ~ Date, data=df) plot(df$Date, df$Indicator.Wellbeing) lines(df$Date, a_lm$fitted) ###Output _____no_output_____
Chapter11/model_performance_drifts/monitoring_data_drift_performance.ipynb
###Markdown Important data ###Code import pandas as pd import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from evidently.dashboard import Dashboard from evidently.tabs import DataDriftTab, NumTargetDriftTab,CatTargetDriftTab ###Output _____no_output_____ ###Markdown Load reference data ###Code reference_data = pd.read_csv("training_data.csv", header=None, names=[ "day{}".format(i) for i in range(0,14) ]+["target"] ) reference_data.head(5) ###Output _____no_output_____ ###Markdown Get Production Input Data ###Code latest_input_data = pd.read_csv("to_score_input_data.csv", header=None, names=[ "day{}".format(i) for i in range(0,14) ] ) latest_input_data import mlflow ###Output _____no_output_____ ###Markdown Input Data Drift Check ###Code EXPERIMENT_NAME="./reports_data_drift" mlflow.set_experiment(EXPERIMENT_NAME) with mlflow.start_run(): drift_dashboard = Dashboard(tabs=[DataDriftTab]) drift_dashboard.calculate(reference_data,latest_input_data) drift_dashboard.save(EXPERIMENT_NAME+"/input_data_drift.html") drift_dashboard._save_to_json(EXPERIMENT_NAME+"/input_data_drift.json") mlflow.log_artifacts(EXPERIMENT_NAME) ###Output _____no_output_____
slides/DLAP2020_ising_detection.ipynb
###Markdown 2Dイジング模型の相転移検出 in Deep learning and physics 2020- 富谷昭夫ニューラルネットを使って $\beta_{cr} = 0.440686$ を検出する。 ###Code #ライブラリのロード import matplotlib.pyplot as plt import numpy as np ###Output _____no_output_____ ###Markdown ここでGoogle drive をマウントしてください。配位(conf/L32b***_***.npy) はgoogle drive に入れてください。 ###Code # もしGoogle drive のマウントが上手く行かない場合に実行してください。 #from google.colab import drive #drive.mount('/content/drive') # もしマウントができていれば配位の数(1900)が表示されます。 !ls -l drive/MyDrive/conf|grep npy|wc -l # パラメータリスト prm_list = [ # beta, file_name, [0.90,"drive/MyDrive/conf/L32b090_"], [0.85,"drive/MyDrive/conf/L32b085_"], [0.80,"drive/MyDrive/conf/L32b080_"], [0.70,"drive/MyDrive/conf/L32b070_"], [0.65,"drive/MyDrive/conf/L32b065_"], [0.60,"drive/MyDrive/conf/L32b060_"], [0.55,"drive/MyDrive/conf/L32b055_"], [0.50,"drive/MyDrive/conf/L32b050_"], [0.47,"drive/MyDrive/conf/L32b047_"], [0.42,"drive/MyDrive/conf/L32b042_"], [0.40,"drive/MyDrive/conf/L32b040_"], [0.35,"drive/MyDrive/conf/L32b035_"], [0.30,"drive/MyDrive/conf/L32b030_"], [0.25,"drive/MyDrive/conf/L32b025_"], [0.20,"drive/MyDrive/conf/L32b020_"], [0.15,"drive/MyDrive/conf/L32b015_"], [0.10,"drive/MyDrive/conf/L32b010_"], [0.05,"drive/MyDrive/conf/L32b005_"], [0.00,"drive/MyDrive/conf/L32b000_"] ] # beta19 x conf100 = 1900 data print("読み込めているかのテスト") for iconf in range(2): print("beta=090") file = f"drive/MyDrive/conf/L32b090_{iconf}.npy" sc = np.load(file) plt.imshow(sc, cmap='gray') plt.show() for iconf in range(2): print("beta=040") file = f"drive/MyDrive/conf/L32b040_{iconf}.npy" sc = np.load(file) plt.imshow(sc, cmap='gray') plt.show() for iconf in range(2): print("beta=000") file = f"drive/MyDrive/conf/L32b000_{iconf}.npy" sc = np.load(file) plt.imshow(sc, cmap='gray') plt.show() ###Output 読み込めているかのテスト beta=090 ###Markdown 教師ラベルの設定とデータの分割 ###Code nconf = 100 # The number of configurations per beta betacr = 0.440686 # critical temp for 2d ising # data = [] labels = [] betas = [] nprm=len(prm_list) for ibeta in range(nprm): beta = prm_list[ibeta][0] fname = prm_list[ibeta][1] for itrj in range(nconf): npsc = np.load(f"{fname}{itrj}.npy") data.append(npsc) if beta > betacr: labels.append([0,1]) else: labels.append([1,0]) betas.append(beta) data = np.array(data) labels = np.array(labels) # train_data=data[0::2] train_labels=labels[0::2] train_betas=betas[0::2] # this will not be used in training # val_data=data[1::2] val_labels=labels[1::2] val_betas=betas[1::2] # # beta18 x conf100 = 1800 data # beta18 x conf50 = 900 training_data(18x50,same beta = 50) + 900 val_data print("train_data.shape = ", train_data.shape) print("val_data.shape = ", val_data.shape) ###Output train_data.shape = (950, 32, 32) val_data.shape = (950, 32, 32) ###Markdown Tensorflow ###Code import tensorflow as tf from tensorflow import keras print(tf.__version__) ###Output 2.3.0 ###Markdown Model def ###Code tf.random.set_seed(12345) model_FC = keras.Sequential([ keras.layers.Flatten(input_shape=(32, 32)), keras.layers.Dense(100, activation='relu'), keras.layers.Dense(2, activation='softmax') ]) model_FC.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model_FC.fit(train_data, train_labels, epochs=10) xs=[] y1s=[] y2s=[] Ndatamax = 950 Nsameclass = 50 for ii in range(0,Ndatamax,Nsameclass): res = model_FC(val_data[ii:ii+Nsameclass]) x = val_betas[ii] y1= np.mean(res.numpy().T[0] ) y2=np.mean(res.numpy().T[1] ) xs.append( x) y1s.append( y1 ) y2s.append( y2 ) print(x,y1,y2) plt.axvline(x=0.440686, ymin=0, ymax=1, ls="dashed",color="gray",label="Critical(Ans)") plt.plot(xs,y1s,label="class:High",marker="o",color="red") plt.plot(xs,y2s,label="class:Low",marker="o",color="blue") plt.legend() plt.xlabel(r"$\beta=1/T$") plt.ylabel(r"Prob") plt.show() # 交点を求める。 u1,v1 = xs[9],y1s[9] u2,v2 = xs[8],y1s[8] w1,t1 = xs[9],y2s[9] w2,t2 = xs[8],y2s[8] print(u1,v1) print(u2,v2) # print(w1,t1) print(w2,t2) from numpy.linalg import solve tan1=(v2-v1)/(u2-u1) tan2=(t2-t1)/(w2-w1) MatA = [[1, -tan1], [1, -tan2]] vecB = [v1-tan1*u1, t1-tan2*w1] # sol = solve(MatA, vecB) print("sol x,y = ", sol) # xx = np.linspace(0,1) yy = tan1*(xx-u1)+v1 plt.plot(xx,yy) # yy = tan2*(xx-w1)+t1 plt.plot(xx, yy) plt.ylim(0,1) plt.show() # beta_cr = 0.440686 er = round(abs(beta_cr - sol[1])/beta_cr *100,2) print(f"Relative error = {er} %") ###Output 0.42 0.90538 0.47 0.0024133257 0.42 0.09461986 0.47 0.9975867 sol x,y = [0.49999998 0.44244712] ###Markdown Convolutional neural networkCNN ###Code tf.random.set_seed(12345) model_CNN = keras.Sequential([ keras.layers.Conv2D(filters = 1, kernel_size=(4, 4), activation='relu', input_shape=(32, 32, 1) ), keras.layers.Flatten(), keras.layers.Dense(100, activation='relu'), keras.layers.Dense(2, activation='softmax') ]) model_CNN.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) train_data_cnn=np.array(train_data) train_data_cnn = train_data_cnn.reshape(train_data.shape[0], train_data.shape[1], train_data.shape[2], 1) train_data_cnn.shape model_CNN.fit(train_data_cnn, train_labels, epochs=10) xs=[] y1s=[] y2s=[] Ndatamax = 950 Nsameclass = 50 for ii in range(0,Ndatamax,Nsameclass): res = model_CNN(val_data[ii:ii+Nsameclass]) x = val_betas[ii] y1= np.mean(res.numpy().T[0] ) y2=np.mean(res.numpy().T[1] ) xs.append( x ) y1s.append( y1 ) y2s.append( y2 ) print(x,y1,y2) plt.axvline(x=0.440686, ymin=0, ymax=1, ls="dashed",color="gray",label="Critical") plt.plot(xs,y1s,label="class:High",marker="o",color="red") plt.plot(xs,y2s,label="class:Low",marker="o",color="blue") plt.legend() plt.xlabel(r"$\beta=1/T$") plt.ylabel(r"Prob") plt.show() u1,v1 = xs[9],y1s[9] u2,v2 = xs[8],y1s[8] w1,t1 = xs[9],y2s[9] w2,t2 = xs[8],y2s[8] print(u1,v1) print(u2,v2) # print(w1,t1) print(w2,t2) from numpy.linalg import solve tan1=(v2-v1)/(u2-u1) tan2=(t2-t1)/(w2-w1) MatA = [[1, -tan1], [1, -tan2]] vecB = [v1-tan1*u1, t1-tan2*w1] # sol = solve(MatA, vecB) print("sol x,y = ", sol) # xx = np.linspace(0,1) yy = tan1*(xx-u1)+v1 plt.plot(xx,yy) # yy = tan2*(xx-w1)+t1 plt.plot(xx, yy) plt.ylim(0,1) plt.show() # beta_cr = 0.440686 er = round(abs(beta_cr - sol[1])/beta_cr *100,2) print(f"Relative error = {er} %") ###Output _____no_output_____
pyFIRS/examples/05_Merge Tiled Derivatives Together.ipynb
###Markdown Launch a parallel computing cluster. ###Code cluster = LocalCluster(scheduler_port=7001, dashboard_address=7002) c = Client(cluster) num_cores = len(c.ncores()) # identify how many workers we have ###Output _____no_output_____ ###Markdown At this point, you should also be able to view an interactive dashboard on port 7002. If you're executing this on a remote server, you'll need to set up port forward so you can view the dashboard on your local machine's browser. Once you've done that, or if you're processing on your own machine, you can view the dashboard at [http://localhost:7002/status](http://localhost:7002/status). ###Code las = lastools.useLAStools('/storage/lidar/LAStools/bin') # define data handling directories INTERIM = os.path.join(WORKDIR, 'interim') PROCESSED = os.path.join(WORKDIR,'processed') # push stuff to the workers on the cluster c.scatter([INTERIM, PROCESSED, las, TARGET_EPSG, num_cores], broadcast=True); tiles_to_merge = [fname(tile) for tile in glob.glob(os.path.join(PROCESSED, 'points', '*.laz'))] print('Found {:,d} tiles to merge derivative products from.'.format( len(tiles_to_merge))) ###Output _____no_output_____ ###Markdown Merge tiled derivative outputs togetherMerge all the tiled GeoTiffs and Shapefiles into single overview files. We'll produce a shapefile showing the layout of the non-buffered tiles as a single shapefile. This is a single process that takes a few seconds to run, so no need to distribute it using `dask`. ###Code @dask.delayed def tile_boundaries(*args, **kwargs): infiles_path = os.path.join(PROCESSED, 'points', '*.laz') OUTFILE = os.path.join(PROCESSED, 'vectors', 'tiles.shp') if os.path.exists(OUTFILE): pass else: proc = las.lasboundary(i=infiles_path, use_bb=True, # use bounding box of tiles overview=True, labels=True, cores=num_cores, # use parallel processing oshp=True, o=OUTFILE) return 'tile_boundaries' @dask.delayed def make_footprint(*args, **kwargs): if os.path.exists(os.path.join(PROCESSED, 'vectors', 'footprint.shp')): pass else: gdf = gpd.read_file(os.path.join(PROCESSED, 'vectors', 'tiles.shp')) gdf['mil_points'] = gdf['num_points'] / 1000000. buffered = gdf.drop(['file_name', 'point_size', 'point_type', 'num_points'], axis=1) buffered.geometry = gdf.buffer(0.01) # buffer by 1cm union = gpd.GeoDataFrame(geometry=[buffered.unary_union], crs=buffered.crs) union['footprint_id'] = union.index + 1 buffered = gpd.tools.sjoin(buffered, union, how='left').drop('index_right', axis=1) aggfuncs = {'mil_points': 'sum', 'version': 'first', 'min_x': 'min', 'min_y': 'min', 'min_z': 'min', 'max_x': 'max', 'max_y': 'max', 'max_z': 'max'} dissolved = buffered.dissolve(by='footprint_id', aggfunc=aggfuncs) OUTFILE = os.path.join(PROCESSED, 'vectors', 'footprint.shp') dissolved.to_file(OUTFILE) return 'footprint' ###Output _____no_output_____ ###Markdown Merge the bare earth tiles into a single GeoTiff. ###Code # @dask.delayed def make_vrt(infiles, vrtfile): """Mosaics files into a single GeoTiff Parameters ---------- infiles : list list of paths to input files to mosaic vrtfile : str, path to file path to VRT file that will be created Returns -------- proc : CompletedProcess the result of executing gdalbuildvrt using subprocess """ proc = subprocess.run(['gdalbuildvrt', vrtfile, *infiles], stderr=subprocess.PIPE, stdout=subprocess.PIPE) return proc @dask.delayed def merge_dem(*args, **kwargs): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'dem_tiles', '*.tif')) VRTFILE = os.path.join(PROCESSED, 'rasters', 'dem.vrt') if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return 'dem' @dask.delayed def merge_intensity(*args, **kwargs): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'intensity_tiles', '*.tif')) VRTFILE = os.path.join(PROCESSED, 'rasters', 'intensity.vrt') if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return 'intensity' ###Output _____no_output_____ ###Markdown Now merge the hillshade tiles into a single raster formatted as GeoTiff. ###Code @dask.delayed def merge_hillshade(*args, **kwargs): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'hillshade_tiles', '*.tif')) VRTFILE = os.path.join(PROCESSED, 'rasters', 'hillshade.vrt') if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return 'hillshade' ###Output _____no_output_____ ###Markdown Merge the trimmed canopy height model tiles into a single raster. ###Code @dask.delayed def merge_chm(*args, **kwargs): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'chm_tiles', '*.tif')) VRTFILE = os.path.join(PROCESSED, 'rasters', 'chm.vrt') if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return 'chm' ###Output _____no_output_____ ###Markdown Merge the cleaned tiles of building footprints together into a single shapefile. We'll use `geopandas` to concatenate all the polygons together into a single geodataframe and then write out to a new shapefile. ###Code @dask.delayed def merge_bldgs(*args, **kwargs): infiles = glob.glob( os.path.join(PROCESSED, 'vectors', 'building_tiles', '*.shp')) OUTFILE = os.path.join(PROCESSED, 'vectors', 'buildings.shp') if os.path.exists(OUTFILE): pass else: # list of geodataframes with tiles of building footprints gdflist = [gpd.read_file(tile) for tile in infiles] # merge them all together merged = pd.concat(gdflist, ignore_index=True) # add projection information back in merged.crs = gdflist[0].crs # and write the merged data to a new shapefile merged.to_file(OUTFILE) return 'bldgs' @dask.delayed def merge_highpoints(*args, **kwargs): infiles = glob.glob( os.path.join(INTERIM, 'chm_tiles', 'treesegs', '*HighPoints.shp')) OUTFILE = os.path.join(PROCESSED, 'vectors', 'high_points.shp') if os.path.exists(OUTFILE): pass else: # list of geodataframes with tiles of building footprints gdflist = [gpd.read_file(tile) for tile in infiles] # merge them all together merged = pd.concat(gdflist, ignore_index=True) # add projection information back in merged.crs = gdflist[0].crs # and write the merged data to a new shapefile merged.to_file(OUTFILE) return 'highpoints' @dask.delayed def merge_crowns(*args, **kwargs): infiles = glob.glob( os.path.join(INTERIM, 'chm_tiles', 'treesegs', '*Polygons.shp')) OUTFILE = os.path.join(PROCESSED, 'vectors', 'tree_crowns.shp') if os.path.exists(OUTFILE): pass else: # list of geodataframes with tiles of building footprints gdflist = [gpd.read_file(tile) for tile in infiles] # merge them all together merged = gpd.GeoDataFrame(pd.concat(gdflist, ignore_index=True)) # add projection information back in merged.crs = gdflist[0].crs # and write the merged data to a new shapefile merged.to_file(OUTFILE) return 'crowns' all_grid_tiles_paths = glob.glob( os.path.join(PROCESSED, 'rasters', 'gridmetrics_tiles', '*_strat0_intensity-median.tif')) all_grid_tiles = [fname(tile).split('_strat0_intensity-median')[0] for tile in all_grid_tiles_paths] example_tile = os.path.basename( all_grid_tiles_paths[0]).split('_strat0_intensity-median.tif')[0] grid_rasters = [os.path.basename(file).split(example_tile)[-1][1:-4] for file in glob.glob( os.path.join(PROCESSED, 'rasters', 'gridmetrics_tiles', example_tile + '*.tif'))] print('{:d} different types of rasters from gridmetrics ' 'to process for each tile:\r\n'.format(len(grid_rasters))) for i, raster in enumerate(grid_rasters): print('{}. {}'.format(i+1, raster)) all_gridsurf_tiles_paths = glob.glob( os.path.join(PROCESSED, 'rasters', 'gridsurface_tiles', '*_potential_volume.tif')) all_gridsurf_tiles = [fname(tile).split('_strat0_intensity-median')[0] for tile in all_gridsurf_tiles_paths] example_tile = os.path.basename( all_gridsurf_tiles_paths[0]).split('_potential_volume.tif')[0] gridsurf_rasters = [os.path.basename(file).split(example_tile)[-1][1:-4] for file in glob.glob( os.path.join(PROCESSED, 'rasters', 'gridsurface_tiles', example_tile + '*.tif'))] # we don't want these redundant rasters gridsurf_rasters = [x for x in gridsurf_rasters if x not in ['mean_height', 'max_height']] print('{:d} different types of rasters from gridsurface ' 'to process for each tile:\r\n'.format(len(gridsurf_rasters))) for i, raster in enumerate(gridsurf_rasters): print('{}. {}'.format(i+1, raster)) @dask.delayed def merge_gridmetric(metric): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'gridmetrics_tiles', '*{}.tif'.format(metric))) VRTFILE = os.path.join(PROCESSED, 'rasters', '{}.vrt'.format(metric)) if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return metric @dask.delayed def merge_gridsurface(metric): infiles = glob.glob( os.path.join(PROCESSED, 'rasters', 'gridsurface_tiles', '*{}.tif'.format(metric))) VRTFILE = os.path.join(PROCESSED, 'rasters', 'gridsurface_tiles', '{}.vrt'.format(metric)) if os.path.exists(VRTFILE): pass else: make_vrt(infiles, VRTFILE) return metric ###Output _____no_output_____ ###Markdown A single state that will depend upon the completion of the merged rasters and vectors. ###Code @dask.delayed def merge_done(*args, **kwargs): return # building the computation receipe merge_dsk = {} merge_dsk['tile_boundaries'] = (tile_boundaries,) merge_dsk['footprint'] = (make_footprint, 'tile_boundaries') merge_dsk['merge_bldgs'] = (merge_bldgs,) merge_dsk['merge_hill'] = (merge_hillshade,) merge_dsk['merge_dem'] = (merge_dem,) merge_dsk['merge_intensity'] = (merge_intensity,) merge_dsk['merge_chm'] = (merge_chm,) for raster in grid_rasters: merge_dsk['merge_gridmetric-{}'.format(raster)] = (merge_gridmetric, raster) for raster in gridsurf_rasters: merge_dsk['merge_gridsurface-{}'.format(raster)] = (merge_gridsurface, raster) merge_dsk['merge_done'] = (merge_done, ['tile_boundaries', 'footprint']+ #) # + ['merge_bldgs'] + #) ['merge_hill', 'merge_dem'] + ['merge_chm', 'merge_intensity'] + ['merge_gridmetric-{}'.format(raster) for raster in grid_rasters] + ['merge_gridsurface-{}'.format(raster) for raster in gridsurf_rasters]) merge_graph = c.get(merge_dsk, 'merge_done') # build the computation graph merge_graph.visualize(rankdir='LR') merge_results = c.persist(merge_graph) # this might take a while... progress(merge_results) # merge_results.result() # c.cancel(merge_results) # c.close() # cluster.close() ###Output _____no_output_____
notebooks/CommonModulus.ipynb
###Markdown Common modulus attackSuppose Alice sends the RSA encryptions of the same message $m$to two people using the same RSA modulus $n$ and relatively prime public exponents $e_1$ and $e_2$.An attacker can retrieve the message $m$ only from the public data(i.e., the modulus $n$, the public exponents $e_1$ and $e_2$,and the encryptions $c_i = m^{e_i} \bmod{n}$ for $i = 1, 2$).By using the extended Euclidean algorithm,one can compute integers $a$ and $b$ such that $a e_1 + b e_2 = 1$.Then the message $m$ can be retrieved as $c_1^a c_2^b \equiv m^{a e_1 + b e_2} \equiv m \pmod{n}$. ExampleLet $n = 55$, $e_1 = 3$, $e_2 = 7$, $c_1 = 8$ and $c_2 = 18$. ###Code from algorithms.euclidean import eea n = 55 e1, e2 = 3, 7 c1, c2 = 8, 18 ###Output _____no_output_____ ###Markdown Let us compute $a$ and $b$. ###Code a, b = eea(c1, c2) a, b ###Output _____no_output_____ ###Markdown We can now retrieve the message. ###Code m = c1^a * c2^b % n m ###Output _____no_output_____ ###Markdown Let us verify that the decryption really encrypts to the given ciphertexts. ###Code [m^e % n for e in (e1, e2)] ###Output _____no_output_____
assignments/PythonBasicsProgramming/Programming_Assignment_9.ipynb
###Markdown 1. Write a Python program to check if the given number is a Disarium Number? ###Code number = input("Enter a number to check if it is Disarium Number: ") disarium = 0 for i in range(len(number)): disarium += int(number[i])**(i+1) if int(number) == disarium: print(f"Given number {number} is a disarium number") else: print(f"Given number {number} is not a disarium number") ###Output Enter a number to check if it is Disarium Number: 135 Given number 135 is a disarium number ###Markdown 2. Write a Python program to print all disarium numbers between 1 to 100? ###Code for i in range(1, 101): number = str(i) disarium = 0 for i in range(len(number)): disarium += int(number[i])**(i+1) if int(number) == disarium: print(number, end=" ") ###Output 1 2 3 4 5 6 7 8 9 89 ###Markdown 3. Write a Python program to check if the given number is Happy Number? ###Code def is_happy_number(n): slow, fast = n, n while(True): slow = numSquareSum(slow) fast = numSquareSum(numSquareSum(fast)) if(slow != fast): continue; else: break return (slow == 1) def num_square_sum(n): squareSum = 0; while(n): squareSum += (n % 10) * (n % 10); n = int(n / 10); return squareSum n = int(input("Enter a number to check if it is a Happy Number: ")) if is_happy_number(n): print(f"{n} is a Happy number"); else: print(f"{n} is not a Happy number"); ###Output Enter a number to check if it is a Happy Number: 13 13 is a Happy number ###Markdown 4. Write a Python program to print all happy numbers between 1 and 100? ###Code def is_happy_number(n): slow, fast = n, n while(True): slow = numSquareSum(slow) fast = numSquareSum(numSquareSum(fast)) if(slow != fast): continue else: break return (slow == 1) def num_square_sum(n): squareSum = 0 while(n): squareSum += (n % 10) * (n % 10) n = int(n / 10) return squareSum for n in range(1, 101): if is_happy_number(n): print(n, end= " ") ###Output 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 ###Markdown 5. Write a Python program to determine whether the given number is a Harshad Number? ###Code # The number 18 is a harshad number in base 10, because the sum of the digits 1 and 8 is 9 (1 + 8 = 9), and 18 is divisible by 9. def is_harshad_number(n): s = 0 for c in str(n): s += int(c) if n % s == 0: return True return False x = int(input("Enter a Harshad Number:")) if is_harshad_number(x): print(f"{x} is a Harshad Number") else: print(f"{x} is not a Harshad Number") ###Output Enter a Harshad Number:198 198 is a Harshad Number ###Markdown 6. Write a Python program to print all pronic numbers between 1 and 100? ###Code def is_harshad_number(n): s = 0 for c in str(n): s += int(c) if n % s == 0: return True return False for i in range(1, 101): if is_harshad_number(i): print(i, end= " ") ###Output 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 45 48 50 54 60 63 70 72 80 81 84 90 100
data/experimental_data_analysis.ipynb
###Markdown Perception of amplitude modulation-induced vibratoData analysis and exploration. Helper functions follow. Skip to next cell to see results. Study 1: Perceived fusion.**Note**: Results are min-max normalized per subject. ###Code study_type = 0 df = du.load_and_clean_data() df = du.min_max_norm(df) df = du.isolate_study(df, study_type) df = df.reset_index(drop=True) # The average variation of ratings, within subject, per stimulus condition. display(du.average_std_of_ratings(df).sort_values()) display(du.get_summary(df)) du.box_plot(df, study_type, savefig=True) # du.response_histograms(df, 10) # The average minimum response per stim condition, per subject. # df.groupby(['subjectNo','condition'])['response'].min().groupby('condition').mean() df['subjectNo'].nunique() ###Output _____no_output_____ ###Markdown Study 2: Perceived realismPerceived realism.**Note**:Ratings are min-max normalized per subject. ###Code study_type = 1 df = du.load_and_clean_data() df = du.isolate_study(df, study_type) df = du.min_max_norm(df) df = df.reset_index(drop=True) display(du.average_std_of_ratings(df)) display(du.get_summary(df)) du.box_plot(df, study_type, savefig=True) # du.response_histograms(df, 10) df['subjectNo'].nunique() ###Output _____no_output_____ ###Markdown Main statistical analysis Anova, T-test and check for normal distribution ###Code # Indicate study type here (0 -> fusion, 1 -> realism) study_type = 1 df = du.load_and_clean_data() df = du.isolate_study(df, study_type) df = du.min_max_norm(df) df = du.anova_prep(df) df = df.reset_index(drop=True) # ANOVA with repeated measures notes. # for condition in df['condition'].unique(): # print(f"Condition: {condition}") # display(pg.normality(df[df['condition']==condition]['rating'])) # sm.qqplot(df[df['condition']==condition]['rating'], fit=True, line="45") # plt.savefig(f"./figs/qq_studytype_{study_type}_{condition}.png", dpi=300) # display(df.rm_anova(dv='rating', within='condition', subject='subjectNo', correction=True)) # # display(pg.friedman(data=df, dv='rating', within='condition', subject='subjectNo', method='f')) tmp = df.pairwise_ttests( dv='rating', within='condition', subject='subjectNo', padjust='holm', parametric=True # False -> Use Wilcoxon ) # for i in range(4): # display(tmp.loc[i*10:i*10 + 9]) display(tmp) ###Output _____no_output_____ ###Markdown InferenceThe plan:- Multiple linear regresion, from timbre toolbox ratings to realness, fusion.- Descriptor commonalities among stimulus conditions?- Perhaps, perhaps, train three quantile linear classifiers, 25%, 50%, 75%. Post hocTables that quantify the variability in the randomized stimulus conditions. ###Code import seaborn as sns import numpy as np df = du.load_and_clean_data() tmp = du.load_tt_descriptors() df = pd.merge(tmp, df, on='stimulus') pd.set_option('display.max_columns', None) features = [ 'STFT__SpectralCentroidMed', 'STFT__SpectralCentroidIQR', 'STFT__SpectralCrestMed', 'STFT__SpectralCrestIQR', 'HARMONIC__HarmonicOddToEvenRatioMed', 'HARMONIC__HarmonicOddToEvenRatioIQR', 'HARMONIC__HarmonicEnergyIQR', 'HARMONIC__HarmonicEnergyMed', 'HARMONIC__SpectralFlatnessMed', 'HARMONIC__SpectralFlatnessIQR', # 'STFT__SpectralSpreadMed', # 'STFT__SpectralSkewnessMed', # 'STFT__SpectralKurtosisMed', # 'STFT__SpectralFlatnessMed', # 'STFT__SpectralSlopeMed', # 'STFT__SpectralDecreaseMed', # 'STFT__SpectralRollOffMed', # 'STFT__SpectralFluxMed', # 'HARMONIC__PitchIQR', # 'HARMONIC__SpectralCentroidIQR', # 'HARMONIC__SpectralSpreadIQR', # 'HARMONIC__SpectralSkewnessIQR', # 'HARMONIC__SpectralKurtosisIQR', # 'HARMONIC__SpectralCrestIQR', # 'HARMONIC__SpectralSlopeIQR', # 'HARMONIC__SpectralDecreaseIQR', # 'HARMONIC__SpectralRollOffIQR', # 'HARMONIC__SpectralVariationIQR', # 'HARMONIC__SpectralFluxIQR', # 'HARMONIC__HarmonicSpectralDeviationIQR', # 'HARMONIC__Tristimulus_1IQR', # 'HARMONIC__Tristimulus_2IQR', # 'HARMONIC__Tristimulus_3IQR', # 'HARMONIC__InharmonicityIQR', # 'HARMONIC__NoiseEnergyIQR', # 'HARMONIC__NoisinessIQR', # 'STFT__SpectralSpreadIQR', # 'STFT__SpectralSkewnessIQR', # 'STFT__SpectralKurtosisIQR', # 'STFT__SpectralFlatnessIQR', # 'STFT__SpectralSlopeIQR', # 'STFT__SpectralDecreaseIQR', # 'STFT__SpectralRollOffIQR', # 'STFT__SpectralVariationIQR', # 'STFT__SpectralFluxIQR', # 'HARMONIC__PitchMed', # 'HARMONIC__SpectralCentroidMed', # 'HARMONIC__SpectralSpreadMed', # 'HARMONIC__SpectralSkewnessMed', # 'HARMONIC__SpectralKurtosisMed', # 'HARMONIC__SpectralFlatnessMed', # 'HARMONIC__SpectralCrestMed', # 'HARMONIC__SpectralSlopeMed', # 'HARMONIC__SpectralDecreaseMed', # 'HARMONIC__SpectralRollOffMed', # 'HARMONIC__SpectralVariationMed', # 'HARMONIC__SpectralFluxMed', # 'HARMONIC__HarmonicSpectralDeviationMed', # 'HARMONIC__Tristimulus_1Med', # 'HARMONIC__Tristimulus_2Med', # 'HARMONIC__Tristimulus_3Med', # 'HARMONIC__InharmonicityMed', # 'HARMONIC__NoiseEnergyMed', # 'HARMONIC__NoisinessMed' ] corr = tmp[features].corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) # these_feats = [ # 'HARMONIC__SpectralFlatnessMed', # # 'HARMONIC__SpectralFlatnessIQR', # # 'HARMONIC__HarmonicEnergyIQR', # 'HARMONIC__HarmonicEnergyMed', # ] import copy this_feats = copy.copy(features) print('='*50 + '\nMEAN\n' + '='*50) display(df.groupby('condition')[these_feats].mean().sort_values(by='HARMONIC__SpectralFlatnessMed')) print('='*50 + '\nSTD\n' + '='*50) display(df.groupby('condition')[these_feats].std()) print('='*50 + '\nCoefficient of Variability\n' + '='*50) display(df.groupby('condition')[these_feats].std()/df.groupby('condition')[these_feats].mean()) tmp = pd.DataFrame() tmp['mean'] = df[these_feats].mean() tmp['std'] = df[these_feats].std() tmp['coefficient_of_variation'] = tmp['std']/tmp['mean'] display(tmp) ###Output ================================================== MEAN ================================================== ###Markdown Relationship between descriptors and ratings ###Code # Inspecting relationship between TT descriptors and ratings. study_type = 1 tmp_index = features + ['stimulus'] df = du.load_and_clean_data() df = du.min_max_norm(df) tt = du.load_tt_descriptors() df = pd.merge(tt[tmp_index], df, on='stimulus') df = du.isolate_study(df, study_type=study_type) print('='*20+'Correlations within subject within condition.'+'='*20) correlations = pd.DataFrame() for subject in df['subjectNo'].unique(): # Calculate within subject correlations to descriptors. tmp = df[df['subjectNo'] == subject] tmp = tmp.groupby('condition')[features].corrwith(tmp['response'], method='spearman') tmp['subjectNo'] = subject correlations = correlations.append(tmp) tmp = correlations.groupby('condition')[features].mean() display(tmp) print('='*20+'Correlations within subject.'+'='*20) for feature in features: pearson = du.within_subject_correlation(df, feature, 'pearson') spearman = du.within_subject_correlation(df, feature, 'spearman') spiel = f"{feature}, pearson = {pearson}, spearman = {spearman}" print(spiel) # Linear regression. study_type = 1 tmp_index = features + ['stimulus'] df = du.load_and_clean_data() df = du.min_max_norm(df) tt = du.load_tt_descriptors() df = pd.merge(tt[tmp_index], df, on='stimulus') df_ = du.isolate_study(df, study_type=study_type) new = df_.groupby('condition')[features + ['response']].mean() new.to_csv(f"rates_tt_study_{study_type}.csv") lm = pg.linear_regression(df_[features], df_['response']) display(lm.round(4)) sse = np.sum(lm.residuals_**2) n = 4400 k = 10 def AIC(_n, _k, _sse): return _n * np.log(_sse/_n) + 2*_k print(f"Simple multiple regression AIC:\t {AIC(n, lm.df_model_, sse)}") # formula = 'response ~ ' + ' + '.join([f + '|groups' for f in features]) model = sm.MixedLM(df_['response'],df_[features], groups=df_["subjectNo"]) result = model.fit(reml=False) print(result.summary()) print(f"AIC:\t{result.aic}") print(f"BIC:\t{result.bic}") study_type = 0 tmp_index = features + ['stimulus'] df = du.load_and_clean_data() df = du.min_max_norm(df) tt = du.load_tt_descriptors() df = pd.merge(tt[tmp_index], df, on='stimulus') tt_means = df[features].mean() # Logistic regression on quantiles. study_type = 0 tmp_index = features + ['stimulus'] df = du.load_and_clean_data() df = du.min_max_norm(df) tt = du.load_tt_descriptors() df = pd.merge(tt[tmp_index], df, on='stimulus') df = du.isolate_study(df, study_type=study_type) # Standardize. df[features] = (df[features] - df[features].mean())/df[features].std() # Range normalize. # df[features] = (df[features] - df[features].min())/(df[features].max() - df[features].min()) # Convert each subjects' ratings into 1/0 above below median. quantile = .50 df['response'] = df.groupby('subjectNo')['response'].transform( lambda x: (x < np.quantile(x, q=quantile)).astype(int) ) from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate X = df[features] y = df['response'] clf = LogisticRegression(max_iter=200) scores = cross_validate(clf, X, y, return_estimator=True, scoring=['roc_auc']) scores['estimator'][0].intercept_ # print(scores.keys()) print(f"ROC AUC:\t{scores['test_roc_auc'].mean()}") tmp = [] for est in scores['estimator']: tmp.append(est.coef_) ans = dict(zip(features, np.array(tmp).squeeze().mean(axis=0))) for key, val in ans.items(): print(f"{key}:\t{val}") ###Output ROC AUC: 0.7398858521592123 STFT__SpectralCentroidMed: 0.7128298331690445 STFT__SpectralCentroidIQR: 0.1723944030189358 STFT__SpectralCrestMed: 0.29239722320127626 STFT__SpectralCrestIQR: 0.040004440772270146 HARMONIC__HarmonicOddToEvenRatioMed: -0.04237170811944522 HARMONIC__HarmonicOddToEvenRatioIQR: -0.09168302582832635 HARMONIC__HarmonicEnergyIQR: 0.18561126441818815 HARMONIC__HarmonicEnergyMed: 0.006021138622016707 HARMONIC__SpectralFlatnessMed: -0.3148393770928664 HARMONIC__SpectralFlatnessIQR: 0.0931881909178502 ###Markdown Explorations ###Code np.mean(lm.residuals_**2) ###Output _____no_output_____
tests/notebooks/mESC-marker-only.ipynb
###Markdown mESC analysis using Cyclum with Prior Knowledge (Infinite Weights)We utilize prior knowledge by only keeping marker genes (i.e., infinite weights).We still use the mESC dataset. For simplicity we have converted the dataset into TPM.The original count data is available at ArrayExpress: [E-MTAB-2805](https://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-2805/). Tools to transform data are also provided and explained in the following sections. ###Code # Add ../../ to path import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) ###Output _____no_output_____ ###Markdown Import necessary packages ###Code %matplotlib inline %load_ext autoreload %autoreload 1 import pandas as pd import numpy as np import sklearn as skl import cyclum.tuning import cyclum.models from cyclum import writer ###Output Using TensorFlow backend. ###Markdown Read dataHere we have label, so we load both. However, the label is not used until evaluation. ###Code input_file_mask = '/home/shaoheng/Documents/data/mESC/mesc-tpm' def preprocess(input_file_mask): """ Read in data and perform log transform (log2(x+1)), centering (mean = 1) and scaling (sd = 1). """ tpm = writer.read_df_from_binary(input_file_mask).T sttpm = pd.DataFrame(data=skl.preprocessing.scale(np.log2(tpm.values + 1)), index=tpm.index, columns=tpm.columns) label = pd.read_csv(input_file_mask + '-label.txt', sep="\t", index_col=0).T return sttpm, label sttpm, label = preprocess(input_file_mask) marker_df = pd.read_table('/home/shaoheng/Documents/cyclum2/data/MGI-cell-cycle-0007049.txt', index_col=False) marker_df.head() sttpm = sttpm.loc[:, marker_df['Symbol'].unique()] sttpm = sttpm.dropna(1) sttpm.shape ###Output /home/shaoheng/miniconda3/envs/tf-gpu/lib/python3.7/site-packages/pandas/core/indexing.py:1418: FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike return self._getitem_tuple(key) ###Markdown There is no convention whether cells should be columns or rows. Here we require cells to be rows. Set up the model and fit the model ###Code model = cyclum.tuning.CyclumAutoTune(sttpm, max_linear_dims=5, epochs=500, rate=2e-4, verbose=100, encoder_width=[30, 20]) model.show_elbow() display(model.show_structure()) model.train(sttpm, epochs=1600, verbose=100, rate=2e-4) pseudotime = model.predict_pseudotime(sttpm) ###Output _____no_output_____ ###Markdown IllustrationsWe illustrate the results on a circle, to show its circular nature. There is virtually no start and end of the circle.Red, green and blue represents G0/G1, S and G2/M phase respectively.The inner lines represents single cells. The cells spread across theThe areas outside ###Code import cyclum.illustration color_map = {'stage': {"g0/g1": "red", "s": "green", "g2/m": "blue"}, 'subcluster': {"intact": "cyan", "perturbed": "violet"}} cyclum.illustration.plot_round_distr_color(pseudotime, label['stage'], color_map['stage']) pass from cyclum.hdfrw import mat2hdf mat2hdf(pseudotime, '/home/shaoheng/Documents/data/EMTAB2805/cyclum-marker-only-pseudotime.h5') ###Output _____no_output_____
Visualization_of_ResNet_101_v2.ipynb
###Markdown ###Code import tensorflow as tf import numpy as np from tensorflow import keras import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.image import img_to_array, load_img import random from PIL import Image model = tf.keras.applications.ResNet101V2(include_top=False, weights = 'imagenet', input_shape=(150,150,3)) model.summary() conv_layers = [layer for layer in model.layers if '_conv' in str(layer.name)] num_conv_layers = len(conv_layers) selected_conv_layers = [conv_layers[i] for i in [12,25,38,51,64,77,90,103]] selected_conv_layers ###Output _____no_output_____ ###Markdown Visualization of the Conv Layers of ResNet101v2 ###Code img_path = '/content/drive/MyDrive/Brain_Tumor_Classification/input/Final_Tumor_Dataset/Train/yes/Image1006.jpg' img = Image.open(img_path) img successive_outputs = [layer.output for layer in selected_conv_layers] #visualization_model = Model(img_input, successive_outputs) visualization_model = tf.keras.models.Model(inputs = model.input, outputs = successive_outputs) img = load_img(img_path, target_size=(150,150)) # this is a PIL image x = img_to_array(img) # Numpy array with shape (150, 150, 3) x = x.reshape((1,) + x.shape) # Numpy array with shape (1, 150, 150, 3) # Rescale by 1/255 x /= 255 # Let's run our image through our network, thus obtaining all # intermediate representations for this image. successive_feature_maps = visualization_model.predict(x) # These are the names of the layers, so can have them as part of our plot layer_names = [layer.name for layer in model.layers[1:]] # Now let's display our representations for layer_name, feature_map in zip(layer_names, successive_feature_maps): if len(feature_map.shape) == 4: # Just do this for the conv / maxpool layers, not the fully-connected layers n_features = 1 # number of features in feature map # The feature map has shape (1, size, size, n_features) size = feature_map.shape[1] # We will tile our images in this matrix display_grid = np.zeros((size, size * n_features)) i = random.randint(0, feature_map.shape[-1]) # Postprocess the feature to make it visually palatable x = feature_map[0, :, :, i] x -= x.mean() x /= x.std() x *= 64 x += 128 x = np.clip(x, 0, 255).astype('uint8') # We'll tile each filter into this big horizontal grid display_grid[:, 0 : size] = x # Display the grid scale = 5. / n_features plt.figure(figsize=(scale * n_features, scale)) plt.title(layer_name) plt.grid(False) plt.imshow(display_grid, aspect='auto', cmap='viridis') ###Output WARNING:tensorflow:11 out of the last 11 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fd977b804d0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. ###Markdown ConclusionIn the initial layers of the ResNet model, we can decipher what the layers are learning but as we see for the later layers of the model, the dimensions of the outputs are reduced as Convolutional layers half the dimensions and so the outputs tend to be in an encoded format and so hard to interpret. ###Code ###Output _____no_output_____
notebooks/.ipynb_checkpoints/Hello,_Colaboratory_test-checkpoint.ipynb
###Markdown [View in Colaboratory](https://colab.research.google.com/github/BlueMoon55/Python_Test/blob/master/Hello,_Colaboratory.ipynb) Colaboratory へようこそColaboratory は、機械学習の教育や研究の促進を目的とした Google 研究プロジェクトです。完全にクラウドで実行される Jupyter ノートブック環境を特別な設定なしにご利用いただけます。Colaboratory ノートブックは [Google ドライブ](https://drive.google.com)に保存され、Google ドキュメントや Google スプレッドシートと同じように共有できます。Colaboratory の利用は無料です。詳細については、[よくある質問](https://research.google.com/colaboratory/faq.html)をご覧ください。 ローカル ランタイムのサポートColaboratory では、ローカルマシン上の Jupyter ランタイムへの接続もサポートしています。詳しくは、[ドキュメント](https://research.google.com/colaboratory/local-runtimes.html)をご覧ください。 Python 3Colaboratory では、Python 2 と Python 3 の両方のコードの実行をサポートしています。* 新しいノートブックを作成するときに、Python 2 と Python 3 のいずれかを選択できます。* ノートブックに関連付けられている言語を変更することもできます。この情報は `.ipynb` ファイルに書き込まれるため、将来のセッションでも維持されます。 ###Code import sys print('Hello, Colaboratory from Python {}!'.format(sys.version_info[0])) ###Output Hello, Colaboratory from Python 3! ###Markdown TensorFlow の実行 Colaboratory では、ワンクリックで TensorFlow のコードをブラウザ上で実行できます。以下の例は 2 つのマトリックスを追加します。$\begin{bmatrix} 1. & 1. & 1. \\ 1. & 1. & 1. \\\end{bmatrix} +\begin{bmatrix} 1. & 2. & 3. \\ 4. & 5. & 6. \\\end{bmatrix} =\begin{bmatrix} 2. & 3. & 4. \\ 5. & 6. & 7. \\\end{bmatrix}$ ###Code import tensorflow as tf import numpy as np with tf.Session(): input1 = tf.constant(1.0, shape=[2, 3]) input2 = tf.constant(np.reshape(np.arange(1.0, 7.0, dtype=np.float32), (2, 3))) output = tf.add(input1, input2) result = output.eval() result ###Output _____no_output_____ ###Markdown 視覚化 Colaboratory には [matplotlib](https://matplotlib.org/) などの広く使用されているライブラリが含まれており、視覚化を簡単に行えます。 ###Code !pip install matplotlib import matplotlib.pyplot as plt import numpy as np x = np.arange(20) y = [x_i + np.random.randn(1) for x_i in x] a, b = np.polyfit(x, y, 1) _ = plt.plot(x, y, 'o', np.arange(20), a*np.arange(20)+b, '-') ###Output _____no_output_____ ###Markdown 新しいライブラリを使用する必要がある場合は、`pip install` でインストールします。一般的に使用されているライブラリをインポートする方法については、[ライブラリのインポートのサンプル ノートブック](/notebooks/snippets/importing_libraries.ipynb)をご覧ください。 ###Code # Only needs to be run once at the top of the notebook. !pip install -q matplotlib-venn # Now the newly-installed library can be used anywhere else in the notebook. from matplotlib_venn import venn2 _ = venn2(subsets = (3, 2, 1)) ###Output _____no_output_____ ###Markdown フォームフォームを使用してコード内の値をパラメータ化できます。詳しくは、[フォームのサンプル ノートブック](/notebooks/forms.ipynb)をご覧ください。 ###Code #@title Examples text = 'value' #@param date_input = '2018-03-22' #@param {type:"date"} number_slider = 0 #@param {type:"slider", min:-1, max:1, step:0.1} dropdown = '1st option' #@param ["1st option", "2nd option", "3rd option"] ###Output _____no_output_____ ###Markdown 詳細情報:- [Colaboratory の概要](/notebooks/basic_features_overview.ipynb)- [ライブラリのインポートと依存関係のインストール](/notebooks/snippets/importing_libraries.ipynb)- [マークダウンに関するガイド](/notebooks/markdown_guide.ipynb)- [グラフ](/notebooks/charts.ipynb)- [ウィジェット](/notebooks/widgets.ipynb)- [データの読み込みと保存: ローカル ファイル、Google ドライブ、Google スプレッドシート、Google Cloud Storage](/notebooks/io.ipynb)- [Google Cloud BigQuery のサンプル ノートブック](/notebooks/bigquery.ipynb)- [GPU を使用した TensorFlow](/notebooks/gpu.ipynb)- [フォーム](/notebooks/forms.ipynb) テスト用セクション ###Code !pip install janome from janome.tokenizer import Tokenizer # janome.tokenizerをインポート import re, pprint # reとpprintモジュールをインポート ''' 形態素解析を行う text :解析対象の文章 戻り値 :見出しと品詞のペアを格納した多重リスト ''' def analyze(text): t = Tokenizer() # Tokenizerオブジェクトを生成 tokens = t.tokenize(text) # 形態素解析を実行 result = [] # 形態素と品詞を格納するリスト for token in tokens: # リストからTokenオブジェクトを1つずつ取り出す result.append( # 形態素と品詞情報をリストにしてresultに追加 [token.surface, # 形態素を取得 token.part_of_speech]) # 品詞情報を取得 return(result) # 解析結果の多重リストを返す ''' 品詞が名詞であるかを調べる関数 part :形態素解析の品詞の部分 戻り値 :名詞であればTrue、そうでなければFalse ''' def keyword_check(part): return re.match( # 名詞であればTrue、それ以外ばFalseを返す '名詞,(一般|固有名詞|サ変接続|形容動詞語幹)', part ) #================================================= # プログラムの起点 #================================================= if __name__ == '__main__': print('文章を入力') S_input = input() # 文章を取得 pprint.pprint(analyze(S_input)) # 入力された文章を解析 # from analyzer import * # analyzerモジュールをインポート # import analyzer import os def make_freq(file): """テキストファイルを読み込んで形態素解析結果を返す 戻り値 : 解析結果を格納した多重リスト """ print('テキストを読み込んでいます...') with open(file, # ファイル名を指定 'r', # 読み取り専用で開く encoding = 'utf_8' # エンコード方式を指定 ) as f: text = f.read() # 全データをtextに格納 text = re.sub('\n', '', text) # 文末の改行文字を取り除く word_dic = {} # 語を保持するリスト analyze_list = analyze(text) # 形態素解析の結果をリストとして取得 for word, part in analyze_list: # 多重リストの要素を2つのパラメーターに取り出す if (keyword_check(part)): # keyword_check()関数の戻り値がTrueの場合 if word in word_dic: # 辞書に語と同じキーがあるか word_dic[word] += 1 # キーの値に1加算 else: # 該当するキーがなければ word_dic[word] = 1 # 単語をキーにして値を1にする return(word_dic) # 頻度表としての辞書を返す def show(word_dic): """頻度表を出力する """ out_file_name = 'freq_'+file_name+'.txt' file = open(out_file_name, 'w', encoding = 'utf_8') for word in sorted( word_dic, # 対象の辞書 key = word_dic.get, # 並べ替えの基準(key)を辞書の値にする reverse = True # 降順で並べ替え ): print( # キー(単語)と値(頻度)を出力 word + '(' + str(word_dic[word]) + ')' ) file.write(word + ',' + str(word_dic[word]) + '\n') file.close() #================================================= # プログラムの起点 #=====中小企業における.txt============================================ if __name__ == '__main__': print('カレントDIR: '+os.getcwd()) file_name = input('ファイル名を入力してください>>>') freq = make_freq(file_name) # 頻度表を取得する show(freq) # 画面表示 ###Output カレントDIR: /content ファイル名を入力してください>>>aa テキストを読み込んでいます...
1.5 Named Entity Recognition.ipynb
###Markdown We want to preprocess the data so that the named entities are replaced with label tag pairs. ###Code nltk.download() import nltk plot = 'An American teenager named Sean Boswell is a loner in school, however he challenges his rival for an ' + \ 'illegal street racing, and he totals his car in the end of the race. To avoid time in prison he is sent to ' + \ 'Tokyo to live with his father who is in the military. As soon as he arrives he discovers a new, fun but ' + \ 'dangerous way of street racing in the underworld of the streets of Tokyo, Japan. Sean Boswell, an Alabama ' + \ 'teenager with a record for street racing, moves to his father\'s resident city of Tokyo, Japan to avoid a ' + \ 'prison sentence in America. Boswell quickly falls in love with the world of drift racing in Tokyo\'s ' + \ 'underground and a Japanese girl named Neela. However, Boswell\'s presence and growing talent for drifting ' + \ 'unsettles the Japanese Mafia, which makes thousands of dollars from the sport. Confrontations arise, and ' + \ 'Sean is faced with a simple decision: drift or die. After totaling his car in an illegal street race, ' + \ 'Shaun Boswell is sent to live with his father, who is in the military, in Tokyo, Japan, to avoid '+ \ 'juvy or even jail. While in school, he befriends Twinkie, a "military brat." Twinkie introduces him to ' + \ 'the world of racing in Japan. Though forbidden to drive, he decides to race against D.K., the "Drift King", ' + \ 'who has ties to the Yakuza, and loses, totaling the car because of his lack of knowledge of drifting, ' + \ 'racing that involves dangerous hair pin turns. To repay his debt, he enters the underground world of drift ' + \ 'street racing. As he becomes better and better, he must finally prove his worth in that world by once again ' + \ 'racing D.K. Sean Boswell, who has always been an outsider. A loner at school, his only connection to the ' + \ 'indifferent world around him is through illegal street racing -- which has made him particularly unpopular ' + \ 'with the local authorities. To avoid jail time, Sean is sent out of the country to live with his Farther in ' + \ 'the military, in a cramped apartment in a low-rent section of Tokyo. In the land that gave birth to the ' + \ 'majority of modified racers on the road, the simple street race has been replaced by the ultimate ' + \ 'pedal-to-the-metal, gravity-defying automotive challenge ... drift racing, a deadly combination of brutal ' + \ 'speed on heart stopping courses of hairpin turns and switchbacks. For his first unsuccessful foray in drift ' + \ 'racing, Shean unknowingly takes on D.K., the "Drift King," with ties to the Yakuza, the Japanese ' + \ 'crime machine. The only way he can pay off the debt of his loss is to venture into the deadly realm of the ' + \ 'Tokyo underworld, where the stakes are life and death. To avoid jail time, street racer Sean Boswell is sent ' + \ 'to live with his father in Tokyo. There he discovers drift racing. After losing a race to Yakuza-connected ' + \ 'D.K., the Drift King, Sean has to enter the Tokyo underworld to find a way to pay his debt.' tokenized = nltk.word_tokenize(plot) tagged = nltk.pos_tag(tokenized) #print(tagged) namedEnt = nltk.ne_chunk(tagged) sean = namedEnt[4] teenager = namedEnt[2] print(namedEnt[4]) print(namedEnt[4].label()) print(namedEnt[4][0][1]) print(namedEnt[2]) def ne(doc): tokenized = nltk.word_tokenize(doc) tagged = nltk.pos_tag(tokenized) namedEnt = nltk.ne_chunk(tagged) return ' '.join([(e.label()+'_'+e[0][1]) if isinstance(e,nltk.tree.Tree) else e[0] for e in namedEnt]) ne(plot) import io, json from collections import OrderedDict def load_movies(path): """ Loads the data into memory. """ with io.open(path, 'r', encoding = 'latin-1') as f: movies = json.load(f) od = OrderedDict({(movie['title'],movie['year']):{'plot':movie['plot'],'cast':set(movie['cast']), \ 'genres':set(movie['genres'])} \ for movie in movies}.items()) return od def write_movies(movies, path): with io.open(path, 'w', encoding='latin-1') as f: data = [{'title':title,'year':year,'plot':val['plot'], 'cast':list(val['cast']), \ 'genres':list(val['genres'])} for (title,year),val in movies.items()] f.write(json.dumps(data, ensure_ascii=False)) movies = load_movies('data.json') for movie, val in movies.items(): plot = val['plot'] val['plot'] = ne(plot) write_movies(movies, 'ne_data.json') ###Output _____no_output_____
.ipynb_checkpoints/Ensemble_Models-checkpoint.ipynb
###Markdown Load in the Validation and Test Set ###Code X_val = np.load("/Users/Hoang/Machine_Learning/skin_cancer/skin_cancer_192_256/256_192_val.npy") X_test = np.load("/Users/Hoang/Machine_Learning/skin_cancer/skin_cancer_192_256/256_192_test.npy") y_val = np.load("/Users/Hoang/Machine_Learning/skin_cancer/skin_cancer_192_256/val_labels.npy") y_test = np.load("/Users/Hoang/Machine_Learning/skin_cancer/skin_cancer_192_256/test_labels.npy") y_val = to_categorical(y_val) y_test = to_categorical(y_test) X_val.shape, X_test.shape, y_val.shape, y_test.shape input_shape = X_val[0,:,:,:].shape model_input = Input(shape=input_shape) ###Output _____no_output_____ ###Markdown Define InceptionV3 ###Code inception = InceptionV3(input_shape=input_shape, input_tensor=model_input, include_top=False, weights=None) for layer in inception.layers: layer.trainable = True inception_last_layer = inception.get_layer('mixed10') print('last layer output shape:', inception_last_layer.output_shape) inception_last_output = inception_last_layer.output # Flatten the output layer to 1 dimension x_inception = layers.GlobalMaxPooling2D()(inception_last_output) # Add a fully connected layer with 512 hidden units and ReLU activation x_inception = layers.Dense(512, activation='relu')(x_inception) # Add a dropout rate of 0.7 x_inception = layers.Dropout(0.5)(x_inception) # Add a final sigmoid layer for classification x_inception = layers.Dense(7, activation='softmax')(x_inception) # Configure and compile the model inception_model = Model(model_input, x_inception) optimizer = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=True) inception_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) inception_model.load_weights("InceptionV3full.h5") inception_model.summary() ###Output __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_1 (InputLayer) (None, 192, 256, 3) 0 __________________________________________________________________________________________________ conv2d_185 (Conv2D) (None, 95, 127, 32) 864 input_1[0][0] __________________________________________________________________________________________________ batch_normalization_185 (BatchN (None, 95, 127, 32) 96 conv2d_185[0][0] __________________________________________________________________________________________________ activation_184 (Activation) (None, 95, 127, 32) 0 batch_normalization_185[0][0] __________________________________________________________________________________________________ conv2d_186 (Conv2D) (None, 93, 125, 32) 9216 activation_184[0][0] __________________________________________________________________________________________________ batch_normalization_186 (BatchN (None, 93, 125, 32) 96 conv2d_186[0][0] __________________________________________________________________________________________________ activation_185 (Activation) (None, 93, 125, 32) 0 batch_normalization_186[0][0] __________________________________________________________________________________________________ conv2d_187 (Conv2D) (None, 93, 125, 64) 18432 activation_185[0][0] __________________________________________________________________________________________________ batch_normalization_187 (BatchN (None, 93, 125, 64) 192 conv2d_187[0][0] __________________________________________________________________________________________________ activation_186 (Activation) (None, 93, 125, 64) 0 batch_normalization_187[0][0] __________________________________________________________________________________________________ max_pooling2d_9 (MaxPooling2D) (None, 46, 62, 64) 0 activation_186[0][0] __________________________________________________________________________________________________ conv2d_188 (Conv2D) (None, 46, 62, 80) 5120 max_pooling2d_9[0][0] __________________________________________________________________________________________________ batch_normalization_188 (BatchN (None, 46, 62, 80) 240 conv2d_188[0][0] __________________________________________________________________________________________________ activation_187 (Activation) (None, 46, 62, 80) 0 batch_normalization_188[0][0] __________________________________________________________________________________________________ conv2d_189 (Conv2D) (None, 44, 60, 192) 138240 activation_187[0][0] __________________________________________________________________________________________________ batch_normalization_189 (BatchN (None, 44, 60, 192) 576 conv2d_189[0][0] __________________________________________________________________________________________________ activation_188 (Activation) (None, 44, 60, 192) 0 batch_normalization_189[0][0] __________________________________________________________________________________________________ max_pooling2d_10 (MaxPooling2D) (None, 21, 29, 192) 0 activation_188[0][0] __________________________________________________________________________________________________ conv2d_193 (Conv2D) (None, 21, 29, 64) 12288 max_pooling2d_10[0][0] __________________________________________________________________________________________________ batch_normalization_193 (BatchN (None, 21, 29, 64) 192 conv2d_193[0][0] __________________________________________________________________________________________________ activation_192 (Activation) (None, 21, 29, 64) 0 batch_normalization_193[0][0] __________________________________________________________________________________________________ conv2d_191 (Conv2D) (None, 21, 29, 48) 9216 max_pooling2d_10[0][0] __________________________________________________________________________________________________ conv2d_194 (Conv2D) (None, 21, 29, 96) 55296 activation_192[0][0] __________________________________________________________________________________________________ batch_normalization_191 (BatchN (None, 21, 29, 48) 144 conv2d_191[0][0] __________________________________________________________________________________________________ batch_normalization_194 (BatchN (None, 21, 29, 96) 288 conv2d_194[0][0] __________________________________________________________________________________________________ activation_190 (Activation) (None, 21, 29, 48) 0 batch_normalization_191[0][0] __________________________________________________________________________________________________ activation_193 (Activation) (None, 21, 29, 96) 0 batch_normalization_194[0][0] __________________________________________________________________________________________________ average_pooling2d_18 (AveragePo (None, 21, 29, 192) 0 max_pooling2d_10[0][0] __________________________________________________________________________________________________ conv2d_190 (Conv2D) (None, 21, 29, 64) 12288 max_pooling2d_10[0][0] __________________________________________________________________________________________________ conv2d_192 (Conv2D) (None, 21, 29, 64) 76800 activation_190[0][0] __________________________________________________________________________________________________ conv2d_195 (Conv2D) (None, 21, 29, 96) 82944 activation_193[0][0] __________________________________________________________________________________________________ conv2d_196 (Conv2D) (None, 21, 29, 32) 6144 average_pooling2d_18[0][0] __________________________________________________________________________________________________ batch_normalization_190 (BatchN (None, 21, 29, 64) 192 conv2d_190[0][0] __________________________________________________________________________________________________ batch_normalization_192 (BatchN (None, 21, 29, 64) 192 conv2d_192[0][0] __________________________________________________________________________________________________ batch_normalization_195 (BatchN (None, 21, 29, 96) 288 conv2d_195[0][0] __________________________________________________________________________________________________ batch_normalization_196 (BatchN (None, 21, 29, 32) 96 conv2d_196[0][0] __________________________________________________________________________________________________ activation_189 (Activation) (None, 21, 29, 64) 0 batch_normalization_190[0][0] __________________________________________________________________________________________________ activation_191 (Activation) (None, 21, 29, 64) 0 batch_normalization_192[0][0] __________________________________________________________________________________________________ activation_194 (Activation) (None, 21, 29, 96) 0 batch_normalization_195[0][0] __________________________________________________________________________________________________ activation_195 (Activation) (None, 21, 29, 32) 0 batch_normalization_196[0][0] __________________________________________________________________________________________________ mixed0 (Concatenate) (None, 21, 29, 256) 0 activation_189[0][0] activation_191[0][0] activation_194[0][0] activation_195[0][0] __________________________________________________________________________________________________ conv2d_200 (Conv2D) (None, 21, 29, 64) 16384 mixed0[0][0] __________________________________________________________________________________________________ batch_normalization_200 (BatchN (None, 21, 29, 64) 192 conv2d_200[0][0] __________________________________________________________________________________________________ activation_199 (Activation) (None, 21, 29, 64) 0 batch_normalization_200[0][0] __________________________________________________________________________________________________ conv2d_198 (Conv2D) (None, 21, 29, 48) 12288 mixed0[0][0] __________________________________________________________________________________________________ conv2d_201 (Conv2D) (None, 21, 29, 96) 55296 activation_199[0][0] __________________________________________________________________________________________________ batch_normalization_198 (BatchN (None, 21, 29, 48) 144 conv2d_198[0][0] __________________________________________________________________________________________________ batch_normalization_201 (BatchN (None, 21, 29, 96) 288 conv2d_201[0][0] __________________________________________________________________________________________________ activation_197 (Activation) (None, 21, 29, 48) 0 batch_normalization_198[0][0] __________________________________________________________________________________________________ activation_200 (Activation) (None, 21, 29, 96) 0 batch_normalization_201[0][0] __________________________________________________________________________________________________ average_pooling2d_19 (AveragePo (None, 21, 29, 256) 0 mixed0[0][0] __________________________________________________________________________________________________ conv2d_197 (Conv2D) (None, 21, 29, 64) 16384 mixed0[0][0] __________________________________________________________________________________________________ conv2d_199 (Conv2D) (None, 21, 29, 64) 76800 activation_197[0][0] __________________________________________________________________________________________________ conv2d_202 (Conv2D) (None, 21, 29, 96) 82944 activation_200[0][0] __________________________________________________________________________________________________ conv2d_203 (Conv2D) (None, 21, 29, 64) 16384 average_pooling2d_19[0][0] __________________________________________________________________________________________________ batch_normalization_197 (BatchN (None, 21, 29, 64) 192 conv2d_197[0][0] __________________________________________________________________________________________________ batch_normalization_199 (BatchN (None, 21, 29, 64) 192 conv2d_199[0][0] __________________________________________________________________________________________________ batch_normalization_202 (BatchN (None, 21, 29, 96) 288 conv2d_202[0][0] __________________________________________________________________________________________________ batch_normalization_203 (BatchN (None, 21, 29, 64) 192 conv2d_203[0][0] __________________________________________________________________________________________________ activation_196 (Activation) (None, 21, 29, 64) 0 batch_normalization_197[0][0] __________________________________________________________________________________________________ activation_198 (Activation) (None, 21, 29, 64) 0 batch_normalization_199[0][0] __________________________________________________________________________________________________ activation_201 (Activation) (None, 21, 29, 96) 0 batch_normalization_202[0][0] __________________________________________________________________________________________________ activation_202 (Activation) (None, 21, 29, 64) 0 batch_normalization_203[0][0] __________________________________________________________________________________________________ mixed1 (Concatenate) (None, 21, 29, 288) 0 activation_196[0][0] activation_198[0][0] activation_201[0][0] activation_202[0][0] __________________________________________________________________________________________________ conv2d_207 (Conv2D) (None, 21, 29, 64) 18432 mixed1[0][0] __________________________________________________________________________________________________ batch_normalization_207 (BatchN (None, 21, 29, 64) 192 conv2d_207[0][0] __________________________________________________________________________________________________ activation_206 (Activation) (None, 21, 29, 64) 0 batch_normalization_207[0][0] __________________________________________________________________________________________________ conv2d_205 (Conv2D) (None, 21, 29, 48) 13824 mixed1[0][0] __________________________________________________________________________________________________ conv2d_208 (Conv2D) (None, 21, 29, 96) 55296 activation_206[0][0] __________________________________________________________________________________________________ batch_normalization_205 (BatchN (None, 21, 29, 48) 144 conv2d_205[0][0] __________________________________________________________________________________________________ batch_normalization_208 (BatchN (None, 21, 29, 96) 288 conv2d_208[0][0] __________________________________________________________________________________________________ activation_204 (Activation) (None, 21, 29, 48) 0 batch_normalization_205[0][0] __________________________________________________________________________________________________ activation_207 (Activation) (None, 21, 29, 96) 0 batch_normalization_208[0][0] __________________________________________________________________________________________________ average_pooling2d_20 (AveragePo (None, 21, 29, 288) 0 mixed1[0][0] __________________________________________________________________________________________________ conv2d_204 (Conv2D) (None, 21, 29, 64) 18432 mixed1[0][0] __________________________________________________________________________________________________ conv2d_206 (Conv2D) (None, 21, 29, 64) 76800 activation_204[0][0] __________________________________________________________________________________________________ conv2d_209 (Conv2D) (None, 21, 29, 96) 82944 activation_207[0][0] __________________________________________________________________________________________________ conv2d_210 (Conv2D) (None, 21, 29, 64) 18432 average_pooling2d_20[0][0] __________________________________________________________________________________________________ batch_normalization_204 (BatchN (None, 21, 29, 64) 192 conv2d_204[0][0] __________________________________________________________________________________________________ batch_normalization_206 (BatchN (None, 21, 29, 64) 192 conv2d_206[0][0] __________________________________________________________________________________________________ batch_normalization_209 (BatchN (None, 21, 29, 96) 288 conv2d_209[0][0] __________________________________________________________________________________________________ batch_normalization_210 (BatchN (None, 21, 29, 64) 192 conv2d_210[0][0] __________________________________________________________________________________________________ activation_203 (Activation) (None, 21, 29, 64) 0 batch_normalization_204[0][0] __________________________________________________________________________________________________ activation_205 (Activation) (None, 21, 29, 64) 0 batch_normalization_206[0][0] __________________________________________________________________________________________________ activation_208 (Activation) (None, 21, 29, 96) 0 batch_normalization_209[0][0] __________________________________________________________________________________________________ activation_209 (Activation) (None, 21, 29, 64) 0 batch_normalization_210[0][0] __________________________________________________________________________________________________ mixed2 (Concatenate) (None, 21, 29, 288) 0 activation_203[0][0] activation_205[0][0] activation_208[0][0] activation_209[0][0] __________________________________________________________________________________________________ conv2d_212 (Conv2D) (None, 21, 29, 64) 18432 mixed2[0][0] __________________________________________________________________________________________________ batch_normalization_212 (BatchN (None, 21, 29, 64) 192 conv2d_212[0][0] __________________________________________________________________________________________________ activation_211 (Activation) (None, 21, 29, 64) 0 batch_normalization_212[0][0] __________________________________________________________________________________________________ conv2d_213 (Conv2D) (None, 21, 29, 96) 55296 activation_211[0][0] __________________________________________________________________________________________________ batch_normalization_213 (BatchN (None, 21, 29, 96) 288 conv2d_213[0][0] __________________________________________________________________________________________________ activation_212 (Activation) (None, 21, 29, 96) 0 batch_normalization_213[0][0] __________________________________________________________________________________________________ conv2d_211 (Conv2D) (None, 10, 14, 384) 995328 mixed2[0][0] __________________________________________________________________________________________________ conv2d_214 (Conv2D) (None, 10, 14, 96) 82944 activation_212[0][0] __________________________________________________________________________________________________ batch_normalization_211 (BatchN (None, 10, 14, 384) 1152 conv2d_211[0][0] __________________________________________________________________________________________________ batch_normalization_214 (BatchN (None, 10, 14, 96) 288 conv2d_214[0][0] __________________________________________________________________________________________________ activation_210 (Activation) (None, 10, 14, 384) 0 batch_normalization_211[0][0] __________________________________________________________________________________________________ activation_213 (Activation) (None, 10, 14, 96) 0 batch_normalization_214[0][0] __________________________________________________________________________________________________ max_pooling2d_11 (MaxPooling2D) (None, 10, 14, 288) 0 mixed2[0][0] __________________________________________________________________________________________________ mixed3 (Concatenate) (None, 10, 14, 768) 0 activation_210[0][0] activation_213[0][0] max_pooling2d_11[0][0] __________________________________________________________________________________________________ conv2d_219 (Conv2D) (None, 10, 14, 128) 98304 mixed3[0][0] __________________________________________________________________________________________________ batch_normalization_219 (BatchN (None, 10, 14, 128) 384 conv2d_219[0][0] __________________________________________________________________________________________________ activation_218 (Activation) (None, 10, 14, 128) 0 batch_normalization_219[0][0] __________________________________________________________________________________________________ conv2d_220 (Conv2D) (None, 10, 14, 128) 114688 activation_218[0][0] __________________________________________________________________________________________________ batch_normalization_220 (BatchN (None, 10, 14, 128) 384 conv2d_220[0][0] __________________________________________________________________________________________________ activation_219 (Activation) (None, 10, 14, 128) 0 batch_normalization_220[0][0] __________________________________________________________________________________________________ conv2d_216 (Conv2D) (None, 10, 14, 128) 98304 mixed3[0][0] __________________________________________________________________________________________________ conv2d_221 (Conv2D) (None, 10, 14, 128) 114688 activation_219[0][0] __________________________________________________________________________________________________ batch_normalization_216 (BatchN (None, 10, 14, 128) 384 conv2d_216[0][0] __________________________________________________________________________________________________ batch_normalization_221 (BatchN (None, 10, 14, 128) 384 conv2d_221[0][0] __________________________________________________________________________________________________ activation_215 (Activation) (None, 10, 14, 128) 0 batch_normalization_216[0][0] __________________________________________________________________________________________________ activation_220 (Activation) (None, 10, 14, 128) 0 batch_normalization_221[0][0] __________________________________________________________________________________________________ conv2d_217 (Conv2D) (None, 10, 14, 128) 114688 activation_215[0][0] __________________________________________________________________________________________________ conv2d_222 (Conv2D) (None, 10, 14, 128) 114688 activation_220[0][0] __________________________________________________________________________________________________ batch_normalization_217 (BatchN (None, 10, 14, 128) 384 conv2d_217[0][0] __________________________________________________________________________________________________ batch_normalization_222 (BatchN (None, 10, 14, 128) 384 conv2d_222[0][0] __________________________________________________________________________________________________ activation_216 (Activation) (None, 10, 14, 128) 0 batch_normalization_217[0][0] __________________________________________________________________________________________________ activation_221 (Activation) (None, 10, 14, 128) 0 batch_normalization_222[0][0] __________________________________________________________________________________________________ average_pooling2d_21 (AveragePo (None, 10, 14, 768) 0 mixed3[0][0] __________________________________________________________________________________________________ conv2d_215 (Conv2D) (None, 10, 14, 192) 147456 mixed3[0][0] __________________________________________________________________________________________________ conv2d_218 (Conv2D) (None, 10, 14, 192) 172032 activation_216[0][0] __________________________________________________________________________________________________ conv2d_223 (Conv2D) (None, 10, 14, 192) 172032 activation_221[0][0] __________________________________________________________________________________________________ conv2d_224 (Conv2D) (None, 10, 14, 192) 147456 average_pooling2d_21[0][0] __________________________________________________________________________________________________ batch_normalization_215 (BatchN (None, 10, 14, 192) 576 conv2d_215[0][0] __________________________________________________________________________________________________ batch_normalization_218 (BatchN (None, 10, 14, 192) 576 conv2d_218[0][0] __________________________________________________________________________________________________ batch_normalization_223 (BatchN (None, 10, 14, 192) 576 conv2d_223[0][0] __________________________________________________________________________________________________ batch_normalization_224 (BatchN (None, 10, 14, 192) 576 conv2d_224[0][0] __________________________________________________________________________________________________ activation_214 (Activation) (None, 10, 14, 192) 0 batch_normalization_215[0][0] __________________________________________________________________________________________________ activation_217 (Activation) (None, 10, 14, 192) 0 batch_normalization_218[0][0] __________________________________________________________________________________________________ activation_222 (Activation) (None, 10, 14, 192) 0 batch_normalization_223[0][0] __________________________________________________________________________________________________ activation_223 (Activation) (None, 10, 14, 192) 0 batch_normalization_224[0][0] __________________________________________________________________________________________________ mixed4 (Concatenate) (None, 10, 14, 768) 0 activation_214[0][0] activation_217[0][0] activation_222[0][0] activation_223[0][0] __________________________________________________________________________________________________ conv2d_229 (Conv2D) (None, 10, 14, 160) 122880 mixed4[0][0] __________________________________________________________________________________________________ batch_normalization_229 (BatchN (None, 10, 14, 160) 480 conv2d_229[0][0] __________________________________________________________________________________________________ activation_228 (Activation) (None, 10, 14, 160) 0 batch_normalization_229[0][0] __________________________________________________________________________________________________ conv2d_230 (Conv2D) (None, 10, 14, 160) 179200 activation_228[0][0] __________________________________________________________________________________________________ batch_normalization_230 (BatchN (None, 10, 14, 160) 480 conv2d_230[0][0] __________________________________________________________________________________________________ activation_229 (Activation) (None, 10, 14, 160) 0 batch_normalization_230[0][0] __________________________________________________________________________________________________ conv2d_226 (Conv2D) (None, 10, 14, 160) 122880 mixed4[0][0] __________________________________________________________________________________________________ conv2d_231 (Conv2D) (None, 10, 14, 160) 179200 activation_229[0][0] __________________________________________________________________________________________________ batch_normalization_226 (BatchN (None, 10, 14, 160) 480 conv2d_226[0][0] __________________________________________________________________________________________________ batch_normalization_231 (BatchN (None, 10, 14, 160) 480 conv2d_231[0][0] __________________________________________________________________________________________________ activation_225 (Activation) (None, 10, 14, 160) 0 batch_normalization_226[0][0] __________________________________________________________________________________________________ activation_230 (Activation) (None, 10, 14, 160) 0 batch_normalization_231[0][0] __________________________________________________________________________________________________ conv2d_227 (Conv2D) (None, 10, 14, 160) 179200 activation_225[0][0] __________________________________________________________________________________________________ conv2d_232 (Conv2D) (None, 10, 14, 160) 179200 activation_230[0][0] __________________________________________________________________________________________________ batch_normalization_227 (BatchN (None, 10, 14, 160) 480 conv2d_227[0][0] __________________________________________________________________________________________________ batch_normalization_232 (BatchN (None, 10, 14, 160) 480 conv2d_232[0][0] __________________________________________________________________________________________________ activation_226 (Activation) (None, 10, 14, 160) 0 batch_normalization_227[0][0] __________________________________________________________________________________________________ activation_231 (Activation) (None, 10, 14, 160) 0 batch_normalization_232[0][0] __________________________________________________________________________________________________ average_pooling2d_22 (AveragePo (None, 10, 14, 768) 0 mixed4[0][0] __________________________________________________________________________________________________ conv2d_225 (Conv2D) (None, 10, 14, 192) 147456 mixed4[0][0] __________________________________________________________________________________________________ conv2d_228 (Conv2D) (None, 10, 14, 192) 215040 activation_226[0][0] __________________________________________________________________________________________________ conv2d_233 (Conv2D) (None, 10, 14, 192) 215040 activation_231[0][0] __________________________________________________________________________________________________ conv2d_234 (Conv2D) (None, 10, 14, 192) 147456 average_pooling2d_22[0][0] __________________________________________________________________________________________________ batch_normalization_225 (BatchN (None, 10, 14, 192) 576 conv2d_225[0][0] __________________________________________________________________________________________________ batch_normalization_228 (BatchN (None, 10, 14, 192) 576 conv2d_228[0][0] __________________________________________________________________________________________________ batch_normalization_233 (BatchN (None, 10, 14, 192) 576 conv2d_233[0][0] __________________________________________________________________________________________________ batch_normalization_234 (BatchN (None, 10, 14, 192) 576 conv2d_234[0][0] __________________________________________________________________________________________________ activation_224 (Activation) (None, 10, 14, 192) 0 batch_normalization_225[0][0] __________________________________________________________________________________________________ activation_227 (Activation) (None, 10, 14, 192) 0 batch_normalization_228[0][0] __________________________________________________________________________________________________ activation_232 (Activation) (None, 10, 14, 192) 0 batch_normalization_233[0][0] __________________________________________________________________________________________________ activation_233 (Activation) (None, 10, 14, 192) 0 batch_normalization_234[0][0] __________________________________________________________________________________________________ mixed5 (Concatenate) (None, 10, 14, 768) 0 activation_224[0][0] activation_227[0][0] activation_232[0][0] activation_233[0][0] __________________________________________________________________________________________________ conv2d_239 (Conv2D) (None, 10, 14, 160) 122880 mixed5[0][0] __________________________________________________________________________________________________ batch_normalization_239 (BatchN (None, 10, 14, 160) 480 conv2d_239[0][0] __________________________________________________________________________________________________ activation_238 (Activation) (None, 10, 14, 160) 0 batch_normalization_239[0][0] __________________________________________________________________________________________________ conv2d_240 (Conv2D) (None, 10, 14, 160) 179200 activation_238[0][0] __________________________________________________________________________________________________ batch_normalization_240 (BatchN (None, 10, 14, 160) 480 conv2d_240[0][0] __________________________________________________________________________________________________ activation_239 (Activation) (None, 10, 14, 160) 0 batch_normalization_240[0][0] __________________________________________________________________________________________________ conv2d_236 (Conv2D) (None, 10, 14, 160) 122880 mixed5[0][0] __________________________________________________________________________________________________ conv2d_241 (Conv2D) (None, 10, 14, 160) 179200 activation_239[0][0] __________________________________________________________________________________________________ batch_normalization_236 (BatchN (None, 10, 14, 160) 480 conv2d_236[0][0] __________________________________________________________________________________________________ batch_normalization_241 (BatchN (None, 10, 14, 160) 480 conv2d_241[0][0] __________________________________________________________________________________________________ activation_235 (Activation) (None, 10, 14, 160) 0 batch_normalization_236[0][0] __________________________________________________________________________________________________ activation_240 (Activation) (None, 10, 14, 160) 0 batch_normalization_241[0][0] __________________________________________________________________________________________________ conv2d_237 (Conv2D) (None, 10, 14, 160) 179200 activation_235[0][0] __________________________________________________________________________________________________ conv2d_242 (Conv2D) (None, 10, 14, 160) 179200 activation_240[0][0] __________________________________________________________________________________________________ batch_normalization_237 (BatchN (None, 10, 14, 160) 480 conv2d_237[0][0] __________________________________________________________________________________________________ batch_normalization_242 (BatchN (None, 10, 14, 160) 480 conv2d_242[0][0] __________________________________________________________________________________________________ activation_236 (Activation) (None, 10, 14, 160) 0 batch_normalization_237[0][0] __________________________________________________________________________________________________ activation_241 (Activation) (None, 10, 14, 160) 0 batch_normalization_242[0][0] __________________________________________________________________________________________________ average_pooling2d_23 (AveragePo (None, 10, 14, 768) 0 mixed5[0][0] __________________________________________________________________________________________________ conv2d_235 (Conv2D) (None, 10, 14, 192) 147456 mixed5[0][0] __________________________________________________________________________________________________ conv2d_238 (Conv2D) (None, 10, 14, 192) 215040 activation_236[0][0] __________________________________________________________________________________________________ conv2d_243 (Conv2D) (None, 10, 14, 192) 215040 activation_241[0][0] __________________________________________________________________________________________________ conv2d_244 (Conv2D) (None, 10, 14, 192) 147456 average_pooling2d_23[0][0] __________________________________________________________________________________________________ batch_normalization_235 (BatchN (None, 10, 14, 192) 576 conv2d_235[0][0] __________________________________________________________________________________________________ batch_normalization_238 (BatchN (None, 10, 14, 192) 576 conv2d_238[0][0] __________________________________________________________________________________________________ batch_normalization_243 (BatchN (None, 10, 14, 192) 576 conv2d_243[0][0] __________________________________________________________________________________________________ batch_normalization_244 (BatchN (None, 10, 14, 192) 576 conv2d_244[0][0] __________________________________________________________________________________________________ activation_234 (Activation) (None, 10, 14, 192) 0 batch_normalization_235[0][0] __________________________________________________________________________________________________ activation_237 (Activation) (None, 10, 14, 192) 0 batch_normalization_238[0][0] __________________________________________________________________________________________________ activation_242 (Activation) (None, 10, 14, 192) 0 batch_normalization_243[0][0] __________________________________________________________________________________________________ activation_243 (Activation) (None, 10, 14, 192) 0 batch_normalization_244[0][0] __________________________________________________________________________________________________ mixed6 (Concatenate) (None, 10, 14, 768) 0 activation_234[0][0] activation_237[0][0] activation_242[0][0] activation_243[0][0] __________________________________________________________________________________________________ conv2d_249 (Conv2D) (None, 10, 14, 192) 147456 mixed6[0][0] __________________________________________________________________________________________________ batch_normalization_249 (BatchN (None, 10, 14, 192) 576 conv2d_249[0][0] __________________________________________________________________________________________________ activation_248 (Activation) (None, 10, 14, 192) 0 batch_normalization_249[0][0] __________________________________________________________________________________________________ conv2d_250 (Conv2D) (None, 10, 14, 192) 258048 activation_248[0][0] __________________________________________________________________________________________________ batch_normalization_250 (BatchN (None, 10, 14, 192) 576 conv2d_250[0][0] __________________________________________________________________________________________________ activation_249 (Activation) (None, 10, 14, 192) 0 batch_normalization_250[0][0] __________________________________________________________________________________________________ conv2d_246 (Conv2D) (None, 10, 14, 192) 147456 mixed6[0][0] __________________________________________________________________________________________________ conv2d_251 (Conv2D) (None, 10, 14, 192) 258048 activation_249[0][0] __________________________________________________________________________________________________ batch_normalization_246 (BatchN (None, 10, 14, 192) 576 conv2d_246[0][0] __________________________________________________________________________________________________ batch_normalization_251 (BatchN (None, 10, 14, 192) 576 conv2d_251[0][0] __________________________________________________________________________________________________ activation_245 (Activation) (None, 10, 14, 192) 0 batch_normalization_246[0][0] __________________________________________________________________________________________________ activation_250 (Activation) (None, 10, 14, 192) 0 batch_normalization_251[0][0] __________________________________________________________________________________________________ conv2d_247 (Conv2D) (None, 10, 14, 192) 258048 activation_245[0][0] __________________________________________________________________________________________________ conv2d_252 (Conv2D) (None, 10, 14, 192) 258048 activation_250[0][0] __________________________________________________________________________________________________ batch_normalization_247 (BatchN (None, 10, 14, 192) 576 conv2d_247[0][0] __________________________________________________________________________________________________ batch_normalization_252 (BatchN (None, 10, 14, 192) 576 conv2d_252[0][0] __________________________________________________________________________________________________ activation_246 (Activation) (None, 10, 14, 192) 0 batch_normalization_247[0][0] __________________________________________________________________________________________________ activation_251 (Activation) (None, 10, 14, 192) 0 batch_normalization_252[0][0] __________________________________________________________________________________________________ average_pooling2d_24 (AveragePo (None, 10, 14, 768) 0 mixed6[0][0] __________________________________________________________________________________________________ conv2d_245 (Conv2D) (None, 10, 14, 192) 147456 mixed6[0][0] __________________________________________________________________________________________________ conv2d_248 (Conv2D) (None, 10, 14, 192) 258048 activation_246[0][0] __________________________________________________________________________________________________ conv2d_253 (Conv2D) (None, 10, 14, 192) 258048 activation_251[0][0] __________________________________________________________________________________________________ conv2d_254 (Conv2D) (None, 10, 14, 192) 147456 average_pooling2d_24[0][0] __________________________________________________________________________________________________ batch_normalization_245 (BatchN (None, 10, 14, 192) 576 conv2d_245[0][0] __________________________________________________________________________________________________ batch_normalization_248 (BatchN (None, 10, 14, 192) 576 conv2d_248[0][0] __________________________________________________________________________________________________ batch_normalization_253 (BatchN (None, 10, 14, 192) 576 conv2d_253[0][0] __________________________________________________________________________________________________ batch_normalization_254 (BatchN (None, 10, 14, 192) 576 conv2d_254[0][0] __________________________________________________________________________________________________ activation_244 (Activation) (None, 10, 14, 192) 0 batch_normalization_245[0][0] __________________________________________________________________________________________________ activation_247 (Activation) (None, 10, 14, 192) 0 batch_normalization_248[0][0] __________________________________________________________________________________________________ activation_252 (Activation) (None, 10, 14, 192) 0 batch_normalization_253[0][0] __________________________________________________________________________________________________ activation_253 (Activation) (None, 10, 14, 192) 0 batch_normalization_254[0][0] __________________________________________________________________________________________________ mixed7 (Concatenate) (None, 10, 14, 768) 0 activation_244[0][0] activation_247[0][0] activation_252[0][0] activation_253[0][0] __________________________________________________________________________________________________ conv2d_257 (Conv2D) (None, 10, 14, 192) 147456 mixed7[0][0] __________________________________________________________________________________________________ batch_normalization_257 (BatchN (None, 10, 14, 192) 576 conv2d_257[0][0] __________________________________________________________________________________________________ activation_256 (Activation) (None, 10, 14, 192) 0 batch_normalization_257[0][0] __________________________________________________________________________________________________ conv2d_258 (Conv2D) (None, 10, 14, 192) 258048 activation_256[0][0] __________________________________________________________________________________________________ batch_normalization_258 (BatchN (None, 10, 14, 192) 576 conv2d_258[0][0] __________________________________________________________________________________________________ activation_257 (Activation) (None, 10, 14, 192) 0 batch_normalization_258[0][0] __________________________________________________________________________________________________ conv2d_255 (Conv2D) (None, 10, 14, 192) 147456 mixed7[0][0] __________________________________________________________________________________________________ conv2d_259 (Conv2D) (None, 10, 14, 192) 258048 activation_257[0][0] __________________________________________________________________________________________________ batch_normalization_255 (BatchN (None, 10, 14, 192) 576 conv2d_255[0][0] __________________________________________________________________________________________________ batch_normalization_259 (BatchN (None, 10, 14, 192) 576 conv2d_259[0][0] __________________________________________________________________________________________________ activation_254 (Activation) (None, 10, 14, 192) 0 batch_normalization_255[0][0] __________________________________________________________________________________________________ activation_258 (Activation) (None, 10, 14, 192) 0 batch_normalization_259[0][0] __________________________________________________________________________________________________ conv2d_256 (Conv2D) (None, 4, 6, 320) 552960 activation_254[0][0] __________________________________________________________________________________________________ conv2d_260 (Conv2D) (None, 4, 6, 192) 331776 activation_258[0][0] __________________________________________________________________________________________________ batch_normalization_256 (BatchN (None, 4, 6, 320) 960 conv2d_256[0][0] __________________________________________________________________________________________________ batch_normalization_260 (BatchN (None, 4, 6, 192) 576 conv2d_260[0][0] __________________________________________________________________________________________________ activation_255 (Activation) (None, 4, 6, 320) 0 batch_normalization_256[0][0] __________________________________________________________________________________________________ activation_259 (Activation) (None, 4, 6, 192) 0 batch_normalization_260[0][0] __________________________________________________________________________________________________ max_pooling2d_12 (MaxPooling2D) (None, 4, 6, 768) 0 mixed7[0][0] __________________________________________________________________________________________________ mixed8 (Concatenate) (None, 4, 6, 1280) 0 activation_255[0][0] activation_259[0][0] max_pooling2d_12[0][0] __________________________________________________________________________________________________ conv2d_265 (Conv2D) (None, 4, 6, 448) 573440 mixed8[0][0] __________________________________________________________________________________________________ batch_normalization_265 (BatchN (None, 4, 6, 448) 1344 conv2d_265[0][0] __________________________________________________________________________________________________ activation_264 (Activation) (None, 4, 6, 448) 0 batch_normalization_265[0][0] __________________________________________________________________________________________________ conv2d_262 (Conv2D) (None, 4, 6, 384) 491520 mixed8[0][0] __________________________________________________________________________________________________ conv2d_266 (Conv2D) (None, 4, 6, 384) 1548288 activation_264[0][0] __________________________________________________________________________________________________ batch_normalization_262 (BatchN (None, 4, 6, 384) 1152 conv2d_262[0][0] __________________________________________________________________________________________________ batch_normalization_266 (BatchN (None, 4, 6, 384) 1152 conv2d_266[0][0] __________________________________________________________________________________________________ activation_261 (Activation) (None, 4, 6, 384) 0 batch_normalization_262[0][0] __________________________________________________________________________________________________ activation_265 (Activation) (None, 4, 6, 384) 0 batch_normalization_266[0][0] __________________________________________________________________________________________________ conv2d_263 (Conv2D) (None, 4, 6, 384) 442368 activation_261[0][0] __________________________________________________________________________________________________ conv2d_264 (Conv2D) (None, 4, 6, 384) 442368 activation_261[0][0] __________________________________________________________________________________________________ conv2d_267 (Conv2D) (None, 4, 6, 384) 442368 activation_265[0][0] __________________________________________________________________________________________________ conv2d_268 (Conv2D) (None, 4, 6, 384) 442368 activation_265[0][0] __________________________________________________________________________________________________ average_pooling2d_25 (AveragePo (None, 4, 6, 1280) 0 mixed8[0][0] __________________________________________________________________________________________________ conv2d_261 (Conv2D) (None, 4, 6, 320) 409600 mixed8[0][0] __________________________________________________________________________________________________ batch_normalization_263 (BatchN (None, 4, 6, 384) 1152 conv2d_263[0][0] __________________________________________________________________________________________________ batch_normalization_264 (BatchN (None, 4, 6, 384) 1152 conv2d_264[0][0] __________________________________________________________________________________________________ batch_normalization_267 (BatchN (None, 4, 6, 384) 1152 conv2d_267[0][0] __________________________________________________________________________________________________ batch_normalization_268 (BatchN (None, 4, 6, 384) 1152 conv2d_268[0][0] __________________________________________________________________________________________________ conv2d_269 (Conv2D) (None, 4, 6, 192) 245760 average_pooling2d_25[0][0] __________________________________________________________________________________________________ batch_normalization_261 (BatchN (None, 4, 6, 320) 960 conv2d_261[0][0] __________________________________________________________________________________________________ activation_262 (Activation) (None, 4, 6, 384) 0 batch_normalization_263[0][0] __________________________________________________________________________________________________ activation_263 (Activation) (None, 4, 6, 384) 0 batch_normalization_264[0][0] __________________________________________________________________________________________________ activation_266 (Activation) (None, 4, 6, 384) 0 batch_normalization_267[0][0] __________________________________________________________________________________________________ activation_267 (Activation) (None, 4, 6, 384) 0 batch_normalization_268[0][0] __________________________________________________________________________________________________ batch_normalization_269 (BatchN (None, 4, 6, 192) 576 conv2d_269[0][0] __________________________________________________________________________________________________ activation_260 (Activation) (None, 4, 6, 320) 0 batch_normalization_261[0][0] __________________________________________________________________________________________________ mixed9_0 (Concatenate) (None, 4, 6, 768) 0 activation_262[0][0] activation_263[0][0] __________________________________________________________________________________________________ concatenate_4 (Concatenate) (None, 4, 6, 768) 0 activation_266[0][0] activation_267[0][0] __________________________________________________________________________________________________ activation_268 (Activation) (None, 4, 6, 192) 0 batch_normalization_269[0][0] __________________________________________________________________________________________________ mixed9 (Concatenate) (None, 4, 6, 2048) 0 activation_260[0][0] mixed9_0[0][0] concatenate_4[0][0] activation_268[0][0] __________________________________________________________________________________________________ conv2d_274 (Conv2D) (None, 4, 6, 448) 917504 mixed9[0][0] __________________________________________________________________________________________________ batch_normalization_274 (BatchN (None, 4, 6, 448) 1344 conv2d_274[0][0] __________________________________________________________________________________________________ activation_273 (Activation) (None, 4, 6, 448) 0 batch_normalization_274[0][0] __________________________________________________________________________________________________ conv2d_271 (Conv2D) (None, 4, 6, 384) 786432 mixed9[0][0] __________________________________________________________________________________________________ conv2d_275 (Conv2D) (None, 4, 6, 384) 1548288 activation_273[0][0] __________________________________________________________________________________________________ batch_normalization_271 (BatchN (None, 4, 6, 384) 1152 conv2d_271[0][0] __________________________________________________________________________________________________ batch_normalization_275 (BatchN (None, 4, 6, 384) 1152 conv2d_275[0][0] __________________________________________________________________________________________________ activation_270 (Activation) (None, 4, 6, 384) 0 batch_normalization_271[0][0] __________________________________________________________________________________________________ activation_274 (Activation) (None, 4, 6, 384) 0 batch_normalization_275[0][0] __________________________________________________________________________________________________ conv2d_272 (Conv2D) (None, 4, 6, 384) 442368 activation_270[0][0] __________________________________________________________________________________________________ conv2d_273 (Conv2D) (None, 4, 6, 384) 442368 activation_270[0][0] __________________________________________________________________________________________________ conv2d_276 (Conv2D) (None, 4, 6, 384) 442368 activation_274[0][0] __________________________________________________________________________________________________ conv2d_277 (Conv2D) (None, 4, 6, 384) 442368 activation_274[0][0] __________________________________________________________________________________________________ average_pooling2d_26 (AveragePo (None, 4, 6, 2048) 0 mixed9[0][0] __________________________________________________________________________________________________ conv2d_270 (Conv2D) (None, 4, 6, 320) 655360 mixed9[0][0] __________________________________________________________________________________________________ batch_normalization_272 (BatchN (None, 4, 6, 384) 1152 conv2d_272[0][0] __________________________________________________________________________________________________ batch_normalization_273 (BatchN (None, 4, 6, 384) 1152 conv2d_273[0][0] __________________________________________________________________________________________________ batch_normalization_276 (BatchN (None, 4, 6, 384) 1152 conv2d_276[0][0] __________________________________________________________________________________________________ batch_normalization_277 (BatchN (None, 4, 6, 384) 1152 conv2d_277[0][0] __________________________________________________________________________________________________ conv2d_278 (Conv2D) (None, 4, 6, 192) 393216 average_pooling2d_26[0][0] __________________________________________________________________________________________________ batch_normalization_270 (BatchN (None, 4, 6, 320) 960 conv2d_270[0][0] __________________________________________________________________________________________________ activation_271 (Activation) (None, 4, 6, 384) 0 batch_normalization_272[0][0] __________________________________________________________________________________________________ activation_272 (Activation) (None, 4, 6, 384) 0 batch_normalization_273[0][0] __________________________________________________________________________________________________ activation_275 (Activation) (None, 4, 6, 384) 0 batch_normalization_276[0][0] __________________________________________________________________________________________________ activation_276 (Activation) (None, 4, 6, 384) 0 batch_normalization_277[0][0] __________________________________________________________________________________________________ batch_normalization_278 (BatchN (None, 4, 6, 192) 576 conv2d_278[0][0] __________________________________________________________________________________________________ activation_269 (Activation) (None, 4, 6, 320) 0 batch_normalization_270[0][0] __________________________________________________________________________________________________ mixed9_1 (Concatenate) (None, 4, 6, 768) 0 activation_271[0][0] activation_272[0][0] __________________________________________________________________________________________________ concatenate_5 (Concatenate) (None, 4, 6, 768) 0 activation_275[0][0] activation_276[0][0] __________________________________________________________________________________________________ activation_277 (Activation) (None, 4, 6, 192) 0 batch_normalization_278[0][0] __________________________________________________________________________________________________ mixed10 (Concatenate) (None, 4, 6, 2048) 0 activation_269[0][0] mixed9_1[0][0] concatenate_5[0][0] activation_277[0][0] __________________________________________________________________________________________________ global_max_pooling2d_2 (GlobalM (None, 2048) 0 mixed10[0][0] __________________________________________________________________________________________________ dense_3 (Dense) (None, 512) 1049088 global_max_pooling2d_2[0][0] __________________________________________________________________________________________________ dropout_2 (Dropout) (None, 512) 0 dense_3[0][0] __________________________________________________________________________________________________ dense_4 (Dense) (None, 7) 3591 dropout_2[0][0] ================================================================================================== Total params: 22,855,463 Trainable params: 22,821,031 Non-trainable params: 34,432 __________________________________________________________________________________________________ ###Markdown Define DenseNet 201 ###Code denseNet = DenseNet201(input_shape=input_shape, input_tensor=model_input, include_top=False, weights=None) for layer in denseNet.layers: layer.trainable = True denseNet_last_layer = denseNet.get_layer('relu') print('last layer output shape:', denseNet_last_layer.output_shape) denseNet_last_output = denseNet_last_layer.output # Flatten the output layer to 1 dimension x_denseNet = layers.GlobalMaxPooling2D()(denseNet_last_output) # Add a fully connected layer with 512 hidden units and ReLU activation x_denseNet = layers.Dense(512, activation='relu')(x_denseNet) # Add a dropout rate of 0.7 x_denseNet = layers.Dropout(0.5)(x_denseNet) # Add a final sigmoid layer for classification x_denseNet = layers.Dense(7, activation='softmax')(x_denseNet) # Configure and compile the model denseNet_model = Model(model_input, x_denseNet) optimizer = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=True) denseNet_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) denseNet_model.load_weights("DenseNetFull.h5") denseNet_model.summary() ###Output __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_1 (InputLayer) (None, 192, 256, 3) 0 __________________________________________________________________________________________________ zero_padding2d_1 (ZeroPadding2D (None, 198, 262, 3) 0 input_1[0][0] __________________________________________________________________________________________________ conv1/conv (Conv2D) (None, 96, 128, 64) 9408 zero_padding2d_1[0][0] __________________________________________________________________________________________________ conv1/bn (BatchNormalization) (None, 96, 128, 64) 256 conv1/conv[0][0] __________________________________________________________________________________________________ conv1/relu (Activation) (None, 96, 128, 64) 0 conv1/bn[0][0] __________________________________________________________________________________________________ zero_padding2d_2 (ZeroPadding2D (None, 98, 130, 64) 0 conv1/relu[0][0] __________________________________________________________________________________________________ pool1 (MaxPooling2D) (None, 48, 64, 64) 0 zero_padding2d_2[0][0] __________________________________________________________________________________________________ conv2_block1_0_bn (BatchNormali (None, 48, 64, 64) 256 pool1[0][0] __________________________________________________________________________________________________ conv2_block1_0_relu (Activation (None, 48, 64, 64) 0 conv2_block1_0_bn[0][0] __________________________________________________________________________________________________ conv2_block1_1_conv (Conv2D) (None, 48, 64, 128) 8192 conv2_block1_0_relu[0][0] __________________________________________________________________________________________________ conv2_block1_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block1_1_conv[0][0] __________________________________________________________________________________________________ conv2_block1_1_relu (Activation (None, 48, 64, 128) 0 conv2_block1_1_bn[0][0] __________________________________________________________________________________________________ conv2_block1_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block1_1_relu[0][0] __________________________________________________________________________________________________ conv2_block1_concat (Concatenat (None, 48, 64, 96) 0 pool1[0][0] conv2_block1_2_conv[0][0] __________________________________________________________________________________________________ conv2_block2_0_bn (BatchNormali (None, 48, 64, 96) 384 conv2_block1_concat[0][0] __________________________________________________________________________________________________ conv2_block2_0_relu (Activation (None, 48, 64, 96) 0 conv2_block2_0_bn[0][0] __________________________________________________________________________________________________ conv2_block2_1_conv (Conv2D) (None, 48, 64, 128) 12288 conv2_block2_0_relu[0][0] __________________________________________________________________________________________________ conv2_block2_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block2_1_conv[0][0] __________________________________________________________________________________________________ conv2_block2_1_relu (Activation (None, 48, 64, 128) 0 conv2_block2_1_bn[0][0] __________________________________________________________________________________________________ conv2_block2_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block2_1_relu[0][0] __________________________________________________________________________________________________ conv2_block2_concat (Concatenat (None, 48, 64, 128) 0 conv2_block1_concat[0][0] conv2_block2_2_conv[0][0] __________________________________________________________________________________________________ conv2_block3_0_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block2_concat[0][0] __________________________________________________________________________________________________ conv2_block3_0_relu (Activation (None, 48, 64, 128) 0 conv2_block3_0_bn[0][0] __________________________________________________________________________________________________ conv2_block3_1_conv (Conv2D) (None, 48, 64, 128) 16384 conv2_block3_0_relu[0][0] __________________________________________________________________________________________________ conv2_block3_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block3_1_conv[0][0] __________________________________________________________________________________________________ conv2_block3_1_relu (Activation (None, 48, 64, 128) 0 conv2_block3_1_bn[0][0] __________________________________________________________________________________________________ conv2_block3_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block3_1_relu[0][0] __________________________________________________________________________________________________ conv2_block3_concat (Concatenat (None, 48, 64, 160) 0 conv2_block2_concat[0][0] conv2_block3_2_conv[0][0] __________________________________________________________________________________________________ conv2_block4_0_bn (BatchNormali (None, 48, 64, 160) 640 conv2_block3_concat[0][0] __________________________________________________________________________________________________ conv2_block4_0_relu (Activation (None, 48, 64, 160) 0 conv2_block4_0_bn[0][0] __________________________________________________________________________________________________ conv2_block4_1_conv (Conv2D) (None, 48, 64, 128) 20480 conv2_block4_0_relu[0][0] __________________________________________________________________________________________________ conv2_block4_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block4_1_conv[0][0] __________________________________________________________________________________________________ conv2_block4_1_relu (Activation (None, 48, 64, 128) 0 conv2_block4_1_bn[0][0] __________________________________________________________________________________________________ conv2_block4_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block4_1_relu[0][0] __________________________________________________________________________________________________ conv2_block4_concat (Concatenat (None, 48, 64, 192) 0 conv2_block3_concat[0][0] conv2_block4_2_conv[0][0] __________________________________________________________________________________________________ conv2_block5_0_bn (BatchNormali (None, 48, 64, 192) 768 conv2_block4_concat[0][0] __________________________________________________________________________________________________ conv2_block5_0_relu (Activation (None, 48, 64, 192) 0 conv2_block5_0_bn[0][0] __________________________________________________________________________________________________ conv2_block5_1_conv (Conv2D) (None, 48, 64, 128) 24576 conv2_block5_0_relu[0][0] __________________________________________________________________________________________________ conv2_block5_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block5_1_conv[0][0] __________________________________________________________________________________________________ conv2_block5_1_relu (Activation (None, 48, 64, 128) 0 conv2_block5_1_bn[0][0] __________________________________________________________________________________________________ conv2_block5_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block5_1_relu[0][0] __________________________________________________________________________________________________ conv2_block5_concat (Concatenat (None, 48, 64, 224) 0 conv2_block4_concat[0][0] conv2_block5_2_conv[0][0] __________________________________________________________________________________________________ conv2_block6_0_bn (BatchNormali (None, 48, 64, 224) 896 conv2_block5_concat[0][0] __________________________________________________________________________________________________ conv2_block6_0_relu (Activation (None, 48, 64, 224) 0 conv2_block6_0_bn[0][0] __________________________________________________________________________________________________ conv2_block6_1_conv (Conv2D) (None, 48, 64, 128) 28672 conv2_block6_0_relu[0][0] __________________________________________________________________________________________________ conv2_block6_1_bn (BatchNormali (None, 48, 64, 128) 512 conv2_block6_1_conv[0][0] __________________________________________________________________________________________________ conv2_block6_1_relu (Activation (None, 48, 64, 128) 0 conv2_block6_1_bn[0][0] __________________________________________________________________________________________________ conv2_block6_2_conv (Conv2D) (None, 48, 64, 32) 36864 conv2_block6_1_relu[0][0] __________________________________________________________________________________________________ conv2_block6_concat (Concatenat (None, 48, 64, 256) 0 conv2_block5_concat[0][0] conv2_block6_2_conv[0][0] __________________________________________________________________________________________________ pool2_bn (BatchNormalization) (None, 48, 64, 256) 1024 conv2_block6_concat[0][0] __________________________________________________________________________________________________ pool2_relu (Activation) (None, 48, 64, 256) 0 pool2_bn[0][0] __________________________________________________________________________________________________ pool2_conv (Conv2D) (None, 48, 64, 128) 32768 pool2_relu[0][0] __________________________________________________________________________________________________ pool2_pool (AveragePooling2D) (None, 24, 32, 128) 0 pool2_conv[0][0] __________________________________________________________________________________________________ conv3_block1_0_bn (BatchNormali (None, 24, 32, 128) 512 pool2_pool[0][0] __________________________________________________________________________________________________ conv3_block1_0_relu (Activation (None, 24, 32, 128) 0 conv3_block1_0_bn[0][0] __________________________________________________________________________________________________ conv3_block1_1_conv (Conv2D) (None, 24, 32, 128) 16384 conv3_block1_0_relu[0][0] __________________________________________________________________________________________________ conv3_block1_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block1_1_conv[0][0] __________________________________________________________________________________________________ conv3_block1_1_relu (Activation (None, 24, 32, 128) 0 conv3_block1_1_bn[0][0] __________________________________________________________________________________________________ conv3_block1_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block1_1_relu[0][0] __________________________________________________________________________________________________ conv3_block1_concat (Concatenat (None, 24, 32, 160) 0 pool2_pool[0][0] conv3_block1_2_conv[0][0] __________________________________________________________________________________________________ conv3_block2_0_bn (BatchNormali (None, 24, 32, 160) 640 conv3_block1_concat[0][0] __________________________________________________________________________________________________ conv3_block2_0_relu (Activation (None, 24, 32, 160) 0 conv3_block2_0_bn[0][0] __________________________________________________________________________________________________ conv3_block2_1_conv (Conv2D) (None, 24, 32, 128) 20480 conv3_block2_0_relu[0][0] __________________________________________________________________________________________________ conv3_block2_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block2_1_conv[0][0] __________________________________________________________________________________________________ conv3_block2_1_relu (Activation (None, 24, 32, 128) 0 conv3_block2_1_bn[0][0] __________________________________________________________________________________________________ conv3_block2_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block2_1_relu[0][0] __________________________________________________________________________________________________ conv3_block2_concat (Concatenat (None, 24, 32, 192) 0 conv3_block1_concat[0][0] conv3_block2_2_conv[0][0] __________________________________________________________________________________________________ conv3_block3_0_bn (BatchNormali (None, 24, 32, 192) 768 conv3_block2_concat[0][0] __________________________________________________________________________________________________ conv3_block3_0_relu (Activation (None, 24, 32, 192) 0 conv3_block3_0_bn[0][0] __________________________________________________________________________________________________ conv3_block3_1_conv (Conv2D) (None, 24, 32, 128) 24576 conv3_block3_0_relu[0][0] __________________________________________________________________________________________________ conv3_block3_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block3_1_conv[0][0] __________________________________________________________________________________________________ conv3_block3_1_relu (Activation (None, 24, 32, 128) 0 conv3_block3_1_bn[0][0] __________________________________________________________________________________________________ conv3_block3_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block3_1_relu[0][0] __________________________________________________________________________________________________ conv3_block3_concat (Concatenat (None, 24, 32, 224) 0 conv3_block2_concat[0][0] conv3_block3_2_conv[0][0] __________________________________________________________________________________________________ conv3_block4_0_bn (BatchNormali (None, 24, 32, 224) 896 conv3_block3_concat[0][0] __________________________________________________________________________________________________ conv3_block4_0_relu (Activation (None, 24, 32, 224) 0 conv3_block4_0_bn[0][0] __________________________________________________________________________________________________ conv3_block4_1_conv (Conv2D) (None, 24, 32, 128) 28672 conv3_block4_0_relu[0][0] __________________________________________________________________________________________________ conv3_block4_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block4_1_conv[0][0] __________________________________________________________________________________________________ conv3_block4_1_relu (Activation (None, 24, 32, 128) 0 conv3_block4_1_bn[0][0] __________________________________________________________________________________________________ conv3_block4_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block4_1_relu[0][0] __________________________________________________________________________________________________ conv3_block4_concat (Concatenat (None, 24, 32, 256) 0 conv3_block3_concat[0][0] conv3_block4_2_conv[0][0] __________________________________________________________________________________________________ conv3_block5_0_bn (BatchNormali (None, 24, 32, 256) 1024 conv3_block4_concat[0][0] __________________________________________________________________________________________________ conv3_block5_0_relu (Activation (None, 24, 32, 256) 0 conv3_block5_0_bn[0][0] __________________________________________________________________________________________________ conv3_block5_1_conv (Conv2D) (None, 24, 32, 128) 32768 conv3_block5_0_relu[0][0] __________________________________________________________________________________________________ conv3_block5_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block5_1_conv[0][0] __________________________________________________________________________________________________ conv3_block5_1_relu (Activation (None, 24, 32, 128) 0 conv3_block5_1_bn[0][0] __________________________________________________________________________________________________ conv3_block5_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block5_1_relu[0][0] __________________________________________________________________________________________________ conv3_block5_concat (Concatenat (None, 24, 32, 288) 0 conv3_block4_concat[0][0] conv3_block5_2_conv[0][0] __________________________________________________________________________________________________ conv3_block6_0_bn (BatchNormali (None, 24, 32, 288) 1152 conv3_block5_concat[0][0] __________________________________________________________________________________________________ conv3_block6_0_relu (Activation (None, 24, 32, 288) 0 conv3_block6_0_bn[0][0] __________________________________________________________________________________________________ conv3_block6_1_conv (Conv2D) (None, 24, 32, 128) 36864 conv3_block6_0_relu[0][0] __________________________________________________________________________________________________ conv3_block6_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block6_1_conv[0][0] __________________________________________________________________________________________________ conv3_block6_1_relu (Activation (None, 24, 32, 128) 0 conv3_block6_1_bn[0][0] __________________________________________________________________________________________________ conv3_block6_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block6_1_relu[0][0] __________________________________________________________________________________________________ conv3_block6_concat (Concatenat (None, 24, 32, 320) 0 conv3_block5_concat[0][0] conv3_block6_2_conv[0][0] __________________________________________________________________________________________________ conv3_block7_0_bn (BatchNormali (None, 24, 32, 320) 1280 conv3_block6_concat[0][0] __________________________________________________________________________________________________ conv3_block7_0_relu (Activation (None, 24, 32, 320) 0 conv3_block7_0_bn[0][0] __________________________________________________________________________________________________ conv3_block7_1_conv (Conv2D) (None, 24, 32, 128) 40960 conv3_block7_0_relu[0][0] __________________________________________________________________________________________________ conv3_block7_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block7_1_conv[0][0] __________________________________________________________________________________________________ conv3_block7_1_relu (Activation (None, 24, 32, 128) 0 conv3_block7_1_bn[0][0] __________________________________________________________________________________________________ conv3_block7_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block7_1_relu[0][0] __________________________________________________________________________________________________ conv3_block7_concat (Concatenat (None, 24, 32, 352) 0 conv3_block6_concat[0][0] conv3_block7_2_conv[0][0] __________________________________________________________________________________________________ conv3_block8_0_bn (BatchNormali (None, 24, 32, 352) 1408 conv3_block7_concat[0][0] __________________________________________________________________________________________________ conv3_block8_0_relu (Activation (None, 24, 32, 352) 0 conv3_block8_0_bn[0][0] __________________________________________________________________________________________________ conv3_block8_1_conv (Conv2D) (None, 24, 32, 128) 45056 conv3_block8_0_relu[0][0] __________________________________________________________________________________________________ conv3_block8_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block8_1_conv[0][0] __________________________________________________________________________________________________ conv3_block8_1_relu (Activation (None, 24, 32, 128) 0 conv3_block8_1_bn[0][0] __________________________________________________________________________________________________ conv3_block8_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block8_1_relu[0][0] __________________________________________________________________________________________________ conv3_block8_concat (Concatenat (None, 24, 32, 384) 0 conv3_block7_concat[0][0] conv3_block8_2_conv[0][0] __________________________________________________________________________________________________ conv3_block9_0_bn (BatchNormali (None, 24, 32, 384) 1536 conv3_block8_concat[0][0] __________________________________________________________________________________________________ conv3_block9_0_relu (Activation (None, 24, 32, 384) 0 conv3_block9_0_bn[0][0] __________________________________________________________________________________________________ conv3_block9_1_conv (Conv2D) (None, 24, 32, 128) 49152 conv3_block9_0_relu[0][0] __________________________________________________________________________________________________ conv3_block9_1_bn (BatchNormali (None, 24, 32, 128) 512 conv3_block9_1_conv[0][0] __________________________________________________________________________________________________ conv3_block9_1_relu (Activation (None, 24, 32, 128) 0 conv3_block9_1_bn[0][0] __________________________________________________________________________________________________ conv3_block9_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block9_1_relu[0][0] __________________________________________________________________________________________________ conv3_block9_concat (Concatenat (None, 24, 32, 416) 0 conv3_block8_concat[0][0] conv3_block9_2_conv[0][0] __________________________________________________________________________________________________ conv3_block10_0_bn (BatchNormal (None, 24, 32, 416) 1664 conv3_block9_concat[0][0] __________________________________________________________________________________________________ conv3_block10_0_relu (Activatio (None, 24, 32, 416) 0 conv3_block10_0_bn[0][0] __________________________________________________________________________________________________ conv3_block10_1_conv (Conv2D) (None, 24, 32, 128) 53248 conv3_block10_0_relu[0][0] __________________________________________________________________________________________________ conv3_block10_1_bn (BatchNormal (None, 24, 32, 128) 512 conv3_block10_1_conv[0][0] __________________________________________________________________________________________________ conv3_block10_1_relu (Activatio (None, 24, 32, 128) 0 conv3_block10_1_bn[0][0] __________________________________________________________________________________________________ conv3_block10_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block10_1_relu[0][0] __________________________________________________________________________________________________ conv3_block10_concat (Concatena (None, 24, 32, 448) 0 conv3_block9_concat[0][0] conv3_block10_2_conv[0][0] __________________________________________________________________________________________________ conv3_block11_0_bn (BatchNormal (None, 24, 32, 448) 1792 conv3_block10_concat[0][0] __________________________________________________________________________________________________ conv3_block11_0_relu (Activatio (None, 24, 32, 448) 0 conv3_block11_0_bn[0][0] __________________________________________________________________________________________________ conv3_block11_1_conv (Conv2D) (None, 24, 32, 128) 57344 conv3_block11_0_relu[0][0] __________________________________________________________________________________________________ conv3_block11_1_bn (BatchNormal (None, 24, 32, 128) 512 conv3_block11_1_conv[0][0] __________________________________________________________________________________________________ conv3_block11_1_relu (Activatio (None, 24, 32, 128) 0 conv3_block11_1_bn[0][0] __________________________________________________________________________________________________ conv3_block11_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block11_1_relu[0][0] __________________________________________________________________________________________________ conv3_block11_concat (Concatena (None, 24, 32, 480) 0 conv3_block10_concat[0][0] conv3_block11_2_conv[0][0] __________________________________________________________________________________________________ conv3_block12_0_bn (BatchNormal (None, 24, 32, 480) 1920 conv3_block11_concat[0][0] __________________________________________________________________________________________________ conv3_block12_0_relu (Activatio (None, 24, 32, 480) 0 conv3_block12_0_bn[0][0] __________________________________________________________________________________________________ conv3_block12_1_conv (Conv2D) (None, 24, 32, 128) 61440 conv3_block12_0_relu[0][0] __________________________________________________________________________________________________ conv3_block12_1_bn (BatchNormal (None, 24, 32, 128) 512 conv3_block12_1_conv[0][0] __________________________________________________________________________________________________ conv3_block12_1_relu (Activatio (None, 24, 32, 128) 0 conv3_block12_1_bn[0][0] __________________________________________________________________________________________________ conv3_block12_2_conv (Conv2D) (None, 24, 32, 32) 36864 conv3_block12_1_relu[0][0] __________________________________________________________________________________________________ conv3_block12_concat (Concatena (None, 24, 32, 512) 0 conv3_block11_concat[0][0] conv3_block12_2_conv[0][0] __________________________________________________________________________________________________ pool3_bn (BatchNormalization) (None, 24, 32, 512) 2048 conv3_block12_concat[0][0] __________________________________________________________________________________________________ pool3_relu (Activation) (None, 24, 32, 512) 0 pool3_bn[0][0] __________________________________________________________________________________________________ pool3_conv (Conv2D) (None, 24, 32, 256) 131072 pool3_relu[0][0] __________________________________________________________________________________________________ pool3_pool (AveragePooling2D) (None, 12, 16, 256) 0 pool3_conv[0][0] __________________________________________________________________________________________________ conv4_block1_0_bn (BatchNormali (None, 12, 16, 256) 1024 pool3_pool[0][0] __________________________________________________________________________________________________ conv4_block1_0_relu (Activation (None, 12, 16, 256) 0 conv4_block1_0_bn[0][0] __________________________________________________________________________________________________ conv4_block1_1_conv (Conv2D) (None, 12, 16, 128) 32768 conv4_block1_0_relu[0][0] __________________________________________________________________________________________________ conv4_block1_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block1_1_conv[0][0] __________________________________________________________________________________________________ conv4_block1_1_relu (Activation (None, 12, 16, 128) 0 conv4_block1_1_bn[0][0] __________________________________________________________________________________________________ conv4_block1_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block1_1_relu[0][0] __________________________________________________________________________________________________ conv4_block1_concat (Concatenat (None, 12, 16, 288) 0 pool3_pool[0][0] conv4_block1_2_conv[0][0] __________________________________________________________________________________________________ conv4_block2_0_bn (BatchNormali (None, 12, 16, 288) 1152 conv4_block1_concat[0][0] __________________________________________________________________________________________________ conv4_block2_0_relu (Activation (None, 12, 16, 288) 0 conv4_block2_0_bn[0][0] __________________________________________________________________________________________________ conv4_block2_1_conv (Conv2D) (None, 12, 16, 128) 36864 conv4_block2_0_relu[0][0] __________________________________________________________________________________________________ conv4_block2_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block2_1_conv[0][0] __________________________________________________________________________________________________ conv4_block2_1_relu (Activation (None, 12, 16, 128) 0 conv4_block2_1_bn[0][0] __________________________________________________________________________________________________ conv4_block2_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block2_1_relu[0][0] __________________________________________________________________________________________________ conv4_block2_concat (Concatenat (None, 12, 16, 320) 0 conv4_block1_concat[0][0] conv4_block2_2_conv[0][0] __________________________________________________________________________________________________ conv4_block3_0_bn (BatchNormali (None, 12, 16, 320) 1280 conv4_block2_concat[0][0] __________________________________________________________________________________________________ conv4_block3_0_relu (Activation (None, 12, 16, 320) 0 conv4_block3_0_bn[0][0] __________________________________________________________________________________________________ conv4_block3_1_conv (Conv2D) (None, 12, 16, 128) 40960 conv4_block3_0_relu[0][0] __________________________________________________________________________________________________ conv4_block3_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block3_1_conv[0][0] __________________________________________________________________________________________________ conv4_block3_1_relu (Activation (None, 12, 16, 128) 0 conv4_block3_1_bn[0][0] __________________________________________________________________________________________________ conv4_block3_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block3_1_relu[0][0] __________________________________________________________________________________________________ conv4_block3_concat (Concatenat (None, 12, 16, 352) 0 conv4_block2_concat[0][0] conv4_block3_2_conv[0][0] __________________________________________________________________________________________________ conv4_block4_0_bn (BatchNormali (None, 12, 16, 352) 1408 conv4_block3_concat[0][0] __________________________________________________________________________________________________ conv4_block4_0_relu (Activation (None, 12, 16, 352) 0 conv4_block4_0_bn[0][0] __________________________________________________________________________________________________ conv4_block4_1_conv (Conv2D) (None, 12, 16, 128) 45056 conv4_block4_0_relu[0][0] __________________________________________________________________________________________________ conv4_block4_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block4_1_conv[0][0] __________________________________________________________________________________________________ conv4_block4_1_relu (Activation (None, 12, 16, 128) 0 conv4_block4_1_bn[0][0] __________________________________________________________________________________________________ conv4_block4_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block4_1_relu[0][0] __________________________________________________________________________________________________ conv4_block4_concat (Concatenat (None, 12, 16, 384) 0 conv4_block3_concat[0][0] conv4_block4_2_conv[0][0] __________________________________________________________________________________________________ conv4_block5_0_bn (BatchNormali (None, 12, 16, 384) 1536 conv4_block4_concat[0][0] __________________________________________________________________________________________________ conv4_block5_0_relu (Activation (None, 12, 16, 384) 0 conv4_block5_0_bn[0][0] __________________________________________________________________________________________________ conv4_block5_1_conv (Conv2D) (None, 12, 16, 128) 49152 conv4_block5_0_relu[0][0] __________________________________________________________________________________________________ conv4_block5_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block5_1_conv[0][0] __________________________________________________________________________________________________ conv4_block5_1_relu (Activation (None, 12, 16, 128) 0 conv4_block5_1_bn[0][0] __________________________________________________________________________________________________ conv4_block5_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block5_1_relu[0][0] __________________________________________________________________________________________________ conv4_block5_concat (Concatenat (None, 12, 16, 416) 0 conv4_block4_concat[0][0] conv4_block5_2_conv[0][0] __________________________________________________________________________________________________ conv4_block6_0_bn (BatchNormali (None, 12, 16, 416) 1664 conv4_block5_concat[0][0] __________________________________________________________________________________________________ conv4_block6_0_relu (Activation (None, 12, 16, 416) 0 conv4_block6_0_bn[0][0] __________________________________________________________________________________________________ conv4_block6_1_conv (Conv2D) (None, 12, 16, 128) 53248 conv4_block6_0_relu[0][0] __________________________________________________________________________________________________ conv4_block6_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block6_1_conv[0][0] __________________________________________________________________________________________________ conv4_block6_1_relu (Activation (None, 12, 16, 128) 0 conv4_block6_1_bn[0][0] __________________________________________________________________________________________________ conv4_block6_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block6_1_relu[0][0] __________________________________________________________________________________________________ conv4_block6_concat (Concatenat (None, 12, 16, 448) 0 conv4_block5_concat[0][0] conv4_block6_2_conv[0][0] __________________________________________________________________________________________________ conv4_block7_0_bn (BatchNormali (None, 12, 16, 448) 1792 conv4_block6_concat[0][0] __________________________________________________________________________________________________ conv4_block7_0_relu (Activation (None, 12, 16, 448) 0 conv4_block7_0_bn[0][0] __________________________________________________________________________________________________ conv4_block7_1_conv (Conv2D) (None, 12, 16, 128) 57344 conv4_block7_0_relu[0][0] __________________________________________________________________________________________________ conv4_block7_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block7_1_conv[0][0] __________________________________________________________________________________________________ conv4_block7_1_relu (Activation (None, 12, 16, 128) 0 conv4_block7_1_bn[0][0] __________________________________________________________________________________________________ conv4_block7_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block7_1_relu[0][0] __________________________________________________________________________________________________ conv4_block7_concat (Concatenat (None, 12, 16, 480) 0 conv4_block6_concat[0][0] conv4_block7_2_conv[0][0] __________________________________________________________________________________________________ conv4_block8_0_bn (BatchNormali (None, 12, 16, 480) 1920 conv4_block7_concat[0][0] __________________________________________________________________________________________________ conv4_block8_0_relu (Activation (None, 12, 16, 480) 0 conv4_block8_0_bn[0][0] __________________________________________________________________________________________________ conv4_block8_1_conv (Conv2D) (None, 12, 16, 128) 61440 conv4_block8_0_relu[0][0] __________________________________________________________________________________________________ conv4_block8_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block8_1_conv[0][0] __________________________________________________________________________________________________ conv4_block8_1_relu (Activation (None, 12, 16, 128) 0 conv4_block8_1_bn[0][0] __________________________________________________________________________________________________ conv4_block8_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block8_1_relu[0][0] __________________________________________________________________________________________________ conv4_block8_concat (Concatenat (None, 12, 16, 512) 0 conv4_block7_concat[0][0] conv4_block8_2_conv[0][0] __________________________________________________________________________________________________ conv4_block9_0_bn (BatchNormali (None, 12, 16, 512) 2048 conv4_block8_concat[0][0] __________________________________________________________________________________________________ conv4_block9_0_relu (Activation (None, 12, 16, 512) 0 conv4_block9_0_bn[0][0] __________________________________________________________________________________________________ conv4_block9_1_conv (Conv2D) (None, 12, 16, 128) 65536 conv4_block9_0_relu[0][0] __________________________________________________________________________________________________ conv4_block9_1_bn (BatchNormali (None, 12, 16, 128) 512 conv4_block9_1_conv[0][0] __________________________________________________________________________________________________ conv4_block9_1_relu (Activation (None, 12, 16, 128) 0 conv4_block9_1_bn[0][0] __________________________________________________________________________________________________ conv4_block9_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block9_1_relu[0][0] __________________________________________________________________________________________________ conv4_block9_concat (Concatenat (None, 12, 16, 544) 0 conv4_block8_concat[0][0] conv4_block9_2_conv[0][0] __________________________________________________________________________________________________ conv4_block10_0_bn (BatchNormal (None, 12, 16, 544) 2176 conv4_block9_concat[0][0] __________________________________________________________________________________________________ conv4_block10_0_relu (Activatio (None, 12, 16, 544) 0 conv4_block10_0_bn[0][0] __________________________________________________________________________________________________ conv4_block10_1_conv (Conv2D) (None, 12, 16, 128) 69632 conv4_block10_0_relu[0][0] __________________________________________________________________________________________________ conv4_block10_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block10_1_conv[0][0] __________________________________________________________________________________________________ conv4_block10_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block10_1_bn[0][0] __________________________________________________________________________________________________ conv4_block10_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block10_1_relu[0][0] __________________________________________________________________________________________________ conv4_block10_concat (Concatena (None, 12, 16, 576) 0 conv4_block9_concat[0][0] conv4_block10_2_conv[0][0] __________________________________________________________________________________________________ conv4_block11_0_bn (BatchNormal (None, 12, 16, 576) 2304 conv4_block10_concat[0][0] __________________________________________________________________________________________________ conv4_block11_0_relu (Activatio (None, 12, 16, 576) 0 conv4_block11_0_bn[0][0] __________________________________________________________________________________________________ conv4_block11_1_conv (Conv2D) (None, 12, 16, 128) 73728 conv4_block11_0_relu[0][0] __________________________________________________________________________________________________ conv4_block11_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block11_1_conv[0][0] __________________________________________________________________________________________________ conv4_block11_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block11_1_bn[0][0] __________________________________________________________________________________________________ conv4_block11_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block11_1_relu[0][0] __________________________________________________________________________________________________ conv4_block11_concat (Concatena (None, 12, 16, 608) 0 conv4_block10_concat[0][0] conv4_block11_2_conv[0][0] __________________________________________________________________________________________________ conv4_block12_0_bn (BatchNormal (None, 12, 16, 608) 2432 conv4_block11_concat[0][0] __________________________________________________________________________________________________ conv4_block12_0_relu (Activatio (None, 12, 16, 608) 0 conv4_block12_0_bn[0][0] __________________________________________________________________________________________________ conv4_block12_1_conv (Conv2D) (None, 12, 16, 128) 77824 conv4_block12_0_relu[0][0] __________________________________________________________________________________________________ conv4_block12_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block12_1_conv[0][0] __________________________________________________________________________________________________ conv4_block12_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block12_1_bn[0][0] __________________________________________________________________________________________________ conv4_block12_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block12_1_relu[0][0] __________________________________________________________________________________________________ conv4_block12_concat (Concatena (None, 12, 16, 640) 0 conv4_block11_concat[0][0] conv4_block12_2_conv[0][0] __________________________________________________________________________________________________ conv4_block13_0_bn (BatchNormal (None, 12, 16, 640) 2560 conv4_block12_concat[0][0] __________________________________________________________________________________________________ conv4_block13_0_relu (Activatio (None, 12, 16, 640) 0 conv4_block13_0_bn[0][0] __________________________________________________________________________________________________ conv4_block13_1_conv (Conv2D) (None, 12, 16, 128) 81920 conv4_block13_0_relu[0][0] __________________________________________________________________________________________________ conv4_block13_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block13_1_conv[0][0] __________________________________________________________________________________________________ conv4_block13_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block13_1_bn[0][0] __________________________________________________________________________________________________ conv4_block13_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block13_1_relu[0][0] __________________________________________________________________________________________________ conv4_block13_concat (Concatena (None, 12, 16, 672) 0 conv4_block12_concat[0][0] conv4_block13_2_conv[0][0] __________________________________________________________________________________________________ conv4_block14_0_bn (BatchNormal (None, 12, 16, 672) 2688 conv4_block13_concat[0][0] __________________________________________________________________________________________________ conv4_block14_0_relu (Activatio (None, 12, 16, 672) 0 conv4_block14_0_bn[0][0] __________________________________________________________________________________________________ conv4_block14_1_conv (Conv2D) (None, 12, 16, 128) 86016 conv4_block14_0_relu[0][0] __________________________________________________________________________________________________ conv4_block14_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block14_1_conv[0][0] __________________________________________________________________________________________________ conv4_block14_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block14_1_bn[0][0] __________________________________________________________________________________________________ conv4_block14_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block14_1_relu[0][0] __________________________________________________________________________________________________ conv4_block14_concat (Concatena (None, 12, 16, 704) 0 conv4_block13_concat[0][0] conv4_block14_2_conv[0][0] __________________________________________________________________________________________________ conv4_block15_0_bn (BatchNormal (None, 12, 16, 704) 2816 conv4_block14_concat[0][0] __________________________________________________________________________________________________ conv4_block15_0_relu (Activatio (None, 12, 16, 704) 0 conv4_block15_0_bn[0][0] __________________________________________________________________________________________________ conv4_block15_1_conv (Conv2D) (None, 12, 16, 128) 90112 conv4_block15_0_relu[0][0] __________________________________________________________________________________________________ conv4_block15_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block15_1_conv[0][0] __________________________________________________________________________________________________ conv4_block15_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block15_1_bn[0][0] __________________________________________________________________________________________________ conv4_block15_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block15_1_relu[0][0] __________________________________________________________________________________________________ conv4_block15_concat (Concatena (None, 12, 16, 736) 0 conv4_block14_concat[0][0] conv4_block15_2_conv[0][0] __________________________________________________________________________________________________ conv4_block16_0_bn (BatchNormal (None, 12, 16, 736) 2944 conv4_block15_concat[0][0] __________________________________________________________________________________________________ conv4_block16_0_relu (Activatio (None, 12, 16, 736) 0 conv4_block16_0_bn[0][0] __________________________________________________________________________________________________ conv4_block16_1_conv (Conv2D) (None, 12, 16, 128) 94208 conv4_block16_0_relu[0][0] __________________________________________________________________________________________________ conv4_block16_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block16_1_conv[0][0] __________________________________________________________________________________________________ conv4_block16_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block16_1_bn[0][0] __________________________________________________________________________________________________ conv4_block16_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block16_1_relu[0][0] __________________________________________________________________________________________________ conv4_block16_concat (Concatena (None, 12, 16, 768) 0 conv4_block15_concat[0][0] conv4_block16_2_conv[0][0] __________________________________________________________________________________________________ conv4_block17_0_bn (BatchNormal (None, 12, 16, 768) 3072 conv4_block16_concat[0][0] __________________________________________________________________________________________________ conv4_block17_0_relu (Activatio (None, 12, 16, 768) 0 conv4_block17_0_bn[0][0] __________________________________________________________________________________________________ conv4_block17_1_conv (Conv2D) (None, 12, 16, 128) 98304 conv4_block17_0_relu[0][0] __________________________________________________________________________________________________ conv4_block17_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block17_1_conv[0][0] __________________________________________________________________________________________________ conv4_block17_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block17_1_bn[0][0] __________________________________________________________________________________________________ conv4_block17_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block17_1_relu[0][0] __________________________________________________________________________________________________ conv4_block17_concat (Concatena (None, 12, 16, 800) 0 conv4_block16_concat[0][0] conv4_block17_2_conv[0][0] __________________________________________________________________________________________________ conv4_block18_0_bn (BatchNormal (None, 12, 16, 800) 3200 conv4_block17_concat[0][0] __________________________________________________________________________________________________ conv4_block18_0_relu (Activatio (None, 12, 16, 800) 0 conv4_block18_0_bn[0][0] __________________________________________________________________________________________________ conv4_block18_1_conv (Conv2D) (None, 12, 16, 128) 102400 conv4_block18_0_relu[0][0] __________________________________________________________________________________________________ conv4_block18_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block18_1_conv[0][0] __________________________________________________________________________________________________ conv4_block18_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block18_1_bn[0][0] __________________________________________________________________________________________________ conv4_block18_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block18_1_relu[0][0] __________________________________________________________________________________________________ conv4_block18_concat (Concatena (None, 12, 16, 832) 0 conv4_block17_concat[0][0] conv4_block18_2_conv[0][0] __________________________________________________________________________________________________ conv4_block19_0_bn (BatchNormal (None, 12, 16, 832) 3328 conv4_block18_concat[0][0] __________________________________________________________________________________________________ conv4_block19_0_relu (Activatio (None, 12, 16, 832) 0 conv4_block19_0_bn[0][0] __________________________________________________________________________________________________ conv4_block19_1_conv (Conv2D) (None, 12, 16, 128) 106496 conv4_block19_0_relu[0][0] __________________________________________________________________________________________________ conv4_block19_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block19_1_conv[0][0] __________________________________________________________________________________________________ conv4_block19_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block19_1_bn[0][0] __________________________________________________________________________________________________ conv4_block19_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block19_1_relu[0][0] __________________________________________________________________________________________________ conv4_block19_concat (Concatena (None, 12, 16, 864) 0 conv4_block18_concat[0][0] conv4_block19_2_conv[0][0] __________________________________________________________________________________________________ conv4_block20_0_bn (BatchNormal (None, 12, 16, 864) 3456 conv4_block19_concat[0][0] __________________________________________________________________________________________________ conv4_block20_0_relu (Activatio (None, 12, 16, 864) 0 conv4_block20_0_bn[0][0] __________________________________________________________________________________________________ conv4_block20_1_conv (Conv2D) (None, 12, 16, 128) 110592 conv4_block20_0_relu[0][0] __________________________________________________________________________________________________ conv4_block20_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block20_1_conv[0][0] __________________________________________________________________________________________________ conv4_block20_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block20_1_bn[0][0] __________________________________________________________________________________________________ conv4_block20_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block20_1_relu[0][0] __________________________________________________________________________________________________ conv4_block20_concat (Concatena (None, 12, 16, 896) 0 conv4_block19_concat[0][0] conv4_block20_2_conv[0][0] __________________________________________________________________________________________________ conv4_block21_0_bn (BatchNormal (None, 12, 16, 896) 3584 conv4_block20_concat[0][0] __________________________________________________________________________________________________ conv4_block21_0_relu (Activatio (None, 12, 16, 896) 0 conv4_block21_0_bn[0][0] __________________________________________________________________________________________________ conv4_block21_1_conv (Conv2D) (None, 12, 16, 128) 114688 conv4_block21_0_relu[0][0] __________________________________________________________________________________________________ conv4_block21_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block21_1_conv[0][0] __________________________________________________________________________________________________ conv4_block21_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block21_1_bn[0][0] __________________________________________________________________________________________________ conv4_block21_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block21_1_relu[0][0] __________________________________________________________________________________________________ conv4_block21_concat (Concatena (None, 12, 16, 928) 0 conv4_block20_concat[0][0] conv4_block21_2_conv[0][0] __________________________________________________________________________________________________ conv4_block22_0_bn (BatchNormal (None, 12, 16, 928) 3712 conv4_block21_concat[0][0] __________________________________________________________________________________________________ conv4_block22_0_relu (Activatio (None, 12, 16, 928) 0 conv4_block22_0_bn[0][0] __________________________________________________________________________________________________ conv4_block22_1_conv (Conv2D) (None, 12, 16, 128) 118784 conv4_block22_0_relu[0][0] __________________________________________________________________________________________________ conv4_block22_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block22_1_conv[0][0] __________________________________________________________________________________________________ conv4_block22_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block22_1_bn[0][0] __________________________________________________________________________________________________ conv4_block22_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block22_1_relu[0][0] __________________________________________________________________________________________________ conv4_block22_concat (Concatena (None, 12, 16, 960) 0 conv4_block21_concat[0][0] conv4_block22_2_conv[0][0] __________________________________________________________________________________________________ conv4_block23_0_bn (BatchNormal (None, 12, 16, 960) 3840 conv4_block22_concat[0][0] __________________________________________________________________________________________________ conv4_block23_0_relu (Activatio (None, 12, 16, 960) 0 conv4_block23_0_bn[0][0] __________________________________________________________________________________________________ conv4_block23_1_conv (Conv2D) (None, 12, 16, 128) 122880 conv4_block23_0_relu[0][0] __________________________________________________________________________________________________ conv4_block23_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block23_1_conv[0][0] __________________________________________________________________________________________________ conv4_block23_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block23_1_bn[0][0] __________________________________________________________________________________________________ conv4_block23_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block23_1_relu[0][0] __________________________________________________________________________________________________ conv4_block23_concat (Concatena (None, 12, 16, 992) 0 conv4_block22_concat[0][0] conv4_block23_2_conv[0][0] __________________________________________________________________________________________________ conv4_block24_0_bn (BatchNormal (None, 12, 16, 992) 3968 conv4_block23_concat[0][0] __________________________________________________________________________________________________ conv4_block24_0_relu (Activatio (None, 12, 16, 992) 0 conv4_block24_0_bn[0][0] __________________________________________________________________________________________________ conv4_block24_1_conv (Conv2D) (None, 12, 16, 128) 126976 conv4_block24_0_relu[0][0] __________________________________________________________________________________________________ conv4_block24_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block24_1_conv[0][0] __________________________________________________________________________________________________ conv4_block24_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block24_1_bn[0][0] __________________________________________________________________________________________________ conv4_block24_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block24_1_relu[0][0] __________________________________________________________________________________________________ conv4_block24_concat (Concatena (None, 12, 16, 1024) 0 conv4_block23_concat[0][0] conv4_block24_2_conv[0][0] __________________________________________________________________________________________________ conv4_block25_0_bn (BatchNormal (None, 12, 16, 1024) 4096 conv4_block24_concat[0][0] __________________________________________________________________________________________________ conv4_block25_0_relu (Activatio (None, 12, 16, 1024) 0 conv4_block25_0_bn[0][0] __________________________________________________________________________________________________ conv4_block25_1_conv (Conv2D) (None, 12, 16, 128) 131072 conv4_block25_0_relu[0][0] __________________________________________________________________________________________________ conv4_block25_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block25_1_conv[0][0] __________________________________________________________________________________________________ conv4_block25_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block25_1_bn[0][0] __________________________________________________________________________________________________ conv4_block25_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block25_1_relu[0][0] __________________________________________________________________________________________________ conv4_block25_concat (Concatena (None, 12, 16, 1056) 0 conv4_block24_concat[0][0] conv4_block25_2_conv[0][0] __________________________________________________________________________________________________ conv4_block26_0_bn (BatchNormal (None, 12, 16, 1056) 4224 conv4_block25_concat[0][0] __________________________________________________________________________________________________ conv4_block26_0_relu (Activatio (None, 12, 16, 1056) 0 conv4_block26_0_bn[0][0] __________________________________________________________________________________________________ conv4_block26_1_conv (Conv2D) (None, 12, 16, 128) 135168 conv4_block26_0_relu[0][0] __________________________________________________________________________________________________ conv4_block26_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block26_1_conv[0][0] __________________________________________________________________________________________________ conv4_block26_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block26_1_bn[0][0] __________________________________________________________________________________________________ conv4_block26_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block26_1_relu[0][0] __________________________________________________________________________________________________ conv4_block26_concat (Concatena (None, 12, 16, 1088) 0 conv4_block25_concat[0][0] conv4_block26_2_conv[0][0] __________________________________________________________________________________________________ conv4_block27_0_bn (BatchNormal (None, 12, 16, 1088) 4352 conv4_block26_concat[0][0] __________________________________________________________________________________________________ conv4_block27_0_relu (Activatio (None, 12, 16, 1088) 0 conv4_block27_0_bn[0][0] __________________________________________________________________________________________________ conv4_block27_1_conv (Conv2D) (None, 12, 16, 128) 139264 conv4_block27_0_relu[0][0] __________________________________________________________________________________________________ conv4_block27_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block27_1_conv[0][0] __________________________________________________________________________________________________ conv4_block27_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block27_1_bn[0][0] __________________________________________________________________________________________________ conv4_block27_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block27_1_relu[0][0] __________________________________________________________________________________________________ conv4_block27_concat (Concatena (None, 12, 16, 1120) 0 conv4_block26_concat[0][0] conv4_block27_2_conv[0][0] __________________________________________________________________________________________________ conv4_block28_0_bn (BatchNormal (None, 12, 16, 1120) 4480 conv4_block27_concat[0][0] __________________________________________________________________________________________________ conv4_block28_0_relu (Activatio (None, 12, 16, 1120) 0 conv4_block28_0_bn[0][0] __________________________________________________________________________________________________ conv4_block28_1_conv (Conv2D) (None, 12, 16, 128) 143360 conv4_block28_0_relu[0][0] __________________________________________________________________________________________________ conv4_block28_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block28_1_conv[0][0] __________________________________________________________________________________________________ conv4_block28_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block28_1_bn[0][0] __________________________________________________________________________________________________ conv4_block28_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block28_1_relu[0][0] __________________________________________________________________________________________________ conv4_block28_concat (Concatena (None, 12, 16, 1152) 0 conv4_block27_concat[0][0] conv4_block28_2_conv[0][0] __________________________________________________________________________________________________ conv4_block29_0_bn (BatchNormal (None, 12, 16, 1152) 4608 conv4_block28_concat[0][0] __________________________________________________________________________________________________ conv4_block29_0_relu (Activatio (None, 12, 16, 1152) 0 conv4_block29_0_bn[0][0] __________________________________________________________________________________________________ conv4_block29_1_conv (Conv2D) (None, 12, 16, 128) 147456 conv4_block29_0_relu[0][0] __________________________________________________________________________________________________ conv4_block29_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block29_1_conv[0][0] __________________________________________________________________________________________________ conv4_block29_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block29_1_bn[0][0] __________________________________________________________________________________________________ conv4_block29_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block29_1_relu[0][0] __________________________________________________________________________________________________ conv4_block29_concat (Concatena (None, 12, 16, 1184) 0 conv4_block28_concat[0][0] conv4_block29_2_conv[0][0] __________________________________________________________________________________________________ conv4_block30_0_bn (BatchNormal (None, 12, 16, 1184) 4736 conv4_block29_concat[0][0] __________________________________________________________________________________________________ conv4_block30_0_relu (Activatio (None, 12, 16, 1184) 0 conv4_block30_0_bn[0][0] __________________________________________________________________________________________________ conv4_block30_1_conv (Conv2D) (None, 12, 16, 128) 151552 conv4_block30_0_relu[0][0] __________________________________________________________________________________________________ conv4_block30_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block30_1_conv[0][0] __________________________________________________________________________________________________ conv4_block30_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block30_1_bn[0][0] __________________________________________________________________________________________________ conv4_block30_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block30_1_relu[0][0] __________________________________________________________________________________________________ conv4_block30_concat (Concatena (None, 12, 16, 1216) 0 conv4_block29_concat[0][0] conv4_block30_2_conv[0][0] __________________________________________________________________________________________________ conv4_block31_0_bn (BatchNormal (None, 12, 16, 1216) 4864 conv4_block30_concat[0][0] __________________________________________________________________________________________________ conv4_block31_0_relu (Activatio (None, 12, 16, 1216) 0 conv4_block31_0_bn[0][0] __________________________________________________________________________________________________ conv4_block31_1_conv (Conv2D) (None, 12, 16, 128) 155648 conv4_block31_0_relu[0][0] __________________________________________________________________________________________________ conv4_block31_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block31_1_conv[0][0] __________________________________________________________________________________________________ conv4_block31_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block31_1_bn[0][0] __________________________________________________________________________________________________ conv4_block31_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block31_1_relu[0][0] __________________________________________________________________________________________________ conv4_block31_concat (Concatena (None, 12, 16, 1248) 0 conv4_block30_concat[0][0] conv4_block31_2_conv[0][0] __________________________________________________________________________________________________ conv4_block32_0_bn (BatchNormal (None, 12, 16, 1248) 4992 conv4_block31_concat[0][0] __________________________________________________________________________________________________ conv4_block32_0_relu (Activatio (None, 12, 16, 1248) 0 conv4_block32_0_bn[0][0] __________________________________________________________________________________________________ conv4_block32_1_conv (Conv2D) (None, 12, 16, 128) 159744 conv4_block32_0_relu[0][0] __________________________________________________________________________________________________ conv4_block32_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block32_1_conv[0][0] __________________________________________________________________________________________________ conv4_block32_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block32_1_bn[0][0] __________________________________________________________________________________________________ conv4_block32_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block32_1_relu[0][0] __________________________________________________________________________________________________ conv4_block32_concat (Concatena (None, 12, 16, 1280) 0 conv4_block31_concat[0][0] conv4_block32_2_conv[0][0] __________________________________________________________________________________________________ conv4_block33_0_bn (BatchNormal (None, 12, 16, 1280) 5120 conv4_block32_concat[0][0] __________________________________________________________________________________________________ conv4_block33_0_relu (Activatio (None, 12, 16, 1280) 0 conv4_block33_0_bn[0][0] __________________________________________________________________________________________________ conv4_block33_1_conv (Conv2D) (None, 12, 16, 128) 163840 conv4_block33_0_relu[0][0] __________________________________________________________________________________________________ conv4_block33_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block33_1_conv[0][0] __________________________________________________________________________________________________ conv4_block33_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block33_1_bn[0][0] __________________________________________________________________________________________________ conv4_block33_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block33_1_relu[0][0] __________________________________________________________________________________________________ conv4_block33_concat (Concatena (None, 12, 16, 1312) 0 conv4_block32_concat[0][0] conv4_block33_2_conv[0][0] __________________________________________________________________________________________________ conv4_block34_0_bn (BatchNormal (None, 12, 16, 1312) 5248 conv4_block33_concat[0][0] __________________________________________________________________________________________________ conv4_block34_0_relu (Activatio (None, 12, 16, 1312) 0 conv4_block34_0_bn[0][0] __________________________________________________________________________________________________ conv4_block34_1_conv (Conv2D) (None, 12, 16, 128) 167936 conv4_block34_0_relu[0][0] __________________________________________________________________________________________________ conv4_block34_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block34_1_conv[0][0] __________________________________________________________________________________________________ conv4_block34_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block34_1_bn[0][0] __________________________________________________________________________________________________ conv4_block34_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block34_1_relu[0][0] __________________________________________________________________________________________________ conv4_block34_concat (Concatena (None, 12, 16, 1344) 0 conv4_block33_concat[0][0] conv4_block34_2_conv[0][0] __________________________________________________________________________________________________ conv4_block35_0_bn (BatchNormal (None, 12, 16, 1344) 5376 conv4_block34_concat[0][0] __________________________________________________________________________________________________ conv4_block35_0_relu (Activatio (None, 12, 16, 1344) 0 conv4_block35_0_bn[0][0] __________________________________________________________________________________________________ conv4_block35_1_conv (Conv2D) (None, 12, 16, 128) 172032 conv4_block35_0_relu[0][0] __________________________________________________________________________________________________ conv4_block35_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block35_1_conv[0][0] __________________________________________________________________________________________________ conv4_block35_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block35_1_bn[0][0] __________________________________________________________________________________________________ conv4_block35_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block35_1_relu[0][0] __________________________________________________________________________________________________ conv4_block35_concat (Concatena (None, 12, 16, 1376) 0 conv4_block34_concat[0][0] conv4_block35_2_conv[0][0] __________________________________________________________________________________________________ conv4_block36_0_bn (BatchNormal (None, 12, 16, 1376) 5504 conv4_block35_concat[0][0] __________________________________________________________________________________________________ conv4_block36_0_relu (Activatio (None, 12, 16, 1376) 0 conv4_block36_0_bn[0][0] __________________________________________________________________________________________________ conv4_block36_1_conv (Conv2D) (None, 12, 16, 128) 176128 conv4_block36_0_relu[0][0] __________________________________________________________________________________________________ conv4_block36_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block36_1_conv[0][0] __________________________________________________________________________________________________ conv4_block36_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block36_1_bn[0][0] __________________________________________________________________________________________________ conv4_block36_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block36_1_relu[0][0] __________________________________________________________________________________________________ conv4_block36_concat (Concatena (None, 12, 16, 1408) 0 conv4_block35_concat[0][0] conv4_block36_2_conv[0][0] __________________________________________________________________________________________________ conv4_block37_0_bn (BatchNormal (None, 12, 16, 1408) 5632 conv4_block36_concat[0][0] __________________________________________________________________________________________________ conv4_block37_0_relu (Activatio (None, 12, 16, 1408) 0 conv4_block37_0_bn[0][0] __________________________________________________________________________________________________ conv4_block37_1_conv (Conv2D) (None, 12, 16, 128) 180224 conv4_block37_0_relu[0][0] __________________________________________________________________________________________________ conv4_block37_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block37_1_conv[0][0] __________________________________________________________________________________________________ conv4_block37_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block37_1_bn[0][0] __________________________________________________________________________________________________ conv4_block37_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block37_1_relu[0][0] __________________________________________________________________________________________________ conv4_block37_concat (Concatena (None, 12, 16, 1440) 0 conv4_block36_concat[0][0] conv4_block37_2_conv[0][0] __________________________________________________________________________________________________ conv4_block38_0_bn (BatchNormal (None, 12, 16, 1440) 5760 conv4_block37_concat[0][0] __________________________________________________________________________________________________ conv4_block38_0_relu (Activatio (None, 12, 16, 1440) 0 conv4_block38_0_bn[0][0] __________________________________________________________________________________________________ conv4_block38_1_conv (Conv2D) (None, 12, 16, 128) 184320 conv4_block38_0_relu[0][0] __________________________________________________________________________________________________ conv4_block38_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block38_1_conv[0][0] __________________________________________________________________________________________________ conv4_block38_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block38_1_bn[0][0] __________________________________________________________________________________________________ conv4_block38_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block38_1_relu[0][0] __________________________________________________________________________________________________ conv4_block38_concat (Concatena (None, 12, 16, 1472) 0 conv4_block37_concat[0][0] conv4_block38_2_conv[0][0] __________________________________________________________________________________________________ conv4_block39_0_bn (BatchNormal (None, 12, 16, 1472) 5888 conv4_block38_concat[0][0] __________________________________________________________________________________________________ conv4_block39_0_relu (Activatio (None, 12, 16, 1472) 0 conv4_block39_0_bn[0][0] __________________________________________________________________________________________________ conv4_block39_1_conv (Conv2D) (None, 12, 16, 128) 188416 conv4_block39_0_relu[0][0] __________________________________________________________________________________________________ conv4_block39_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block39_1_conv[0][0] __________________________________________________________________________________________________ conv4_block39_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block39_1_bn[0][0] __________________________________________________________________________________________________ conv4_block39_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block39_1_relu[0][0] __________________________________________________________________________________________________ conv4_block39_concat (Concatena (None, 12, 16, 1504) 0 conv4_block38_concat[0][0] conv4_block39_2_conv[0][0] __________________________________________________________________________________________________ conv4_block40_0_bn (BatchNormal (None, 12, 16, 1504) 6016 conv4_block39_concat[0][0] __________________________________________________________________________________________________ conv4_block40_0_relu (Activatio (None, 12, 16, 1504) 0 conv4_block40_0_bn[0][0] __________________________________________________________________________________________________ conv4_block40_1_conv (Conv2D) (None, 12, 16, 128) 192512 conv4_block40_0_relu[0][0] __________________________________________________________________________________________________ conv4_block40_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block40_1_conv[0][0] __________________________________________________________________________________________________ conv4_block40_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block40_1_bn[0][0] __________________________________________________________________________________________________ conv4_block40_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block40_1_relu[0][0] __________________________________________________________________________________________________ conv4_block40_concat (Concatena (None, 12, 16, 1536) 0 conv4_block39_concat[0][0] conv4_block40_2_conv[0][0] __________________________________________________________________________________________________ conv4_block41_0_bn (BatchNormal (None, 12, 16, 1536) 6144 conv4_block40_concat[0][0] __________________________________________________________________________________________________ conv4_block41_0_relu (Activatio (None, 12, 16, 1536) 0 conv4_block41_0_bn[0][0] __________________________________________________________________________________________________ conv4_block41_1_conv (Conv2D) (None, 12, 16, 128) 196608 conv4_block41_0_relu[0][0] __________________________________________________________________________________________________ conv4_block41_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block41_1_conv[0][0] __________________________________________________________________________________________________ conv4_block41_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block41_1_bn[0][0] __________________________________________________________________________________________________ conv4_block41_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block41_1_relu[0][0] __________________________________________________________________________________________________ conv4_block41_concat (Concatena (None, 12, 16, 1568) 0 conv4_block40_concat[0][0] conv4_block41_2_conv[0][0] __________________________________________________________________________________________________ conv4_block42_0_bn (BatchNormal (None, 12, 16, 1568) 6272 conv4_block41_concat[0][0] __________________________________________________________________________________________________ conv4_block42_0_relu (Activatio (None, 12, 16, 1568) 0 conv4_block42_0_bn[0][0] __________________________________________________________________________________________________ conv4_block42_1_conv (Conv2D) (None, 12, 16, 128) 200704 conv4_block42_0_relu[0][0] __________________________________________________________________________________________________ conv4_block42_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block42_1_conv[0][0] __________________________________________________________________________________________________ conv4_block42_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block42_1_bn[0][0] __________________________________________________________________________________________________ conv4_block42_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block42_1_relu[0][0] __________________________________________________________________________________________________ conv4_block42_concat (Concatena (None, 12, 16, 1600) 0 conv4_block41_concat[0][0] conv4_block42_2_conv[0][0] __________________________________________________________________________________________________ conv4_block43_0_bn (BatchNormal (None, 12, 16, 1600) 6400 conv4_block42_concat[0][0] __________________________________________________________________________________________________ conv4_block43_0_relu (Activatio (None, 12, 16, 1600) 0 conv4_block43_0_bn[0][0] __________________________________________________________________________________________________ conv4_block43_1_conv (Conv2D) (None, 12, 16, 128) 204800 conv4_block43_0_relu[0][0] __________________________________________________________________________________________________ conv4_block43_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block43_1_conv[0][0] __________________________________________________________________________________________________ conv4_block43_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block43_1_bn[0][0] __________________________________________________________________________________________________ conv4_block43_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block43_1_relu[0][0] __________________________________________________________________________________________________ conv4_block43_concat (Concatena (None, 12, 16, 1632) 0 conv4_block42_concat[0][0] conv4_block43_2_conv[0][0] __________________________________________________________________________________________________ conv4_block44_0_bn (BatchNormal (None, 12, 16, 1632) 6528 conv4_block43_concat[0][0] __________________________________________________________________________________________________ conv4_block44_0_relu (Activatio (None, 12, 16, 1632) 0 conv4_block44_0_bn[0][0] __________________________________________________________________________________________________ conv4_block44_1_conv (Conv2D) (None, 12, 16, 128) 208896 conv4_block44_0_relu[0][0] __________________________________________________________________________________________________ conv4_block44_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block44_1_conv[0][0] __________________________________________________________________________________________________ conv4_block44_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block44_1_bn[0][0] __________________________________________________________________________________________________ conv4_block44_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block44_1_relu[0][0] __________________________________________________________________________________________________ conv4_block44_concat (Concatena (None, 12, 16, 1664) 0 conv4_block43_concat[0][0] conv4_block44_2_conv[0][0] __________________________________________________________________________________________________ conv4_block45_0_bn (BatchNormal (None, 12, 16, 1664) 6656 conv4_block44_concat[0][0] __________________________________________________________________________________________________ conv4_block45_0_relu (Activatio (None, 12, 16, 1664) 0 conv4_block45_0_bn[0][0] __________________________________________________________________________________________________ conv4_block45_1_conv (Conv2D) (None, 12, 16, 128) 212992 conv4_block45_0_relu[0][0] __________________________________________________________________________________________________ conv4_block45_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block45_1_conv[0][0] __________________________________________________________________________________________________ conv4_block45_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block45_1_bn[0][0] __________________________________________________________________________________________________ conv4_block45_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block45_1_relu[0][0] __________________________________________________________________________________________________ conv4_block45_concat (Concatena (None, 12, 16, 1696) 0 conv4_block44_concat[0][0] conv4_block45_2_conv[0][0] __________________________________________________________________________________________________ conv4_block46_0_bn (BatchNormal (None, 12, 16, 1696) 6784 conv4_block45_concat[0][0] __________________________________________________________________________________________________ conv4_block46_0_relu (Activatio (None, 12, 16, 1696) 0 conv4_block46_0_bn[0][0] __________________________________________________________________________________________________ conv4_block46_1_conv (Conv2D) (None, 12, 16, 128) 217088 conv4_block46_0_relu[0][0] __________________________________________________________________________________________________ conv4_block46_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block46_1_conv[0][0] __________________________________________________________________________________________________ conv4_block46_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block46_1_bn[0][0] __________________________________________________________________________________________________ conv4_block46_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block46_1_relu[0][0] __________________________________________________________________________________________________ conv4_block46_concat (Concatena (None, 12, 16, 1728) 0 conv4_block45_concat[0][0] conv4_block46_2_conv[0][0] __________________________________________________________________________________________________ conv4_block47_0_bn (BatchNormal (None, 12, 16, 1728) 6912 conv4_block46_concat[0][0] __________________________________________________________________________________________________ conv4_block47_0_relu (Activatio (None, 12, 16, 1728) 0 conv4_block47_0_bn[0][0] __________________________________________________________________________________________________ conv4_block47_1_conv (Conv2D) (None, 12, 16, 128) 221184 conv4_block47_0_relu[0][0] __________________________________________________________________________________________________ conv4_block47_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block47_1_conv[0][0] __________________________________________________________________________________________________ conv4_block47_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block47_1_bn[0][0] __________________________________________________________________________________________________ conv4_block47_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block47_1_relu[0][0] __________________________________________________________________________________________________ conv4_block47_concat (Concatena (None, 12, 16, 1760) 0 conv4_block46_concat[0][0] conv4_block47_2_conv[0][0] __________________________________________________________________________________________________ conv4_block48_0_bn (BatchNormal (None, 12, 16, 1760) 7040 conv4_block47_concat[0][0] __________________________________________________________________________________________________ conv4_block48_0_relu (Activatio (None, 12, 16, 1760) 0 conv4_block48_0_bn[0][0] __________________________________________________________________________________________________ conv4_block48_1_conv (Conv2D) (None, 12, 16, 128) 225280 conv4_block48_0_relu[0][0] __________________________________________________________________________________________________ conv4_block48_1_bn (BatchNormal (None, 12, 16, 128) 512 conv4_block48_1_conv[0][0] __________________________________________________________________________________________________ conv4_block48_1_relu (Activatio (None, 12, 16, 128) 0 conv4_block48_1_bn[0][0] __________________________________________________________________________________________________ conv4_block48_2_conv (Conv2D) (None, 12, 16, 32) 36864 conv4_block48_1_relu[0][0] __________________________________________________________________________________________________ conv4_block48_concat (Concatena (None, 12, 16, 1792) 0 conv4_block47_concat[0][0] conv4_block48_2_conv[0][0] __________________________________________________________________________________________________ pool4_bn (BatchNormalization) (None, 12, 16, 1792) 7168 conv4_block48_concat[0][0] __________________________________________________________________________________________________ pool4_relu (Activation) (None, 12, 16, 1792) 0 pool4_bn[0][0] __________________________________________________________________________________________________ pool4_conv (Conv2D) (None, 12, 16, 896) 1605632 pool4_relu[0][0] __________________________________________________________________________________________________ pool4_pool (AveragePooling2D) (None, 6, 8, 896) 0 pool4_conv[0][0] __________________________________________________________________________________________________ conv5_block1_0_bn (BatchNormali (None, 6, 8, 896) 3584 pool4_pool[0][0] __________________________________________________________________________________________________ conv5_block1_0_relu (Activation (None, 6, 8, 896) 0 conv5_block1_0_bn[0][0] __________________________________________________________________________________________________ conv5_block1_1_conv (Conv2D) (None, 6, 8, 128) 114688 conv5_block1_0_relu[0][0] __________________________________________________________________________________________________ conv5_block1_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block1_1_conv[0][0] __________________________________________________________________________________________________ conv5_block1_1_relu (Activation (None, 6, 8, 128) 0 conv5_block1_1_bn[0][0] __________________________________________________________________________________________________ conv5_block1_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block1_1_relu[0][0] __________________________________________________________________________________________________ conv5_block1_concat (Concatenat (None, 6, 8, 928) 0 pool4_pool[0][0] conv5_block1_2_conv[0][0] __________________________________________________________________________________________________ conv5_block2_0_bn (BatchNormali (None, 6, 8, 928) 3712 conv5_block1_concat[0][0] __________________________________________________________________________________________________ conv5_block2_0_relu (Activation (None, 6, 8, 928) 0 conv5_block2_0_bn[0][0] __________________________________________________________________________________________________ conv5_block2_1_conv (Conv2D) (None, 6, 8, 128) 118784 conv5_block2_0_relu[0][0] __________________________________________________________________________________________________ conv5_block2_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block2_1_conv[0][0] __________________________________________________________________________________________________ conv5_block2_1_relu (Activation (None, 6, 8, 128) 0 conv5_block2_1_bn[0][0] __________________________________________________________________________________________________ conv5_block2_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block2_1_relu[0][0] __________________________________________________________________________________________________ conv5_block2_concat (Concatenat (None, 6, 8, 960) 0 conv5_block1_concat[0][0] conv5_block2_2_conv[0][0] __________________________________________________________________________________________________ conv5_block3_0_bn (BatchNormali (None, 6, 8, 960) 3840 conv5_block2_concat[0][0] __________________________________________________________________________________________________ conv5_block3_0_relu (Activation (None, 6, 8, 960) 0 conv5_block3_0_bn[0][0] __________________________________________________________________________________________________ conv5_block3_1_conv (Conv2D) (None, 6, 8, 128) 122880 conv5_block3_0_relu[0][0] __________________________________________________________________________________________________ conv5_block3_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block3_1_conv[0][0] __________________________________________________________________________________________________ conv5_block3_1_relu (Activation (None, 6, 8, 128) 0 conv5_block3_1_bn[0][0] __________________________________________________________________________________________________ conv5_block3_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block3_1_relu[0][0] __________________________________________________________________________________________________ conv5_block3_concat (Concatenat (None, 6, 8, 992) 0 conv5_block2_concat[0][0] conv5_block3_2_conv[0][0] __________________________________________________________________________________________________ conv5_block4_0_bn (BatchNormali (None, 6, 8, 992) 3968 conv5_block3_concat[0][0] __________________________________________________________________________________________________ conv5_block4_0_relu (Activation (None, 6, 8, 992) 0 conv5_block4_0_bn[0][0] __________________________________________________________________________________________________ conv5_block4_1_conv (Conv2D) (None, 6, 8, 128) 126976 conv5_block4_0_relu[0][0] __________________________________________________________________________________________________ conv5_block4_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block4_1_conv[0][0] __________________________________________________________________________________________________ conv5_block4_1_relu (Activation (None, 6, 8, 128) 0 conv5_block4_1_bn[0][0] __________________________________________________________________________________________________ conv5_block4_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block4_1_relu[0][0] __________________________________________________________________________________________________ conv5_block4_concat (Concatenat (None, 6, 8, 1024) 0 conv5_block3_concat[0][0] conv5_block4_2_conv[0][0] __________________________________________________________________________________________________ conv5_block5_0_bn (BatchNormali (None, 6, 8, 1024) 4096 conv5_block4_concat[0][0] __________________________________________________________________________________________________ conv5_block5_0_relu (Activation (None, 6, 8, 1024) 0 conv5_block5_0_bn[0][0] __________________________________________________________________________________________________ conv5_block5_1_conv (Conv2D) (None, 6, 8, 128) 131072 conv5_block5_0_relu[0][0] __________________________________________________________________________________________________ conv5_block5_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block5_1_conv[0][0] __________________________________________________________________________________________________ conv5_block5_1_relu (Activation (None, 6, 8, 128) 0 conv5_block5_1_bn[0][0] __________________________________________________________________________________________________ conv5_block5_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block5_1_relu[0][0] __________________________________________________________________________________________________ conv5_block5_concat (Concatenat (None, 6, 8, 1056) 0 conv5_block4_concat[0][0] conv5_block5_2_conv[0][0] __________________________________________________________________________________________________ conv5_block6_0_bn (BatchNormali (None, 6, 8, 1056) 4224 conv5_block5_concat[0][0] __________________________________________________________________________________________________ conv5_block6_0_relu (Activation (None, 6, 8, 1056) 0 conv5_block6_0_bn[0][0] __________________________________________________________________________________________________ conv5_block6_1_conv (Conv2D) (None, 6, 8, 128) 135168 conv5_block6_0_relu[0][0] __________________________________________________________________________________________________ conv5_block6_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block6_1_conv[0][0] __________________________________________________________________________________________________ conv5_block6_1_relu (Activation (None, 6, 8, 128) 0 conv5_block6_1_bn[0][0] __________________________________________________________________________________________________ conv5_block6_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block6_1_relu[0][0] __________________________________________________________________________________________________ conv5_block6_concat (Concatenat (None, 6, 8, 1088) 0 conv5_block5_concat[0][0] conv5_block6_2_conv[0][0] __________________________________________________________________________________________________ conv5_block7_0_bn (BatchNormali (None, 6, 8, 1088) 4352 conv5_block6_concat[0][0] __________________________________________________________________________________________________ conv5_block7_0_relu (Activation (None, 6, 8, 1088) 0 conv5_block7_0_bn[0][0] __________________________________________________________________________________________________ conv5_block7_1_conv (Conv2D) (None, 6, 8, 128) 139264 conv5_block7_0_relu[0][0] __________________________________________________________________________________________________ conv5_block7_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block7_1_conv[0][0] __________________________________________________________________________________________________ conv5_block7_1_relu (Activation (None, 6, 8, 128) 0 conv5_block7_1_bn[0][0] __________________________________________________________________________________________________ conv5_block7_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block7_1_relu[0][0] __________________________________________________________________________________________________ conv5_block7_concat (Concatenat (None, 6, 8, 1120) 0 conv5_block6_concat[0][0] conv5_block7_2_conv[0][0] __________________________________________________________________________________________________ conv5_block8_0_bn (BatchNormali (None, 6, 8, 1120) 4480 conv5_block7_concat[0][0] __________________________________________________________________________________________________ conv5_block8_0_relu (Activation (None, 6, 8, 1120) 0 conv5_block8_0_bn[0][0] __________________________________________________________________________________________________ conv5_block8_1_conv (Conv2D) (None, 6, 8, 128) 143360 conv5_block8_0_relu[0][0] __________________________________________________________________________________________________ conv5_block8_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block8_1_conv[0][0] __________________________________________________________________________________________________ conv5_block8_1_relu (Activation (None, 6, 8, 128) 0 conv5_block8_1_bn[0][0] __________________________________________________________________________________________________ conv5_block8_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block8_1_relu[0][0] __________________________________________________________________________________________________ conv5_block8_concat (Concatenat (None, 6, 8, 1152) 0 conv5_block7_concat[0][0] conv5_block8_2_conv[0][0] __________________________________________________________________________________________________ conv5_block9_0_bn (BatchNormali (None, 6, 8, 1152) 4608 conv5_block8_concat[0][0] __________________________________________________________________________________________________ conv5_block9_0_relu (Activation (None, 6, 8, 1152) 0 conv5_block9_0_bn[0][0] __________________________________________________________________________________________________ conv5_block9_1_conv (Conv2D) (None, 6, 8, 128) 147456 conv5_block9_0_relu[0][0] __________________________________________________________________________________________________ conv5_block9_1_bn (BatchNormali (None, 6, 8, 128) 512 conv5_block9_1_conv[0][0] __________________________________________________________________________________________________ conv5_block9_1_relu (Activation (None, 6, 8, 128) 0 conv5_block9_1_bn[0][0] __________________________________________________________________________________________________ conv5_block9_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block9_1_relu[0][0] __________________________________________________________________________________________________ conv5_block9_concat (Concatenat (None, 6, 8, 1184) 0 conv5_block8_concat[0][0] conv5_block9_2_conv[0][0] __________________________________________________________________________________________________ conv5_block10_0_bn (BatchNormal (None, 6, 8, 1184) 4736 conv5_block9_concat[0][0] __________________________________________________________________________________________________ conv5_block10_0_relu (Activatio (None, 6, 8, 1184) 0 conv5_block10_0_bn[0][0] __________________________________________________________________________________________________ conv5_block10_1_conv (Conv2D) (None, 6, 8, 128) 151552 conv5_block10_0_relu[0][0] __________________________________________________________________________________________________ conv5_block10_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block10_1_conv[0][0] __________________________________________________________________________________________________ conv5_block10_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block10_1_bn[0][0] __________________________________________________________________________________________________ conv5_block10_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block10_1_relu[0][0] __________________________________________________________________________________________________ conv5_block10_concat (Concatena (None, 6, 8, 1216) 0 conv5_block9_concat[0][0] conv5_block10_2_conv[0][0] __________________________________________________________________________________________________ conv5_block11_0_bn (BatchNormal (None, 6, 8, 1216) 4864 conv5_block10_concat[0][0] __________________________________________________________________________________________________ conv5_block11_0_relu (Activatio (None, 6, 8, 1216) 0 conv5_block11_0_bn[0][0] __________________________________________________________________________________________________ conv5_block11_1_conv (Conv2D) (None, 6, 8, 128) 155648 conv5_block11_0_relu[0][0] __________________________________________________________________________________________________ conv5_block11_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block11_1_conv[0][0] __________________________________________________________________________________________________ conv5_block11_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block11_1_bn[0][0] __________________________________________________________________________________________________ conv5_block11_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block11_1_relu[0][0] __________________________________________________________________________________________________ conv5_block11_concat (Concatena (None, 6, 8, 1248) 0 conv5_block10_concat[0][0] conv5_block11_2_conv[0][0] __________________________________________________________________________________________________ conv5_block12_0_bn (BatchNormal (None, 6, 8, 1248) 4992 conv5_block11_concat[0][0] __________________________________________________________________________________________________ conv5_block12_0_relu (Activatio (None, 6, 8, 1248) 0 conv5_block12_0_bn[0][0] __________________________________________________________________________________________________ conv5_block12_1_conv (Conv2D) (None, 6, 8, 128) 159744 conv5_block12_0_relu[0][0] __________________________________________________________________________________________________ conv5_block12_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block12_1_conv[0][0] __________________________________________________________________________________________________ conv5_block12_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block12_1_bn[0][0] __________________________________________________________________________________________________ conv5_block12_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block12_1_relu[0][0] __________________________________________________________________________________________________ conv5_block12_concat (Concatena (None, 6, 8, 1280) 0 conv5_block11_concat[0][0] conv5_block12_2_conv[0][0] __________________________________________________________________________________________________ conv5_block13_0_bn (BatchNormal (None, 6, 8, 1280) 5120 conv5_block12_concat[0][0] __________________________________________________________________________________________________ conv5_block13_0_relu (Activatio (None, 6, 8, 1280) 0 conv5_block13_0_bn[0][0] __________________________________________________________________________________________________ conv5_block13_1_conv (Conv2D) (None, 6, 8, 128) 163840 conv5_block13_0_relu[0][0] __________________________________________________________________________________________________ conv5_block13_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block13_1_conv[0][0] __________________________________________________________________________________________________ conv5_block13_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block13_1_bn[0][0] __________________________________________________________________________________________________ conv5_block13_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block13_1_relu[0][0] __________________________________________________________________________________________________ conv5_block13_concat (Concatena (None, 6, 8, 1312) 0 conv5_block12_concat[0][0] conv5_block13_2_conv[0][0] __________________________________________________________________________________________________ conv5_block14_0_bn (BatchNormal (None, 6, 8, 1312) 5248 conv5_block13_concat[0][0] __________________________________________________________________________________________________ conv5_block14_0_relu (Activatio (None, 6, 8, 1312) 0 conv5_block14_0_bn[0][0] __________________________________________________________________________________________________ conv5_block14_1_conv (Conv2D) (None, 6, 8, 128) 167936 conv5_block14_0_relu[0][0] __________________________________________________________________________________________________ conv5_block14_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block14_1_conv[0][0] __________________________________________________________________________________________________ conv5_block14_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block14_1_bn[0][0] __________________________________________________________________________________________________ conv5_block14_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block14_1_relu[0][0] __________________________________________________________________________________________________ conv5_block14_concat (Concatena (None, 6, 8, 1344) 0 conv5_block13_concat[0][0] conv5_block14_2_conv[0][0] __________________________________________________________________________________________________ conv5_block15_0_bn (BatchNormal (None, 6, 8, 1344) 5376 conv5_block14_concat[0][0] __________________________________________________________________________________________________ conv5_block15_0_relu (Activatio (None, 6, 8, 1344) 0 conv5_block15_0_bn[0][0] __________________________________________________________________________________________________ conv5_block15_1_conv (Conv2D) (None, 6, 8, 128) 172032 conv5_block15_0_relu[0][0] __________________________________________________________________________________________________ conv5_block15_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block15_1_conv[0][0] __________________________________________________________________________________________________ conv5_block15_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block15_1_bn[0][0] __________________________________________________________________________________________________ conv5_block15_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block15_1_relu[0][0] __________________________________________________________________________________________________ conv5_block15_concat (Concatena (None, 6, 8, 1376) 0 conv5_block14_concat[0][0] conv5_block15_2_conv[0][0] __________________________________________________________________________________________________ conv5_block16_0_bn (BatchNormal (None, 6, 8, 1376) 5504 conv5_block15_concat[0][0] __________________________________________________________________________________________________ conv5_block16_0_relu (Activatio (None, 6, 8, 1376) 0 conv5_block16_0_bn[0][0] __________________________________________________________________________________________________ conv5_block16_1_conv (Conv2D) (None, 6, 8, 128) 176128 conv5_block16_0_relu[0][0] __________________________________________________________________________________________________ conv5_block16_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block16_1_conv[0][0] __________________________________________________________________________________________________ conv5_block16_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block16_1_bn[0][0] __________________________________________________________________________________________________ conv5_block16_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block16_1_relu[0][0] __________________________________________________________________________________________________ conv5_block16_concat (Concatena (None, 6, 8, 1408) 0 conv5_block15_concat[0][0] conv5_block16_2_conv[0][0] __________________________________________________________________________________________________ conv5_block17_0_bn (BatchNormal (None, 6, 8, 1408) 5632 conv5_block16_concat[0][0] __________________________________________________________________________________________________ conv5_block17_0_relu (Activatio (None, 6, 8, 1408) 0 conv5_block17_0_bn[0][0] __________________________________________________________________________________________________ conv5_block17_1_conv (Conv2D) (None, 6, 8, 128) 180224 conv5_block17_0_relu[0][0] __________________________________________________________________________________________________ conv5_block17_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block17_1_conv[0][0] __________________________________________________________________________________________________ conv5_block17_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block17_1_bn[0][0] __________________________________________________________________________________________________ conv5_block17_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block17_1_relu[0][0] __________________________________________________________________________________________________ conv5_block17_concat (Concatena (None, 6, 8, 1440) 0 conv5_block16_concat[0][0] conv5_block17_2_conv[0][0] __________________________________________________________________________________________________ conv5_block18_0_bn (BatchNormal (None, 6, 8, 1440) 5760 conv5_block17_concat[0][0] __________________________________________________________________________________________________ conv5_block18_0_relu (Activatio (None, 6, 8, 1440) 0 conv5_block18_0_bn[0][0] __________________________________________________________________________________________________ conv5_block18_1_conv (Conv2D) (None, 6, 8, 128) 184320 conv5_block18_0_relu[0][0] __________________________________________________________________________________________________ conv5_block18_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block18_1_conv[0][0] __________________________________________________________________________________________________ conv5_block18_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block18_1_bn[0][0] __________________________________________________________________________________________________ conv5_block18_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block18_1_relu[0][0] __________________________________________________________________________________________________ conv5_block18_concat (Concatena (None, 6, 8, 1472) 0 conv5_block17_concat[0][0] conv5_block18_2_conv[0][0] __________________________________________________________________________________________________ conv5_block19_0_bn (BatchNormal (None, 6, 8, 1472) 5888 conv5_block18_concat[0][0] __________________________________________________________________________________________________ conv5_block19_0_relu (Activatio (None, 6, 8, 1472) 0 conv5_block19_0_bn[0][0] __________________________________________________________________________________________________ conv5_block19_1_conv (Conv2D) (None, 6, 8, 128) 188416 conv5_block19_0_relu[0][0] __________________________________________________________________________________________________ conv5_block19_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block19_1_conv[0][0] __________________________________________________________________________________________________ conv5_block19_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block19_1_bn[0][0] __________________________________________________________________________________________________ conv5_block19_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block19_1_relu[0][0] __________________________________________________________________________________________________ conv5_block19_concat (Concatena (None, 6, 8, 1504) 0 conv5_block18_concat[0][0] conv5_block19_2_conv[0][0] __________________________________________________________________________________________________ conv5_block20_0_bn (BatchNormal (None, 6, 8, 1504) 6016 conv5_block19_concat[0][0] __________________________________________________________________________________________________ conv5_block20_0_relu (Activatio (None, 6, 8, 1504) 0 conv5_block20_0_bn[0][0] __________________________________________________________________________________________________ conv5_block20_1_conv (Conv2D) (None, 6, 8, 128) 192512 conv5_block20_0_relu[0][0] __________________________________________________________________________________________________ conv5_block20_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block20_1_conv[0][0] __________________________________________________________________________________________________ conv5_block20_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block20_1_bn[0][0] __________________________________________________________________________________________________ conv5_block20_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block20_1_relu[0][0] __________________________________________________________________________________________________ conv5_block20_concat (Concatena (None, 6, 8, 1536) 0 conv5_block19_concat[0][0] conv5_block20_2_conv[0][0] __________________________________________________________________________________________________ conv5_block21_0_bn (BatchNormal (None, 6, 8, 1536) 6144 conv5_block20_concat[0][0] __________________________________________________________________________________________________ conv5_block21_0_relu (Activatio (None, 6, 8, 1536) 0 conv5_block21_0_bn[0][0] __________________________________________________________________________________________________ conv5_block21_1_conv (Conv2D) (None, 6, 8, 128) 196608 conv5_block21_0_relu[0][0] __________________________________________________________________________________________________ conv5_block21_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block21_1_conv[0][0] __________________________________________________________________________________________________ conv5_block21_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block21_1_bn[0][0] __________________________________________________________________________________________________ conv5_block21_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block21_1_relu[0][0] __________________________________________________________________________________________________ conv5_block21_concat (Concatena (None, 6, 8, 1568) 0 conv5_block20_concat[0][0] conv5_block21_2_conv[0][0] __________________________________________________________________________________________________ conv5_block22_0_bn (BatchNormal (None, 6, 8, 1568) 6272 conv5_block21_concat[0][0] __________________________________________________________________________________________________ conv5_block22_0_relu (Activatio (None, 6, 8, 1568) 0 conv5_block22_0_bn[0][0] __________________________________________________________________________________________________ conv5_block22_1_conv (Conv2D) (None, 6, 8, 128) 200704 conv5_block22_0_relu[0][0] __________________________________________________________________________________________________ conv5_block22_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block22_1_conv[0][0] __________________________________________________________________________________________________ conv5_block22_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block22_1_bn[0][0] __________________________________________________________________________________________________ conv5_block22_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block22_1_relu[0][0] __________________________________________________________________________________________________ conv5_block22_concat (Concatena (None, 6, 8, 1600) 0 conv5_block21_concat[0][0] conv5_block22_2_conv[0][0] __________________________________________________________________________________________________ conv5_block23_0_bn (BatchNormal (None, 6, 8, 1600) 6400 conv5_block22_concat[0][0] __________________________________________________________________________________________________ conv5_block23_0_relu (Activatio (None, 6, 8, 1600) 0 conv5_block23_0_bn[0][0] __________________________________________________________________________________________________ conv5_block23_1_conv (Conv2D) (None, 6, 8, 128) 204800 conv5_block23_0_relu[0][0] __________________________________________________________________________________________________ conv5_block23_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block23_1_conv[0][0] __________________________________________________________________________________________________ conv5_block23_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block23_1_bn[0][0] __________________________________________________________________________________________________ conv5_block23_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block23_1_relu[0][0] __________________________________________________________________________________________________ conv5_block23_concat (Concatena (None, 6, 8, 1632) 0 conv5_block22_concat[0][0] conv5_block23_2_conv[0][0] __________________________________________________________________________________________________ conv5_block24_0_bn (BatchNormal (None, 6, 8, 1632) 6528 conv5_block23_concat[0][0] __________________________________________________________________________________________________ conv5_block24_0_relu (Activatio (None, 6, 8, 1632) 0 conv5_block24_0_bn[0][0] __________________________________________________________________________________________________ conv5_block24_1_conv (Conv2D) (None, 6, 8, 128) 208896 conv5_block24_0_relu[0][0] __________________________________________________________________________________________________ conv5_block24_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block24_1_conv[0][0] __________________________________________________________________________________________________ conv5_block24_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block24_1_bn[0][0] __________________________________________________________________________________________________ conv5_block24_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block24_1_relu[0][0] __________________________________________________________________________________________________ conv5_block24_concat (Concatena (None, 6, 8, 1664) 0 conv5_block23_concat[0][0] conv5_block24_2_conv[0][0] __________________________________________________________________________________________________ conv5_block25_0_bn (BatchNormal (None, 6, 8, 1664) 6656 conv5_block24_concat[0][0] __________________________________________________________________________________________________ conv5_block25_0_relu (Activatio (None, 6, 8, 1664) 0 conv5_block25_0_bn[0][0] __________________________________________________________________________________________________ conv5_block25_1_conv (Conv2D) (None, 6, 8, 128) 212992 conv5_block25_0_relu[0][0] __________________________________________________________________________________________________ conv5_block25_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block25_1_conv[0][0] __________________________________________________________________________________________________ conv5_block25_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block25_1_bn[0][0] __________________________________________________________________________________________________ conv5_block25_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block25_1_relu[0][0] __________________________________________________________________________________________________ conv5_block25_concat (Concatena (None, 6, 8, 1696) 0 conv5_block24_concat[0][0] conv5_block25_2_conv[0][0] __________________________________________________________________________________________________ conv5_block26_0_bn (BatchNormal (None, 6, 8, 1696) 6784 conv5_block25_concat[0][0] __________________________________________________________________________________________________ conv5_block26_0_relu (Activatio (None, 6, 8, 1696) 0 conv5_block26_0_bn[0][0] __________________________________________________________________________________________________ conv5_block26_1_conv (Conv2D) (None, 6, 8, 128) 217088 conv5_block26_0_relu[0][0] __________________________________________________________________________________________________ conv5_block26_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block26_1_conv[0][0] __________________________________________________________________________________________________ conv5_block26_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block26_1_bn[0][0] __________________________________________________________________________________________________ conv5_block26_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block26_1_relu[0][0] __________________________________________________________________________________________________ conv5_block26_concat (Concatena (None, 6, 8, 1728) 0 conv5_block25_concat[0][0] conv5_block26_2_conv[0][0] __________________________________________________________________________________________________ conv5_block27_0_bn (BatchNormal (None, 6, 8, 1728) 6912 conv5_block26_concat[0][0] __________________________________________________________________________________________________ conv5_block27_0_relu (Activatio (None, 6, 8, 1728) 0 conv5_block27_0_bn[0][0] __________________________________________________________________________________________________ conv5_block27_1_conv (Conv2D) (None, 6, 8, 128) 221184 conv5_block27_0_relu[0][0] __________________________________________________________________________________________________ conv5_block27_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block27_1_conv[0][0] __________________________________________________________________________________________________ conv5_block27_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block27_1_bn[0][0] __________________________________________________________________________________________________ conv5_block27_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block27_1_relu[0][0] __________________________________________________________________________________________________ conv5_block27_concat (Concatena (None, 6, 8, 1760) 0 conv5_block26_concat[0][0] conv5_block27_2_conv[0][0] __________________________________________________________________________________________________ conv5_block28_0_bn (BatchNormal (None, 6, 8, 1760) 7040 conv5_block27_concat[0][0] __________________________________________________________________________________________________ conv5_block28_0_relu (Activatio (None, 6, 8, 1760) 0 conv5_block28_0_bn[0][0] __________________________________________________________________________________________________ conv5_block28_1_conv (Conv2D) (None, 6, 8, 128) 225280 conv5_block28_0_relu[0][0] __________________________________________________________________________________________________ conv5_block28_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block28_1_conv[0][0] __________________________________________________________________________________________________ conv5_block28_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block28_1_bn[0][0] __________________________________________________________________________________________________ conv5_block28_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block28_1_relu[0][0] __________________________________________________________________________________________________ conv5_block28_concat (Concatena (None, 6, 8, 1792) 0 conv5_block27_concat[0][0] conv5_block28_2_conv[0][0] __________________________________________________________________________________________________ conv5_block29_0_bn (BatchNormal (None, 6, 8, 1792) 7168 conv5_block28_concat[0][0] __________________________________________________________________________________________________ conv5_block29_0_relu (Activatio (None, 6, 8, 1792) 0 conv5_block29_0_bn[0][0] __________________________________________________________________________________________________ conv5_block29_1_conv (Conv2D) (None, 6, 8, 128) 229376 conv5_block29_0_relu[0][0] __________________________________________________________________________________________________ conv5_block29_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block29_1_conv[0][0] __________________________________________________________________________________________________ conv5_block29_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block29_1_bn[0][0] __________________________________________________________________________________________________ conv5_block29_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block29_1_relu[0][0] __________________________________________________________________________________________________ conv5_block29_concat (Concatena (None, 6, 8, 1824) 0 conv5_block28_concat[0][0] conv5_block29_2_conv[0][0] __________________________________________________________________________________________________ conv5_block30_0_bn (BatchNormal (None, 6, 8, 1824) 7296 conv5_block29_concat[0][0] __________________________________________________________________________________________________ conv5_block30_0_relu (Activatio (None, 6, 8, 1824) 0 conv5_block30_0_bn[0][0] __________________________________________________________________________________________________ conv5_block30_1_conv (Conv2D) (None, 6, 8, 128) 233472 conv5_block30_0_relu[0][0] __________________________________________________________________________________________________ conv5_block30_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block30_1_conv[0][0] __________________________________________________________________________________________________ conv5_block30_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block30_1_bn[0][0] __________________________________________________________________________________________________ conv5_block30_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block30_1_relu[0][0] __________________________________________________________________________________________________ conv5_block30_concat (Concatena (None, 6, 8, 1856) 0 conv5_block29_concat[0][0] conv5_block30_2_conv[0][0] __________________________________________________________________________________________________ conv5_block31_0_bn (BatchNormal (None, 6, 8, 1856) 7424 conv5_block30_concat[0][0] __________________________________________________________________________________________________ conv5_block31_0_relu (Activatio (None, 6, 8, 1856) 0 conv5_block31_0_bn[0][0] __________________________________________________________________________________________________ conv5_block31_1_conv (Conv2D) (None, 6, 8, 128) 237568 conv5_block31_0_relu[0][0] __________________________________________________________________________________________________ conv5_block31_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block31_1_conv[0][0] __________________________________________________________________________________________________ conv5_block31_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block31_1_bn[0][0] __________________________________________________________________________________________________ conv5_block31_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block31_1_relu[0][0] __________________________________________________________________________________________________ conv5_block31_concat (Concatena (None, 6, 8, 1888) 0 conv5_block30_concat[0][0] conv5_block31_2_conv[0][0] __________________________________________________________________________________________________ conv5_block32_0_bn (BatchNormal (None, 6, 8, 1888) 7552 conv5_block31_concat[0][0] __________________________________________________________________________________________________ conv5_block32_0_relu (Activatio (None, 6, 8, 1888) 0 conv5_block32_0_bn[0][0] __________________________________________________________________________________________________ conv5_block32_1_conv (Conv2D) (None, 6, 8, 128) 241664 conv5_block32_0_relu[0][0] __________________________________________________________________________________________________ conv5_block32_1_bn (BatchNormal (None, 6, 8, 128) 512 conv5_block32_1_conv[0][0] __________________________________________________________________________________________________ conv5_block32_1_relu (Activatio (None, 6, 8, 128) 0 conv5_block32_1_bn[0][0] __________________________________________________________________________________________________ conv5_block32_2_conv (Conv2D) (None, 6, 8, 32) 36864 conv5_block32_1_relu[0][0] __________________________________________________________________________________________________ conv5_block32_concat (Concatena (None, 6, 8, 1920) 0 conv5_block31_concat[0][0] conv5_block32_2_conv[0][0] __________________________________________________________________________________________________ bn (BatchNormalization) (None, 6, 8, 1920) 7680 conv5_block32_concat[0][0] __________________________________________________________________________________________________ relu (Activation) (None, 6, 8, 1920) 0 bn[0][0] __________________________________________________________________________________________________ global_max_pooling2d_3 (GlobalM (None, 1920) 0 relu[0][0] __________________________________________________________________________________________________ dense_5 (Dense) (None, 512) 983552 global_max_pooling2d_3[0][0] __________________________________________________________________________________________________ dropout_3 (Dropout) (None, 512) 0 dense_5[0][0] __________________________________________________________________________________________________ dense_6 (Dense) (None, 7) 3591 dropout_3[0][0] ================================================================================================== Total params: 19,309,127 Trainable params: 19,080,071 Non-trainable params: 229,056 __________________________________________________________________________________________________ ###Markdown Define Ensemble Model ###Code def ensemble(models, model_input): outputs = [model.outputs[0] for model in models] y = layers.Average()(outputs) model = Model(model_input, y, name='ensemble') return model ensemble_model = ensemble([denseNet_model, inception_model], model_input) ensemble_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) ###Output _____no_output_____ ###Markdown TestingThis is taking very long because I am running on my own PC to save money instead of on Floydhub ###Code loss_val, acc_val = ensemble_model.evaluate(X_val, y_val, verbose=1) print("Validation: accuracy = %f ; loss_v = %f" % (acc_val, loss_val)) loss_test, acc_test = ensemble_model.evaluate(X_test, y_test, verbose=1) print("Test: accuracy = %f ; loss = %f" % (acc_test, loss_test)) ###Output 1002/1002 [==============================] - 419s 418ms/step Test: accuracy = 0.885230 ; loss = 0.411560
notebooks/OLD/decision_variables_OLD.ipynb
###Markdown Problem formulation1. Define decision variables2. Define constraints (on the decision variables)3. Define objective function Global decision variables - FSIInputs required:- maximum building extents in 3D (in the form of a .obj to be provided by user)- the current occupation latticeNB THESE ARE ACTUALLY OBJECTIVE FUNCTIONS ###Code # first we define the decision variables for the programmatic minimum requirement of the entire project (manifesting itself as FSI) # then we find the solar yield of the entire project, this includes solar heat gain and PV potential as aggregated values (manifesting itself as collisisons per m2) import trimesh as tm import os import pyvista as pv import numpy as np import topogenesis as tg lattice_path = os.path.relpath("../data/voxelized_envelope.csv") occ_lattice = tg.lattice_from_csv(lattice_path) # the current occupation lattice path = os.path.relpath('../data/my_envelope.obj') # building outer boundaries file path buildingplot = tm.load(path) # load specified building boundary mesh (footprint extruded to max height, USER INPUT) base = buildingplot.apply_transform(tm.transformations.projection_matrix((0,0,0), (0,0,-1))) # project mesh on z plane to get footprint env_all_vox = occ_lattice.flatten() # flattened lattice of all possible positions, True is occupied, False is unoccupied FSI_min = 2.0 # current goal for the FSI, can be a variable # FSI DO: maybe it is faster to take footprint outside of the equation so it does not recompute the footprint everytime? def FSI(footprint, occupationlattice): # calculate FSI based on occupation lattice and mesh plot vox_size = occupationlattice.unit[0] m2_plot = footprint.area/2 # area calculates both sides of the flattened mesh, we need only 1 cell_count = [i for i in occupationlattice if i != False ] m2_total = vox_size**2*len(cell_count) FSI = m2_total/m2_plot return FSI def FSI_fast(floors, floor_percent=0.8): # calculate FSI based on floorcount, plot coverage of the floors m2_floor = floor_percent FSI = m2_floor*floors #FSI = m2_total/m2_plot return FSI # FSI(base,env_all_vox) FSI_fast(3) import trimesh as tm import os import pyvista as pv import numpy as np import topogenesis as tg lattice_path = os.path.relpath("../data/voxelized_envelope.csv") occ_lattice = tg.lattice_from_csv(lattice_path) # the current occupation lattice path = os.path.relpath('../data/my_envelope.obj') # building outer boundaries file path buildingplot = tm.load(path) # load specified building boundary mesh (footprint extruded to max height, USER INPUT) np.arange(9) ###Output _____no_output_____ ###Markdown Global decision variables - Aggregated Solar Score (ASS) (working title) (PV and heat gain)Inputs required:- Building mass (mesh or .obj) OR floorcount + roof area- Coordinates OR solar vectors (prepared) using Ladybug plugin- DO: check values for constants, check if it is needed iteratively or only global ###Code # this includes a. the PV potential (calculated by roof area over total floor area) # and b. the solar heat gain over the year (calculated by G-value/SHGC, window/wall ratio, solar heat gain coefficient of opaque components) # PV potential - how much roof area per m2 is available for installing PV def PV_fast(floors): # this gives ESTIMATED RATIO between floor area and PV area. Needs to be recomputed at the end of the local scale (or continuously calculated) DO: find out PV = 1/floors return PV # Annual solar energy output of PV is calculated as follows: # E(kwh) = A*r*H*PR where A = total solar panel area, r = solar panel yield/efficiency, H = Annual average solar radiation, PR = performance ratio # from: https://photovoltaic-software.com/principle-ressources/how-calculate-solar-energy-power-pv-systems r = 0.15 # yield/efficiency estimate H = 1050 # to be updated, currently wikipedia estimate. Slope, tilt, orientation may change values. kWh.y so maybe *365??? PR = 0.75 # default value, estimate def PV(occupationlattice): # an accurate value (kWh estimate) of the PV potential DO: change to only check for the added voxels of the current iteration? vox_size = occupationlattice.unit[0] cell_count = [ i for i in occupationlattice if i != False ] # change to only include voxels on the 'roof' A = len(cell_count)*vox_size # update to actual roof area E = A*r*H*PR # the estimated solar yield in kWh for the year return E PV(env_all_vox) # solar heat gain (windows only), include opaque surfaces? # Aggregated score ###Output _____no_output_____ ###Markdown Local cost/objective function - Energy usage (minimize)inputs required:- current floor area (per building unit type)- constant value (per building unit type) ###Code # skip for now, maybe skip permanently? --> too dependant on building (material) quality and not only on massing/envelope ###Output _____no_output_____
tasks/human_pose/pytorch_to_onnx_v2.ipynb
###Markdown First, let's load the JSON file which describes the human pose task. This is in COCO format, it is the category descriptor pulled from the annotations file. We modify the COCO category slightly, to add a neck keypoint. We will use this task description JSON to create a topology tensor, which is an intermediate data structure that describes the part linkages, as well as which channels in the part affinity field each linkage corresponds to. ###Code import json import trt_pose.coco with open('human_pose.json', 'r') as f: human_pose = json.load(f) topology = trt_pose.coco.coco_category_to_topology(human_pose) ###Output _____no_output_____ ###Markdown Next, we'll load our model. Each model takes at least two parameters, *cmap_channels* and *paf_channels* corresponding to the number of heatmap channelsand part affinity field channels. The number of part affinity field channels is 2x the number of links, because each link has a channel corresponding to thex and y direction of the vector field for each link. ###Code import trt_pose.models num_parts = len(human_pose['keypoints']) num_links = len(human_pose['skeleton']) # model = trt_pose.models.resnet18_baseline_att(num_parts, 2 * num_links, pretrained=False).cuda().eval() model = trt_pose.models.densenet121_baseline_att(num_parts, 2 * num_links, pretrained=False).cuda().eval() ###Output _____no_output_____ ###Markdown Next, let's load the model weights. You will need to download these according to the table in the README. ###Code import torch # MODEL_WEIGHTS = 'resnet18_baseline_att_224x224_A_epoch_249.pth' # ONNX_OUTPUT = 'resnet18_baseline_att_224x224_A_epoch_249.onnx' MODEL_WEIGHTS = 'densenet121_baseline_att_256x256_B_epoch_160.pth' ONNX_OUTPUT = 'densenet121_baseline_att_256x256_B_epoch_160.onnx' model.load_state_dict(torch.load(MODEL_WEIGHTS)) ###Output _____no_output_____ ###Markdown Convert a pytorch model to ONNX format ###Code # WIDTH = 224 # HEIGHT = 224 WIDTH = 256 HEIGHT = 256 data = torch.zeros((1, 3, HEIGHT, WIDTH)).cuda() torch_out = model(data) torch.onnx.export(model, data, ONNX_OUTPUT, export_params=True, opset_version=10, do_constant_folding=True ) ###Output _____no_output_____ ###Markdown Verify converted ONNX model ###Code import onnx onnx_model = onnx.load(ONNX_OUTPUT) onnx.checker.check_model(onnx_model) # Print a human readable representation of the graph print(onnx.helper.printable_graph(onnx_model.graph)) ###Output graph torch-jit-export ( %0[FLOAT, 1x3x256x256] ) optional inputs with matching initializers ( %0.densenet.features.conv0.weight[FLOAT, 64x3x7x7] %0.densenet.features.norm0.weight[FLOAT, 64] %0.densenet.features.norm0.bias[FLOAT, 64] %0.densenet.features.norm0.running_mean[FLOAT, 64] %0.densenet.features.norm0.running_var[FLOAT, 64] %0.densenet.features.norm0.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer1.norm1.weight[FLOAT, 64] %0.densenet.features.denseblock1.denselayer1.norm1.bias[FLOAT, 64] %0.densenet.features.denseblock1.denselayer1.norm1.running_mean[FLOAT, 64] %0.densenet.features.denseblock1.denselayer1.norm1.running_var[FLOAT, 64] %0.densenet.features.denseblock1.denselayer1.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer1.conv1.weight[FLOAT, 128x64x1x1] %0.densenet.features.denseblock1.denselayer1.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer1.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer1.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer1.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer1.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer1.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock1.denselayer2.norm1.weight[FLOAT, 96] %0.densenet.features.denseblock1.denselayer2.norm1.bias[FLOAT, 96] %0.densenet.features.denseblock1.denselayer2.norm1.running_mean[FLOAT, 96] %0.densenet.features.denseblock1.denselayer2.norm1.running_var[FLOAT, 96] %0.densenet.features.denseblock1.denselayer2.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer2.conv1.weight[FLOAT, 128x96x1x1] %0.densenet.features.denseblock1.denselayer2.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer2.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer2.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer2.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer2.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer2.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock1.denselayer3.norm1.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm1.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm1.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm1.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer3.conv1.weight[FLOAT, 128x128x1x1] %0.densenet.features.denseblock1.denselayer3.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer3.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer3.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock1.denselayer4.norm1.weight[FLOAT, 160] %0.densenet.features.denseblock1.denselayer4.norm1.bias[FLOAT, 160] %0.densenet.features.denseblock1.denselayer4.norm1.running_mean[FLOAT, 160] %0.densenet.features.denseblock1.denselayer4.norm1.running_var[FLOAT, 160] %0.densenet.features.denseblock1.denselayer4.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer4.conv1.weight[FLOAT, 128x160x1x1] %0.densenet.features.denseblock1.denselayer4.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer4.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer4.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer4.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer4.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer4.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock1.denselayer5.norm1.weight[FLOAT, 192] %0.densenet.features.denseblock1.denselayer5.norm1.bias[FLOAT, 192] %0.densenet.features.denseblock1.denselayer5.norm1.running_mean[FLOAT, 192] %0.densenet.features.denseblock1.denselayer5.norm1.running_var[FLOAT, 192] %0.densenet.features.denseblock1.denselayer5.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer5.conv1.weight[FLOAT, 128x192x1x1] %0.densenet.features.denseblock1.denselayer5.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer5.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer5.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer5.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer5.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer5.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock1.denselayer6.norm1.weight[FLOAT, 224] %0.densenet.features.denseblock1.denselayer6.norm1.bias[FLOAT, 224] %0.densenet.features.denseblock1.denselayer6.norm1.running_mean[FLOAT, 224] %0.densenet.features.denseblock1.denselayer6.norm1.running_var[FLOAT, 224] %0.densenet.features.denseblock1.denselayer6.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer6.conv1.weight[FLOAT, 128x224x1x1] %0.densenet.features.denseblock1.denselayer6.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock1.denselayer6.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock1.denselayer6.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock1.denselayer6.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock1.denselayer6.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock1.denselayer6.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.transition1.norm.weight[FLOAT, 256] %0.densenet.features.transition1.norm.bias[FLOAT, 256] %0.densenet.features.transition1.norm.running_mean[FLOAT, 256] %0.densenet.features.transition1.norm.running_var[FLOAT, 256] %0.densenet.features.transition1.norm.num_batches_tracked[INT64, scalar] %0.densenet.features.transition1.conv.weight[FLOAT, 128x256x1x1] %0.densenet.features.denseblock2.denselayer1.norm1.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm1.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm1.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm1.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer1.conv1.weight[FLOAT, 128x128x1x1] %0.densenet.features.denseblock2.denselayer1.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer1.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer1.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer2.norm1.weight[FLOAT, 160] %0.densenet.features.denseblock2.denselayer2.norm1.bias[FLOAT, 160] %0.densenet.features.denseblock2.denselayer2.norm1.running_mean[FLOAT, 160] %0.densenet.features.denseblock2.denselayer2.norm1.running_var[FLOAT, 160] %0.densenet.features.denseblock2.denselayer2.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer2.conv1.weight[FLOAT, 128x160x1x1] %0.densenet.features.denseblock2.denselayer2.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer2.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer2.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer2.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer2.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer2.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer3.norm1.weight[FLOAT, 192] %0.densenet.features.denseblock2.denselayer3.norm1.bias[FLOAT, 192] %0.densenet.features.denseblock2.denselayer3.norm1.running_mean[FLOAT, 192] %0.densenet.features.denseblock2.denselayer3.norm1.running_var[FLOAT, 192] %0.densenet.features.denseblock2.denselayer3.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer3.conv1.weight[FLOAT, 128x192x1x1] %0.densenet.features.denseblock2.denselayer3.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer3.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer3.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer3.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer3.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer3.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer4.norm1.weight[FLOAT, 224] %0.densenet.features.denseblock2.denselayer4.norm1.bias[FLOAT, 224] %0.densenet.features.denseblock2.denselayer4.norm1.running_mean[FLOAT, 224] %0.densenet.features.denseblock2.denselayer4.norm1.running_var[FLOAT, 224] %0.densenet.features.denseblock2.denselayer4.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer4.conv1.weight[FLOAT, 128x224x1x1] %0.densenet.features.denseblock2.denselayer4.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer4.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer4.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer4.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer4.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer4.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer5.norm1.weight[FLOAT, 256] %0.densenet.features.denseblock2.denselayer5.norm1.bias[FLOAT, 256] %0.densenet.features.denseblock2.denselayer5.norm1.running_mean[FLOAT, 256] %0.densenet.features.denseblock2.denselayer5.norm1.running_var[FLOAT, 256] %0.densenet.features.denseblock2.denselayer5.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer5.conv1.weight[FLOAT, 128x256x1x1] %0.densenet.features.denseblock2.denselayer5.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer5.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer5.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer5.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer5.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer5.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer6.norm1.weight[FLOAT, 288] %0.densenet.features.denseblock2.denselayer6.norm1.bias[FLOAT, 288] %0.densenet.features.denseblock2.denselayer6.norm1.running_mean[FLOAT, 288] %0.densenet.features.denseblock2.denselayer6.norm1.running_var[FLOAT, 288] %0.densenet.features.denseblock2.denselayer6.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer6.conv1.weight[FLOAT, 128x288x1x1] %0.densenet.features.denseblock2.denselayer6.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer6.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer6.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer6.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer6.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer6.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer7.norm1.weight[FLOAT, 320] %0.densenet.features.denseblock2.denselayer7.norm1.bias[FLOAT, 320] %0.densenet.features.denseblock2.denselayer7.norm1.running_mean[FLOAT, 320] %0.densenet.features.denseblock2.denselayer7.norm1.running_var[FLOAT, 320] %0.densenet.features.denseblock2.denselayer7.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer7.conv1.weight[FLOAT, 128x320x1x1] %0.densenet.features.denseblock2.denselayer7.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer7.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer7.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer7.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer7.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer7.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer8.norm1.weight[FLOAT, 352] %0.densenet.features.denseblock2.denselayer8.norm1.bias[FLOAT, 352] %0.densenet.features.denseblock2.denselayer8.norm1.running_mean[FLOAT, 352] %0.densenet.features.denseblock2.denselayer8.norm1.running_var[FLOAT, 352] %0.densenet.features.denseblock2.denselayer8.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer8.conv1.weight[FLOAT, 128x352x1x1] %0.densenet.features.denseblock2.denselayer8.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer8.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer8.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer8.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer8.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer8.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer9.norm1.weight[FLOAT, 384] %0.densenet.features.denseblock2.denselayer9.norm1.bias[FLOAT, 384] %0.densenet.features.denseblock2.denselayer9.norm1.running_mean[FLOAT, 384] %0.densenet.features.denseblock2.denselayer9.norm1.running_var[FLOAT, 384] %0.densenet.features.denseblock2.denselayer9.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer9.conv1.weight[FLOAT, 128x384x1x1] %0.densenet.features.denseblock2.denselayer9.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer9.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer9.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer9.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer9.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer9.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer10.norm1.weight[FLOAT, 416] %0.densenet.features.denseblock2.denselayer10.norm1.bias[FLOAT, 416] %0.densenet.features.denseblock2.denselayer10.norm1.running_mean[FLOAT, 416] %0.densenet.features.denseblock2.denselayer10.norm1.running_var[FLOAT, 416] %0.densenet.features.denseblock2.denselayer10.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer10.conv1.weight[FLOAT, 128x416x1x1] %0.densenet.features.denseblock2.denselayer10.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer10.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer10.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer10.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer10.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer10.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer11.norm1.weight[FLOAT, 448] %0.densenet.features.denseblock2.denselayer11.norm1.bias[FLOAT, 448] %0.densenet.features.denseblock2.denselayer11.norm1.running_mean[FLOAT, 448] %0.densenet.features.denseblock2.denselayer11.norm1.running_var[FLOAT, 448] %0.densenet.features.denseblock2.denselayer11.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer11.conv1.weight[FLOAT, 128x448x1x1] %0.densenet.features.denseblock2.denselayer11.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer11.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer11.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer11.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer11.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer11.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock2.denselayer12.norm1.weight[FLOAT, 480] %0.densenet.features.denseblock2.denselayer12.norm1.bias[FLOAT, 480] %0.densenet.features.denseblock2.denselayer12.norm1.running_mean[FLOAT, 480] %0.densenet.features.denseblock2.denselayer12.norm1.running_var[FLOAT, 480] %0.densenet.features.denseblock2.denselayer12.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer12.conv1.weight[FLOAT, 128x480x1x1] %0.densenet.features.denseblock2.denselayer12.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock2.denselayer12.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock2.denselayer12.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock2.denselayer12.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock2.denselayer12.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock2.denselayer12.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.transition2.norm.weight[FLOAT, 512] %0.densenet.features.transition2.norm.bias[FLOAT, 512] %0.densenet.features.transition2.norm.running_mean[FLOAT, 512] %0.densenet.features.transition2.norm.running_var[FLOAT, 512] %0.densenet.features.transition2.norm.num_batches_tracked[INT64, scalar] %0.densenet.features.transition2.conv.weight[FLOAT, 256x512x1x1] %0.densenet.features.denseblock3.denselayer1.norm1.weight[FLOAT, 256] %0.densenet.features.denseblock3.denselayer1.norm1.bias[FLOAT, 256] %0.densenet.features.denseblock3.denselayer1.norm1.running_mean[FLOAT, 256] %0.densenet.features.denseblock3.denselayer1.norm1.running_var[FLOAT, 256] %0.densenet.features.denseblock3.denselayer1.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer1.conv1.weight[FLOAT, 128x256x1x1] %0.densenet.features.denseblock3.denselayer1.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer1.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer1.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer1.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer1.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer1.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer2.norm1.weight[FLOAT, 288] %0.densenet.features.denseblock3.denselayer2.norm1.bias[FLOAT, 288] %0.densenet.features.denseblock3.denselayer2.norm1.running_mean[FLOAT, 288] %0.densenet.features.denseblock3.denselayer2.norm1.running_var[FLOAT, 288] %0.densenet.features.denseblock3.denselayer2.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer2.conv1.weight[FLOAT, 128x288x1x1] %0.densenet.features.denseblock3.denselayer2.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer2.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer2.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer2.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer2.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer2.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer3.norm1.weight[FLOAT, 320] %0.densenet.features.denseblock3.denselayer3.norm1.bias[FLOAT, 320] %0.densenet.features.denseblock3.denselayer3.norm1.running_mean[FLOAT, 320] %0.densenet.features.denseblock3.denselayer3.norm1.running_var[FLOAT, 320] %0.densenet.features.denseblock3.denselayer3.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer3.conv1.weight[FLOAT, 128x320x1x1] %0.densenet.features.denseblock3.denselayer3.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer3.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer3.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer3.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer3.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer3.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer4.norm1.weight[FLOAT, 352] %0.densenet.features.denseblock3.denselayer4.norm1.bias[FLOAT, 352] %0.densenet.features.denseblock3.denselayer4.norm1.running_mean[FLOAT, 352] %0.densenet.features.denseblock3.denselayer4.norm1.running_var[FLOAT, 352] %0.densenet.features.denseblock3.denselayer4.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer4.conv1.weight[FLOAT, 128x352x1x1] %0.densenet.features.denseblock3.denselayer4.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer4.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer4.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer4.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer4.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer4.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer5.norm1.weight[FLOAT, 384] %0.densenet.features.denseblock3.denselayer5.norm1.bias[FLOAT, 384] %0.densenet.features.denseblock3.denselayer5.norm1.running_mean[FLOAT, 384] %0.densenet.features.denseblock3.denselayer5.norm1.running_var[FLOAT, 384] %0.densenet.features.denseblock3.denselayer5.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer5.conv1.weight[FLOAT, 128x384x1x1] %0.densenet.features.denseblock3.denselayer5.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer5.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer5.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer5.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer5.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer5.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer6.norm1.weight[FLOAT, 416] %0.densenet.features.denseblock3.denselayer6.norm1.bias[FLOAT, 416] %0.densenet.features.denseblock3.denselayer6.norm1.running_mean[FLOAT, 416] %0.densenet.features.denseblock3.denselayer6.norm1.running_var[FLOAT, 416] %0.densenet.features.denseblock3.denselayer6.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer6.conv1.weight[FLOAT, 128x416x1x1] %0.densenet.features.denseblock3.denselayer6.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer6.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer6.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer6.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer6.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer6.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer7.norm1.weight[FLOAT, 448] %0.densenet.features.denseblock3.denselayer7.norm1.bias[FLOAT, 448] %0.densenet.features.denseblock3.denselayer7.norm1.running_mean[FLOAT, 448] %0.densenet.features.denseblock3.denselayer7.norm1.running_var[FLOAT, 448] %0.densenet.features.denseblock3.denselayer7.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer7.conv1.weight[FLOAT, 128x448x1x1] %0.densenet.features.denseblock3.denselayer7.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer7.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer7.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer7.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer7.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer7.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer8.norm1.weight[FLOAT, 480] %0.densenet.features.denseblock3.denselayer8.norm1.bias[FLOAT, 480] %0.densenet.features.denseblock3.denselayer8.norm1.running_mean[FLOAT, 480] %0.densenet.features.denseblock3.denselayer8.norm1.running_var[FLOAT, 480] %0.densenet.features.denseblock3.denselayer8.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer8.conv1.weight[FLOAT, 128x480x1x1] %0.densenet.features.denseblock3.denselayer8.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer8.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer8.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer8.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer8.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer8.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer9.norm1.weight[FLOAT, 512] %0.densenet.features.denseblock3.denselayer9.norm1.bias[FLOAT, 512] %0.densenet.features.denseblock3.denselayer9.norm1.running_mean[FLOAT, 512] %0.densenet.features.denseblock3.denselayer9.norm1.running_var[FLOAT, 512] %0.densenet.features.denseblock3.denselayer9.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer9.conv1.weight[FLOAT, 128x512x1x1] %0.densenet.features.denseblock3.denselayer9.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer9.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer9.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer9.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer9.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer9.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer10.norm1.weight[FLOAT, 544] %0.densenet.features.denseblock3.denselayer10.norm1.bias[FLOAT, 544] %0.densenet.features.denseblock3.denselayer10.norm1.running_mean[FLOAT, 544] %0.densenet.features.denseblock3.denselayer10.norm1.running_var[FLOAT, 544] %0.densenet.features.denseblock3.denselayer10.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer10.conv1.weight[FLOAT, 128x544x1x1] %0.densenet.features.denseblock3.denselayer10.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer10.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer10.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer10.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer10.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer10.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer11.norm1.weight[FLOAT, 576] %0.densenet.features.denseblock3.denselayer11.norm1.bias[FLOAT, 576] %0.densenet.features.denseblock3.denselayer11.norm1.running_mean[FLOAT, 576] %0.densenet.features.denseblock3.denselayer11.norm1.running_var[FLOAT, 576] %0.densenet.features.denseblock3.denselayer11.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer11.conv1.weight[FLOAT, 128x576x1x1] %0.densenet.features.denseblock3.denselayer11.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer11.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer11.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer11.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer11.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer11.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer12.norm1.weight[FLOAT, 608] %0.densenet.features.denseblock3.denselayer12.norm1.bias[FLOAT, 608] %0.densenet.features.denseblock3.denselayer12.norm1.running_mean[FLOAT, 608] %0.densenet.features.denseblock3.denselayer12.norm1.running_var[FLOAT, 608] %0.densenet.features.denseblock3.denselayer12.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer12.conv1.weight[FLOAT, 128x608x1x1] %0.densenet.features.denseblock3.denselayer12.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer12.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer12.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer12.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer12.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer12.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer13.norm1.weight[FLOAT, 640] %0.densenet.features.denseblock3.denselayer13.norm1.bias[FLOAT, 640] %0.densenet.features.denseblock3.denselayer13.norm1.running_mean[FLOAT, 640] %0.densenet.features.denseblock3.denselayer13.norm1.running_var[FLOAT, 640] %0.densenet.features.denseblock3.denselayer13.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer13.conv1.weight[FLOAT, 128x640x1x1] %0.densenet.features.denseblock3.denselayer13.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer13.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer13.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer13.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer13.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer13.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer14.norm1.weight[FLOAT, 672] %0.densenet.features.denseblock3.denselayer14.norm1.bias[FLOAT, 672] %0.densenet.features.denseblock3.denselayer14.norm1.running_mean[FLOAT, 672] %0.densenet.features.denseblock3.denselayer14.norm1.running_var[FLOAT, 672] %0.densenet.features.denseblock3.denselayer14.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer14.conv1.weight[FLOAT, 128x672x1x1] %0.densenet.features.denseblock3.denselayer14.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer14.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer14.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer14.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer14.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer14.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer15.norm1.weight[FLOAT, 704] %0.densenet.features.denseblock3.denselayer15.norm1.bias[FLOAT, 704] %0.densenet.features.denseblock3.denselayer15.norm1.running_mean[FLOAT, 704] %0.densenet.features.denseblock3.denselayer15.norm1.running_var[FLOAT, 704] %0.densenet.features.denseblock3.denselayer15.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer15.conv1.weight[FLOAT, 128x704x1x1] %0.densenet.features.denseblock3.denselayer15.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer15.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer15.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer15.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer15.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer15.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer16.norm1.weight[FLOAT, 736] %0.densenet.features.denseblock3.denselayer16.norm1.bias[FLOAT, 736] %0.densenet.features.denseblock3.denselayer16.norm1.running_mean[FLOAT, 736] %0.densenet.features.denseblock3.denselayer16.norm1.running_var[FLOAT, 736] %0.densenet.features.denseblock3.denselayer16.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer16.conv1.weight[FLOAT, 128x736x1x1] %0.densenet.features.denseblock3.denselayer16.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer16.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer16.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer16.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer16.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer16.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer17.norm1.weight[FLOAT, 768] %0.densenet.features.denseblock3.denselayer17.norm1.bias[FLOAT, 768] %0.densenet.features.denseblock3.denselayer17.norm1.running_mean[FLOAT, 768] %0.densenet.features.denseblock3.denselayer17.norm1.running_var[FLOAT, 768] %0.densenet.features.denseblock3.denselayer17.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer17.conv1.weight[FLOAT, 128x768x1x1] %0.densenet.features.denseblock3.denselayer17.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer17.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer17.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer17.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer17.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer17.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer18.norm1.weight[FLOAT, 800] %0.densenet.features.denseblock3.denselayer18.norm1.bias[FLOAT, 800] %0.densenet.features.denseblock3.denselayer18.norm1.running_mean[FLOAT, 800] %0.densenet.features.denseblock3.denselayer18.norm1.running_var[FLOAT, 800] %0.densenet.features.denseblock3.denselayer18.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer18.conv1.weight[FLOAT, 128x800x1x1] %0.densenet.features.denseblock3.denselayer18.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer18.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer18.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer18.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer18.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer18.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer19.norm1.weight[FLOAT, 832] %0.densenet.features.denseblock3.denselayer19.norm1.bias[FLOAT, 832] %0.densenet.features.denseblock3.denselayer19.norm1.running_mean[FLOAT, 832] %0.densenet.features.denseblock3.denselayer19.norm1.running_var[FLOAT, 832] %0.densenet.features.denseblock3.denselayer19.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer19.conv1.weight[FLOAT, 128x832x1x1] %0.densenet.features.denseblock3.denselayer19.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer19.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer19.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer19.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer19.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer19.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer20.norm1.weight[FLOAT, 864] %0.densenet.features.denseblock3.denselayer20.norm1.bias[FLOAT, 864] %0.densenet.features.denseblock3.denselayer20.norm1.running_mean[FLOAT, 864] %0.densenet.features.denseblock3.denselayer20.norm1.running_var[FLOAT, 864] %0.densenet.features.denseblock3.denselayer20.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer20.conv1.weight[FLOAT, 128x864x1x1] %0.densenet.features.denseblock3.denselayer20.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer20.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer20.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer20.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer20.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer20.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer21.norm1.weight[FLOAT, 896] %0.densenet.features.denseblock3.denselayer21.norm1.bias[FLOAT, 896] %0.densenet.features.denseblock3.denselayer21.norm1.running_mean[FLOAT, 896] %0.densenet.features.denseblock3.denselayer21.norm1.running_var[FLOAT, 896] %0.densenet.features.denseblock3.denselayer21.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer21.conv1.weight[FLOAT, 128x896x1x1] %0.densenet.features.denseblock3.denselayer21.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer21.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer21.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer21.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer21.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer21.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer22.norm1.weight[FLOAT, 928] %0.densenet.features.denseblock3.denselayer22.norm1.bias[FLOAT, 928] %0.densenet.features.denseblock3.denselayer22.norm1.running_mean[FLOAT, 928] %0.densenet.features.denseblock3.denselayer22.norm1.running_var[FLOAT, 928] %0.densenet.features.denseblock3.denselayer22.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer22.conv1.weight[FLOAT, 128x928x1x1] %0.densenet.features.denseblock3.denselayer22.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer22.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer22.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer22.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer22.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer22.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer23.norm1.weight[FLOAT, 960] %0.densenet.features.denseblock3.denselayer23.norm1.bias[FLOAT, 960] %0.densenet.features.denseblock3.denselayer23.norm1.running_mean[FLOAT, 960] %0.densenet.features.denseblock3.denselayer23.norm1.running_var[FLOAT, 960] %0.densenet.features.denseblock3.denselayer23.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer23.conv1.weight[FLOAT, 128x960x1x1] %0.densenet.features.denseblock3.denselayer23.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer23.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer23.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer23.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer23.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer23.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock3.denselayer24.norm1.weight[FLOAT, 992] %0.densenet.features.denseblock3.denselayer24.norm1.bias[FLOAT, 992] %0.densenet.features.denseblock3.denselayer24.norm1.running_mean[FLOAT, 992] %0.densenet.features.denseblock3.denselayer24.norm1.running_var[FLOAT, 992] %0.densenet.features.denseblock3.denselayer24.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer24.conv1.weight[FLOAT, 128x992x1x1] %0.densenet.features.denseblock3.denselayer24.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock3.denselayer24.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock3.denselayer24.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock3.denselayer24.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock3.denselayer24.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock3.denselayer24.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.transition3.norm.weight[FLOAT, 1024] %0.densenet.features.transition3.norm.bias[FLOAT, 1024] %0.densenet.features.transition3.norm.running_mean[FLOAT, 1024] %0.densenet.features.transition3.norm.running_var[FLOAT, 1024] %0.densenet.features.transition3.norm.num_batches_tracked[INT64, scalar] %0.densenet.features.transition3.conv.weight[FLOAT, 512x1024x1x1] %0.densenet.features.denseblock4.denselayer1.norm1.weight[FLOAT, 512] %0.densenet.features.denseblock4.denselayer1.norm1.bias[FLOAT, 512] %0.densenet.features.denseblock4.denselayer1.norm1.running_mean[FLOAT, 512] %0.densenet.features.denseblock4.denselayer1.norm1.running_var[FLOAT, 512] %0.densenet.features.denseblock4.denselayer1.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer1.conv1.weight[FLOAT, 128x512x1x1] %0.densenet.features.denseblock4.denselayer1.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer1.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer1.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer1.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer1.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer1.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer2.norm1.weight[FLOAT, 544] %0.densenet.features.denseblock4.denselayer2.norm1.bias[FLOAT, 544] %0.densenet.features.denseblock4.denselayer2.norm1.running_mean[FLOAT, 544] %0.densenet.features.denseblock4.denselayer2.norm1.running_var[FLOAT, 544] %0.densenet.features.denseblock4.denselayer2.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer2.conv1.weight[FLOAT, 128x544x1x1] %0.densenet.features.denseblock4.denselayer2.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer2.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer2.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer2.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer2.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer2.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer3.norm1.weight[FLOAT, 576] %0.densenet.features.denseblock4.denselayer3.norm1.bias[FLOAT, 576] %0.densenet.features.denseblock4.denselayer3.norm1.running_mean[FLOAT, 576] %0.densenet.features.denseblock4.denselayer3.norm1.running_var[FLOAT, 576] %0.densenet.features.denseblock4.denselayer3.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer3.conv1.weight[FLOAT, 128x576x1x1] %0.densenet.features.denseblock4.denselayer3.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer3.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer3.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer3.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer3.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer3.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer4.norm1.weight[FLOAT, 608] %0.densenet.features.denseblock4.denselayer4.norm1.bias[FLOAT, 608] %0.densenet.features.denseblock4.denselayer4.norm1.running_mean[FLOAT, 608] %0.densenet.features.denseblock4.denselayer4.norm1.running_var[FLOAT, 608] %0.densenet.features.denseblock4.denselayer4.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer4.conv1.weight[FLOAT, 128x608x1x1] %0.densenet.features.denseblock4.denselayer4.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer4.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer4.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer4.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer4.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer4.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer5.norm1.weight[FLOAT, 640] %0.densenet.features.denseblock4.denselayer5.norm1.bias[FLOAT, 640] %0.densenet.features.denseblock4.denselayer5.norm1.running_mean[FLOAT, 640] %0.densenet.features.denseblock4.denselayer5.norm1.running_var[FLOAT, 640] %0.densenet.features.denseblock4.denselayer5.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer5.conv1.weight[FLOAT, 128x640x1x1] %0.densenet.features.denseblock4.denselayer5.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer5.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer5.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer5.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer5.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer5.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer6.norm1.weight[FLOAT, 672] %0.densenet.features.denseblock4.denselayer6.norm1.bias[FLOAT, 672] %0.densenet.features.denseblock4.denselayer6.norm1.running_mean[FLOAT, 672] %0.densenet.features.denseblock4.denselayer6.norm1.running_var[FLOAT, 672] %0.densenet.features.denseblock4.denselayer6.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer6.conv1.weight[FLOAT, 128x672x1x1] %0.densenet.features.denseblock4.denselayer6.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer6.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer6.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer6.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer6.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer6.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer7.norm1.weight[FLOAT, 704] %0.densenet.features.denseblock4.denselayer7.norm1.bias[FLOAT, 704] %0.densenet.features.denseblock4.denselayer7.norm1.running_mean[FLOAT, 704] %0.densenet.features.denseblock4.denselayer7.norm1.running_var[FLOAT, 704] %0.densenet.features.denseblock4.denselayer7.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer7.conv1.weight[FLOAT, 128x704x1x1] %0.densenet.features.denseblock4.denselayer7.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer7.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer7.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer7.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer7.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer7.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer8.norm1.weight[FLOAT, 736] %0.densenet.features.denseblock4.denselayer8.norm1.bias[FLOAT, 736] %0.densenet.features.denseblock4.denselayer8.norm1.running_mean[FLOAT, 736] %0.densenet.features.denseblock4.denselayer8.norm1.running_var[FLOAT, 736] %0.densenet.features.denseblock4.denselayer8.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer8.conv1.weight[FLOAT, 128x736x1x1] %0.densenet.features.denseblock4.denselayer8.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer8.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer8.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer8.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer8.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer8.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer9.norm1.weight[FLOAT, 768] %0.densenet.features.denseblock4.denselayer9.norm1.bias[FLOAT, 768] %0.densenet.features.denseblock4.denselayer9.norm1.running_mean[FLOAT, 768] %0.densenet.features.denseblock4.denselayer9.norm1.running_var[FLOAT, 768] %0.densenet.features.denseblock4.denselayer9.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer9.conv1.weight[FLOAT, 128x768x1x1] %0.densenet.features.denseblock4.denselayer9.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer9.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer9.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer9.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer9.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer9.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer10.norm1.weight[FLOAT, 800] %0.densenet.features.denseblock4.denselayer10.norm1.bias[FLOAT, 800] %0.densenet.features.denseblock4.denselayer10.norm1.running_mean[FLOAT, 800] %0.densenet.features.denseblock4.denselayer10.norm1.running_var[FLOAT, 800] %0.densenet.features.denseblock4.denselayer10.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer10.conv1.weight[FLOAT, 128x800x1x1] %0.densenet.features.denseblock4.denselayer10.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer10.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer10.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer10.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer10.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer10.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer11.norm1.weight[FLOAT, 832] %0.densenet.features.denseblock4.denselayer11.norm1.bias[FLOAT, 832] %0.densenet.features.denseblock4.denselayer11.norm1.running_mean[FLOAT, 832] %0.densenet.features.denseblock4.denselayer11.norm1.running_var[FLOAT, 832] %0.densenet.features.denseblock4.denselayer11.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer11.conv1.weight[FLOAT, 128x832x1x1] %0.densenet.features.denseblock4.denselayer11.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer11.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer11.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer11.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer11.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer11.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer12.norm1.weight[FLOAT, 864] %0.densenet.features.denseblock4.denselayer12.norm1.bias[FLOAT, 864] %0.densenet.features.denseblock4.denselayer12.norm1.running_mean[FLOAT, 864] %0.densenet.features.denseblock4.denselayer12.norm1.running_var[FLOAT, 864] %0.densenet.features.denseblock4.denselayer12.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer12.conv1.weight[FLOAT, 128x864x1x1] %0.densenet.features.denseblock4.denselayer12.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer12.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer12.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer12.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer12.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer12.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer13.norm1.weight[FLOAT, 896] %0.densenet.features.denseblock4.denselayer13.norm1.bias[FLOAT, 896] %0.densenet.features.denseblock4.denselayer13.norm1.running_mean[FLOAT, 896] %0.densenet.features.denseblock4.denselayer13.norm1.running_var[FLOAT, 896] %0.densenet.features.denseblock4.denselayer13.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer13.conv1.weight[FLOAT, 128x896x1x1] %0.densenet.features.denseblock4.denselayer13.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer13.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer13.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer13.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer13.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer13.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer14.norm1.weight[FLOAT, 928] %0.densenet.features.denseblock4.denselayer14.norm1.bias[FLOAT, 928] %0.densenet.features.denseblock4.denselayer14.norm1.running_mean[FLOAT, 928] %0.densenet.features.denseblock4.denselayer14.norm1.running_var[FLOAT, 928] %0.densenet.features.denseblock4.denselayer14.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer14.conv1.weight[FLOAT, 128x928x1x1] %0.densenet.features.denseblock4.denselayer14.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer14.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer14.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer14.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer14.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer14.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer15.norm1.weight[FLOAT, 960] %0.densenet.features.denseblock4.denselayer15.norm1.bias[FLOAT, 960] %0.densenet.features.denseblock4.denselayer15.norm1.running_mean[FLOAT, 960] %0.densenet.features.denseblock4.denselayer15.norm1.running_var[FLOAT, 960] %0.densenet.features.denseblock4.denselayer15.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer15.conv1.weight[FLOAT, 128x960x1x1] %0.densenet.features.denseblock4.denselayer15.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer15.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer15.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer15.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer15.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer15.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.denseblock4.denselayer16.norm1.weight[FLOAT, 992] %0.densenet.features.denseblock4.denselayer16.norm1.bias[FLOAT, 992] %0.densenet.features.denseblock4.denselayer16.norm1.running_mean[FLOAT, 992] %0.densenet.features.denseblock4.denselayer16.norm1.running_var[FLOAT, 992] %0.densenet.features.denseblock4.denselayer16.norm1.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer16.conv1.weight[FLOAT, 128x992x1x1] %0.densenet.features.denseblock4.denselayer16.norm2.weight[FLOAT, 128] %0.densenet.features.denseblock4.denselayer16.norm2.bias[FLOAT, 128] %0.densenet.features.denseblock4.denselayer16.norm2.running_mean[FLOAT, 128] %0.densenet.features.denseblock4.denselayer16.norm2.running_var[FLOAT, 128] %0.densenet.features.denseblock4.denselayer16.norm2.num_batches_tracked[INT64, scalar] %0.densenet.features.denseblock4.denselayer16.conv2.weight[FLOAT, 32x128x3x3] %0.densenet.features.norm5.weight[FLOAT, 1024] %0.densenet.features.norm5.bias[FLOAT, 1024] %0.densenet.features.norm5.running_mean[FLOAT, 1024] %0.densenet.features.norm5.running_var[FLOAT, 1024] %0.densenet.features.norm5.num_batches_tracked[INT64, scalar] %0.densenet.classifier.weight[FLOAT, 1000x1024] %0.densenet.classifier.bias[FLOAT, 1000] %1.cmap_up.0.weight[FLOAT, 1024x256x4x4] %1.cmap_up.0.bias[FLOAT, 256] %1.cmap_up.1.weight[FLOAT, 256] %1.cmap_up.1.bias[FLOAT, 256] %1.cmap_up.1.running_mean[FLOAT, 256] %1.cmap_up.1.running_var[FLOAT, 256] %1.cmap_up.1.num_batches_tracked[INT64, scalar] %1.cmap_up.3.weight[FLOAT, 256x256x4x4] %1.cmap_up.3.bias[FLOAT, 256] %1.cmap_up.4.weight[FLOAT, 256] %1.cmap_up.4.bias[FLOAT, 256] %1.cmap_up.4.running_mean[FLOAT, 256] %1.cmap_up.4.running_var[FLOAT, 256] %1.cmap_up.4.num_batches_tracked[INT64, scalar] %1.cmap_up.6.weight[FLOAT, 256x256x4x4] %1.cmap_up.6.bias[FLOAT, 256] %1.cmap_up.7.weight[FLOAT, 256] %1.cmap_up.7.bias[FLOAT, 256] %1.cmap_up.7.running_mean[FLOAT, 256] %1.cmap_up.7.running_var[FLOAT, 256] %1.cmap_up.7.num_batches_tracked[INT64, scalar] %1.paf_up.0.weight[FLOAT, 1024x256x4x4] %1.paf_up.0.bias[FLOAT, 256] %1.paf_up.1.weight[FLOAT, 256] %1.paf_up.1.bias[FLOAT, 256] %1.paf_up.1.running_mean[FLOAT, 256] %1.paf_up.1.running_var[FLOAT, 256] %1.paf_up.1.num_batches_tracked[INT64, scalar] %1.paf_up.3.weight[FLOAT, 256x256x4x4] %1.paf_up.3.bias[FLOAT, 256] %1.paf_up.4.weight[FLOAT, 256] %1.paf_up.4.bias[FLOAT, 256] %1.paf_up.4.running_mean[FLOAT, 256] %1.paf_up.4.running_var[FLOAT, 256] %1.paf_up.4.num_batches_tracked[INT64, scalar] %1.paf_up.6.weight[FLOAT, 256x256x4x4] %1.paf_up.6.bias[FLOAT, 256] %1.paf_up.7.weight[FLOAT, 256] %1.paf_up.7.bias[FLOAT, 256] %1.paf_up.7.running_mean[FLOAT, 256] %1.paf_up.7.running_var[FLOAT, 256] %1.paf_up.7.num_batches_tracked[INT64, scalar] %1.cmap_att.weight[FLOAT, 256x256x3x3] %1.cmap_att.bias[FLOAT, 256] %1.paf_att.weight[FLOAT, 256x256x3x3] %1.paf_att.bias[FLOAT, 256] %1.cmap_conv.weight[FLOAT, 18x256x1x1] %1.cmap_conv.bias[FLOAT, 18] %1.paf_conv.weight[FLOAT, 42x256x1x1] %1.paf_conv.bias[FLOAT, 42] ) { %778 = Conv[dilations = [1, 1], group = 1, kernel_shape = [7, 7], pads = [3, 3, 3, 3], strides = [2, 2]](%0, %0.densenet.features.conv0.weight) %779 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%778, %0.densenet.features.norm0.weight, %0.densenet.features.norm0.bias, %0.densenet.features.norm0.running_mean, %0.densenet.features.norm0.running_var) %780 = Relu(%779) %781 = MaxPool[kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [2, 2]](%780) %782 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%781, %0.densenet.features.denseblock1.denselayer1.norm1.weight, %0.densenet.features.denseblock1.denselayer1.norm1.bias, %0.densenet.features.denseblock1.denselayer1.norm1.running_mean, %0.densenet.features.denseblock1.denselayer1.norm1.running_var) %783 = Relu(%782) %784 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%783, %0.densenet.features.denseblock1.denselayer1.conv1.weight) %785 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%784, %0.densenet.features.denseblock1.denselayer1.norm2.weight, %0.densenet.features.denseblock1.denselayer1.norm2.bias, %0.densenet.features.denseblock1.denselayer1.norm2.running_mean, %0.densenet.features.denseblock1.denselayer1.norm2.running_var) %786 = Relu(%785) %787 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%786, %0.densenet.features.denseblock1.denselayer1.conv2.weight) %788 = Concat[axis = 1](%781, %787) %789 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%788, %0.densenet.features.denseblock1.denselayer2.norm1.weight, %0.densenet.features.denseblock1.denselayer2.norm1.bias, %0.densenet.features.denseblock1.denselayer2.norm1.running_mean, %0.densenet.features.denseblock1.denselayer2.norm1.running_var) %790 = Relu(%789) %791 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%790, %0.densenet.features.denseblock1.denselayer2.conv1.weight) %792 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%791, %0.densenet.features.denseblock1.denselayer2.norm2.weight, %0.densenet.features.denseblock1.denselayer2.norm2.bias, %0.densenet.features.denseblock1.denselayer2.norm2.running_mean, %0.densenet.features.denseblock1.denselayer2.norm2.running_var) %793 = Relu(%792) %794 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%793, %0.densenet.features.denseblock1.denselayer2.conv2.weight) %795 = Concat[axis = 1](%788, %794) %796 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%795, %0.densenet.features.denseblock1.denselayer3.norm1.weight, %0.densenet.features.denseblock1.denselayer3.norm1.bias, %0.densenet.features.denseblock1.denselayer3.norm1.running_mean, %0.densenet.features.denseblock1.denselayer3.norm1.running_var) %797 = Relu(%796) %798 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%797, %0.densenet.features.denseblock1.denselayer3.conv1.weight) %799 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%798, %0.densenet.features.denseblock1.denselayer3.norm2.weight, %0.densenet.features.denseblock1.denselayer3.norm2.bias, %0.densenet.features.denseblock1.denselayer3.norm2.running_mean, %0.densenet.features.denseblock1.denselayer3.norm2.running_var) %800 = Relu(%799) %801 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%800, %0.densenet.features.denseblock1.denselayer3.conv2.weight) %802 = Concat[axis = 1](%795, %801) %803 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%802, %0.densenet.features.denseblock1.denselayer4.norm1.weight, %0.densenet.features.denseblock1.denselayer4.norm1.bias, %0.densenet.features.denseblock1.denselayer4.norm1.running_mean, %0.densenet.features.denseblock1.denselayer4.norm1.running_var) %804 = Relu(%803) %805 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%804, %0.densenet.features.denseblock1.denselayer4.conv1.weight) %806 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%805, %0.densenet.features.denseblock1.denselayer4.norm2.weight, %0.densenet.features.denseblock1.denselayer4.norm2.bias, %0.densenet.features.denseblock1.denselayer4.norm2.running_mean, %0.densenet.features.denseblock1.denselayer4.norm2.running_var) %807 = Relu(%806) %808 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%807, %0.densenet.features.denseblock1.denselayer4.conv2.weight) %809 = Concat[axis = 1](%802, %808) %810 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%809, %0.densenet.features.denseblock1.denselayer5.norm1.weight, %0.densenet.features.denseblock1.denselayer5.norm1.bias, %0.densenet.features.denseblock1.denselayer5.norm1.running_mean, %0.densenet.features.denseblock1.denselayer5.norm1.running_var) %811 = Relu(%810) %812 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%811, %0.densenet.features.denseblock1.denselayer5.conv1.weight) %813 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%812, %0.densenet.features.denseblock1.denselayer5.norm2.weight, %0.densenet.features.denseblock1.denselayer5.norm2.bias, %0.densenet.features.denseblock1.denselayer5.norm2.running_mean, %0.densenet.features.denseblock1.denselayer5.norm2.running_var) %814 = Relu(%813) %815 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%814, %0.densenet.features.denseblock1.denselayer5.conv2.weight) %816 = Concat[axis = 1](%809, %815) %817 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%816, %0.densenet.features.denseblock1.denselayer6.norm1.weight, %0.densenet.features.denseblock1.denselayer6.norm1.bias, %0.densenet.features.denseblock1.denselayer6.norm1.running_mean, %0.densenet.features.denseblock1.denselayer6.norm1.running_var) %818 = Relu(%817) %819 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%818, %0.densenet.features.denseblock1.denselayer6.conv1.weight) %820 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%819, %0.densenet.features.denseblock1.denselayer6.norm2.weight, %0.densenet.features.denseblock1.denselayer6.norm2.bias, %0.densenet.features.denseblock1.denselayer6.norm2.running_mean, %0.densenet.features.denseblock1.denselayer6.norm2.running_var) %821 = Relu(%820) %822 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%821, %0.densenet.features.denseblock1.denselayer6.conv2.weight) %823 = Concat[axis = 1](%816, %822) %824 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%823, %0.densenet.features.transition1.norm.weight, %0.densenet.features.transition1.norm.bias, %0.densenet.features.transition1.norm.running_mean, %0.densenet.features.transition1.norm.running_var) %825 = Relu(%824) %826 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%825, %0.densenet.features.transition1.conv.weight) %827 = Pad[mode = 'constant', pads = [0, 0, 0, 0, 0, 0, 0, 0], value = 0](%826) %828 = AveragePool[kernel_shape = [2, 2], pads = [0, 0, 0, 0], strides = [2, 2]](%827) %829 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%828, %0.densenet.features.denseblock2.denselayer1.norm1.weight, %0.densenet.features.denseblock2.denselayer1.norm1.bias, %0.densenet.features.denseblock2.denselayer1.norm1.running_mean, %0.densenet.features.denseblock2.denselayer1.norm1.running_var) %830 = Relu(%829) %831 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%830, %0.densenet.features.denseblock2.denselayer1.conv1.weight) %832 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%831, %0.densenet.features.denseblock2.denselayer1.norm2.weight, %0.densenet.features.denseblock2.denselayer1.norm2.bias, %0.densenet.features.denseblock2.denselayer1.norm2.running_mean, %0.densenet.features.denseblock2.denselayer1.norm2.running_var) %833 = Relu(%832) %834 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%833, %0.densenet.features.denseblock2.denselayer1.conv2.weight) %835 = Concat[axis = 1](%828, %834) %836 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%835, %0.densenet.features.denseblock2.denselayer2.norm1.weight, %0.densenet.features.denseblock2.denselayer2.norm1.bias, %0.densenet.features.denseblock2.denselayer2.norm1.running_mean, %0.densenet.features.denseblock2.denselayer2.norm1.running_var) %837 = Relu(%836) %838 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%837, %0.densenet.features.denseblock2.denselayer2.conv1.weight) %839 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%838, %0.densenet.features.denseblock2.denselayer2.norm2.weight, %0.densenet.features.denseblock2.denselayer2.norm2.bias, %0.densenet.features.denseblock2.denselayer2.norm2.running_mean, %0.densenet.features.denseblock2.denselayer2.norm2.running_var) %840 = Relu(%839) %841 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%840, %0.densenet.features.denseblock2.denselayer2.conv2.weight) %842 = Concat[axis = 1](%835, %841) %843 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%842, %0.densenet.features.denseblock2.denselayer3.norm1.weight, %0.densenet.features.denseblock2.denselayer3.norm1.bias, %0.densenet.features.denseblock2.denselayer3.norm1.running_mean, %0.densenet.features.denseblock2.denselayer3.norm1.running_var) %844 = Relu(%843) %845 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%844, %0.densenet.features.denseblock2.denselayer3.conv1.weight) %846 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%845, %0.densenet.features.denseblock2.denselayer3.norm2.weight, %0.densenet.features.denseblock2.denselayer3.norm2.bias, %0.densenet.features.denseblock2.denselayer3.norm2.running_mean, %0.densenet.features.denseblock2.denselayer3.norm2.running_var) %847 = Relu(%846) %848 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%847, %0.densenet.features.denseblock2.denselayer3.conv2.weight) %849 = Concat[axis = 1](%842, %848) %850 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%849, %0.densenet.features.denseblock2.denselayer4.norm1.weight, %0.densenet.features.denseblock2.denselayer4.norm1.bias, %0.densenet.features.denseblock2.denselayer4.norm1.running_mean, %0.densenet.features.denseblock2.denselayer4.norm1.running_var) %851 = Relu(%850) %852 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%851, %0.densenet.features.denseblock2.denselayer4.conv1.weight) %853 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%852, %0.densenet.features.denseblock2.denselayer4.norm2.weight, %0.densenet.features.denseblock2.denselayer4.norm2.bias, %0.densenet.features.denseblock2.denselayer4.norm2.running_mean, %0.densenet.features.denseblock2.denselayer4.norm2.running_var) %854 = Relu(%853) %855 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%854, %0.densenet.features.denseblock2.denselayer4.conv2.weight) %856 = Concat[axis = 1](%849, %855) %857 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%856, %0.densenet.features.denseblock2.denselayer5.norm1.weight, %0.densenet.features.denseblock2.denselayer5.norm1.bias, %0.densenet.features.denseblock2.denselayer5.norm1.running_mean, %0.densenet.features.denseblock2.denselayer5.norm1.running_var) %858 = Relu(%857) %859 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%858, %0.densenet.features.denseblock2.denselayer5.conv1.weight) %860 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%859, %0.densenet.features.denseblock2.denselayer5.norm2.weight, %0.densenet.features.denseblock2.denselayer5.norm2.bias, %0.densenet.features.denseblock2.denselayer5.norm2.running_mean, %0.densenet.features.denseblock2.denselayer5.norm2.running_var) %861 = Relu(%860) %862 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%861, %0.densenet.features.denseblock2.denselayer5.conv2.weight) %863 = Concat[axis = 1](%856, %862) %864 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%863, %0.densenet.features.denseblock2.denselayer6.norm1.weight, %0.densenet.features.denseblock2.denselayer6.norm1.bias, %0.densenet.features.denseblock2.denselayer6.norm1.running_mean, %0.densenet.features.denseblock2.denselayer6.norm1.running_var) %865 = Relu(%864) %866 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%865, %0.densenet.features.denseblock2.denselayer6.conv1.weight) %867 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%866, %0.densenet.features.denseblock2.denselayer6.norm2.weight, %0.densenet.features.denseblock2.denselayer6.norm2.bias, %0.densenet.features.denseblock2.denselayer6.norm2.running_mean, %0.densenet.features.denseblock2.denselayer6.norm2.running_var) %868 = Relu(%867) %869 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%868, %0.densenet.features.denseblock2.denselayer6.conv2.weight) %870 = Concat[axis = 1](%863, %869) %871 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%870, %0.densenet.features.denseblock2.denselayer7.norm1.weight, %0.densenet.features.denseblock2.denselayer7.norm1.bias, %0.densenet.features.denseblock2.denselayer7.norm1.running_mean, %0.densenet.features.denseblock2.denselayer7.norm1.running_var) %872 = Relu(%871) %873 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%872, %0.densenet.features.denseblock2.denselayer7.conv1.weight) %874 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%873, %0.densenet.features.denseblock2.denselayer7.norm2.weight, %0.densenet.features.denseblock2.denselayer7.norm2.bias, %0.densenet.features.denseblock2.denselayer7.norm2.running_mean, %0.densenet.features.denseblock2.denselayer7.norm2.running_var) %875 = Relu(%874) %876 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%875, %0.densenet.features.denseblock2.denselayer7.conv2.weight) %877 = Concat[axis = 1](%870, %876) %878 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%877, %0.densenet.features.denseblock2.denselayer8.norm1.weight, %0.densenet.features.denseblock2.denselayer8.norm1.bias, %0.densenet.features.denseblock2.denselayer8.norm1.running_mean, %0.densenet.features.denseblock2.denselayer8.norm1.running_var) %879 = Relu(%878) %880 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%879, %0.densenet.features.denseblock2.denselayer8.conv1.weight) %881 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%880, %0.densenet.features.denseblock2.denselayer8.norm2.weight, %0.densenet.features.denseblock2.denselayer8.norm2.bias, %0.densenet.features.denseblock2.denselayer8.norm2.running_mean, %0.densenet.features.denseblock2.denselayer8.norm2.running_var) %882 = Relu(%881) %883 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%882, %0.densenet.features.denseblock2.denselayer8.conv2.weight) %884 = Concat[axis = 1](%877, %883) %885 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%884, %0.densenet.features.denseblock2.denselayer9.norm1.weight, %0.densenet.features.denseblock2.denselayer9.norm1.bias, %0.densenet.features.denseblock2.denselayer9.norm1.running_mean, %0.densenet.features.denseblock2.denselayer9.norm1.running_var) %886 = Relu(%885) %887 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%886, %0.densenet.features.denseblock2.denselayer9.conv1.weight) %888 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%887, %0.densenet.features.denseblock2.denselayer9.norm2.weight, %0.densenet.features.denseblock2.denselayer9.norm2.bias, %0.densenet.features.denseblock2.denselayer9.norm2.running_mean, %0.densenet.features.denseblock2.denselayer9.norm2.running_var) %889 = Relu(%888) %890 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%889, %0.densenet.features.denseblock2.denselayer9.conv2.weight) %891 = Concat[axis = 1](%884, %890) %892 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%891, %0.densenet.features.denseblock2.denselayer10.norm1.weight, %0.densenet.features.denseblock2.denselayer10.norm1.bias, %0.densenet.features.denseblock2.denselayer10.norm1.running_mean, %0.densenet.features.denseblock2.denselayer10.norm1.running_var) %893 = Relu(%892) %894 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%893, %0.densenet.features.denseblock2.denselayer10.conv1.weight) %895 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%894, %0.densenet.features.denseblock2.denselayer10.norm2.weight, %0.densenet.features.denseblock2.denselayer10.norm2.bias, %0.densenet.features.denseblock2.denselayer10.norm2.running_mean, %0.densenet.features.denseblock2.denselayer10.norm2.running_var) %896 = Relu(%895) %897 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%896, %0.densenet.features.denseblock2.denselayer10.conv2.weight) %898 = Concat[axis = 1](%891, %897) %899 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%898, %0.densenet.features.denseblock2.denselayer11.norm1.weight, %0.densenet.features.denseblock2.denselayer11.norm1.bias, %0.densenet.features.denseblock2.denselayer11.norm1.running_mean, %0.densenet.features.denseblock2.denselayer11.norm1.running_var) %900 = Relu(%899) %901 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%900, %0.densenet.features.denseblock2.denselayer11.conv1.weight) %902 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%901, %0.densenet.features.denseblock2.denselayer11.norm2.weight, %0.densenet.features.denseblock2.denselayer11.norm2.bias, %0.densenet.features.denseblock2.denselayer11.norm2.running_mean, %0.densenet.features.denseblock2.denselayer11.norm2.running_var) %903 = Relu(%902) %904 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%903, %0.densenet.features.denseblock2.denselayer11.conv2.weight) %905 = Concat[axis = 1](%898, %904) %906 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%905, %0.densenet.features.denseblock2.denselayer12.norm1.weight, %0.densenet.features.denseblock2.denselayer12.norm1.bias, %0.densenet.features.denseblock2.denselayer12.norm1.running_mean, %0.densenet.features.denseblock2.denselayer12.norm1.running_var) %907 = Relu(%906) %908 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%907, %0.densenet.features.denseblock2.denselayer12.conv1.weight) %909 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%908, %0.densenet.features.denseblock2.denselayer12.norm2.weight, %0.densenet.features.denseblock2.denselayer12.norm2.bias, %0.densenet.features.denseblock2.denselayer12.norm2.running_mean, %0.densenet.features.denseblock2.denselayer12.norm2.running_var) %910 = Relu(%909) %911 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%910, %0.densenet.features.denseblock2.denselayer12.conv2.weight) %912 = Concat[axis = 1](%905, %911) %913 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%912, %0.densenet.features.transition2.norm.weight, %0.densenet.features.transition2.norm.bias, %0.densenet.features.transition2.norm.running_mean, %0.densenet.features.transition2.norm.running_var) %914 = Relu(%913) %915 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%914, %0.densenet.features.transition2.conv.weight) %916 = Pad[mode = 'constant', pads = [0, 0, 0, 0, 0, 0, 0, 0], value = 0](%915) %917 = AveragePool[kernel_shape = [2, 2], pads = [0, 0, 0, 0], strides = [2, 2]](%916) %918 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%917, %0.densenet.features.denseblock3.denselayer1.norm1.weight, %0.densenet.features.denseblock3.denselayer1.norm1.bias, %0.densenet.features.denseblock3.denselayer1.norm1.running_mean, %0.densenet.features.denseblock3.denselayer1.norm1.running_var) %919 = Relu(%918) %920 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%919, %0.densenet.features.denseblock3.denselayer1.conv1.weight) %921 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%920, %0.densenet.features.denseblock3.denselayer1.norm2.weight, %0.densenet.features.denseblock3.denselayer1.norm2.bias, %0.densenet.features.denseblock3.denselayer1.norm2.running_mean, %0.densenet.features.denseblock3.denselayer1.norm2.running_var) %922 = Relu(%921) %923 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%922, %0.densenet.features.denseblock3.denselayer1.conv2.weight) %924 = Concat[axis = 1](%917, %923) %925 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%924, %0.densenet.features.denseblock3.denselayer2.norm1.weight, %0.densenet.features.denseblock3.denselayer2.norm1.bias, %0.densenet.features.denseblock3.denselayer2.norm1.running_mean, %0.densenet.features.denseblock3.denselayer2.norm1.running_var) %926 = Relu(%925) %927 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%926, %0.densenet.features.denseblock3.denselayer2.conv1.weight) %928 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%927, %0.densenet.features.denseblock3.denselayer2.norm2.weight, %0.densenet.features.denseblock3.denselayer2.norm2.bias, %0.densenet.features.denseblock3.denselayer2.norm2.running_mean, %0.densenet.features.denseblock3.denselayer2.norm2.running_var) %929 = Relu(%928) %930 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%929, %0.densenet.features.denseblock3.denselayer2.conv2.weight) %931 = Concat[axis = 1](%924, %930) %932 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%931, %0.densenet.features.denseblock3.denselayer3.norm1.weight, %0.densenet.features.denseblock3.denselayer3.norm1.bias, %0.densenet.features.denseblock3.denselayer3.norm1.running_mean, %0.densenet.features.denseblock3.denselayer3.norm1.running_var) %933 = Relu(%932) %934 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%933, %0.densenet.features.denseblock3.denselayer3.conv1.weight) %935 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%934, %0.densenet.features.denseblock3.denselayer3.norm2.weight, %0.densenet.features.denseblock3.denselayer3.norm2.bias, %0.densenet.features.denseblock3.denselayer3.norm2.running_mean, %0.densenet.features.denseblock3.denselayer3.norm2.running_var) %936 = Relu(%935) %937 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%936, %0.densenet.features.denseblock3.denselayer3.conv2.weight) %938 = Concat[axis = 1](%931, %937) %939 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%938, %0.densenet.features.denseblock3.denselayer4.norm1.weight, %0.densenet.features.denseblock3.denselayer4.norm1.bias, %0.densenet.features.denseblock3.denselayer4.norm1.running_mean, %0.densenet.features.denseblock3.denselayer4.norm1.running_var) %940 = Relu(%939) %941 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%940, %0.densenet.features.denseblock3.denselayer4.conv1.weight) %942 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%941, %0.densenet.features.denseblock3.denselayer4.norm2.weight, %0.densenet.features.denseblock3.denselayer4.norm2.bias, %0.densenet.features.denseblock3.denselayer4.norm2.running_mean, %0.densenet.features.denseblock3.denselayer4.norm2.running_var) %943 = Relu(%942) %944 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%943, %0.densenet.features.denseblock3.denselayer4.conv2.weight) %945 = Concat[axis = 1](%938, %944) %946 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%945, %0.densenet.features.denseblock3.denselayer5.norm1.weight, %0.densenet.features.denseblock3.denselayer5.norm1.bias, %0.densenet.features.denseblock3.denselayer5.norm1.running_mean, %0.densenet.features.denseblock3.denselayer5.norm1.running_var) %947 = Relu(%946) %948 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%947, %0.densenet.features.denseblock3.denselayer5.conv1.weight) %949 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%948, %0.densenet.features.denseblock3.denselayer5.norm2.weight, %0.densenet.features.denseblock3.denselayer5.norm2.bias, %0.densenet.features.denseblock3.denselayer5.norm2.running_mean, %0.densenet.features.denseblock3.denselayer5.norm2.running_var) %950 = Relu(%949) %951 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%950, %0.densenet.features.denseblock3.denselayer5.conv2.weight) %952 = Concat[axis = 1](%945, %951) %953 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%952, %0.densenet.features.denseblock3.denselayer6.norm1.weight, %0.densenet.features.denseblock3.denselayer6.norm1.bias, %0.densenet.features.denseblock3.denselayer6.norm1.running_mean, %0.densenet.features.denseblock3.denselayer6.norm1.running_var) %954 = Relu(%953) %955 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%954, %0.densenet.features.denseblock3.denselayer6.conv1.weight) %956 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%955, %0.densenet.features.denseblock3.denselayer6.norm2.weight, %0.densenet.features.denseblock3.denselayer6.norm2.bias, %0.densenet.features.denseblock3.denselayer6.norm2.running_mean, %0.densenet.features.denseblock3.denselayer6.norm2.running_var) %957 = Relu(%956) %958 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%957, %0.densenet.features.denseblock3.denselayer6.conv2.weight) %959 = Concat[axis = 1](%952, %958) %960 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%959, %0.densenet.features.denseblock3.denselayer7.norm1.weight, %0.densenet.features.denseblock3.denselayer7.norm1.bias, %0.densenet.features.denseblock3.denselayer7.norm1.running_mean, %0.densenet.features.denseblock3.denselayer7.norm1.running_var) %961 = Relu(%960) %962 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%961, %0.densenet.features.denseblock3.denselayer7.conv1.weight) %963 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%962, %0.densenet.features.denseblock3.denselayer7.norm2.weight, %0.densenet.features.denseblock3.denselayer7.norm2.bias, %0.densenet.features.denseblock3.denselayer7.norm2.running_mean, %0.densenet.features.denseblock3.denselayer7.norm2.running_var) %964 = Relu(%963) %965 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%964, %0.densenet.features.denseblock3.denselayer7.conv2.weight) %966 = Concat[axis = 1](%959, %965) %967 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%966, %0.densenet.features.denseblock3.denselayer8.norm1.weight, %0.densenet.features.denseblock3.denselayer8.norm1.bias, %0.densenet.features.denseblock3.denselayer8.norm1.running_mean, %0.densenet.features.denseblock3.denselayer8.norm1.running_var) %968 = Relu(%967) %969 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%968, %0.densenet.features.denseblock3.denselayer8.conv1.weight) %970 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%969, %0.densenet.features.denseblock3.denselayer8.norm2.weight, %0.densenet.features.denseblock3.denselayer8.norm2.bias, %0.densenet.features.denseblock3.denselayer8.norm2.running_mean, %0.densenet.features.denseblock3.denselayer8.norm2.running_var) %971 = Relu(%970) %972 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%971, %0.densenet.features.denseblock3.denselayer8.conv2.weight) %973 = Concat[axis = 1](%966, %972) %974 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%973, %0.densenet.features.denseblock3.denselayer9.norm1.weight, %0.densenet.features.denseblock3.denselayer9.norm1.bias, %0.densenet.features.denseblock3.denselayer9.norm1.running_mean, %0.densenet.features.denseblock3.denselayer9.norm1.running_var) %975 = Relu(%974) %976 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%975, %0.densenet.features.denseblock3.denselayer9.conv1.weight) %977 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%976, %0.densenet.features.denseblock3.denselayer9.norm2.weight, %0.densenet.features.denseblock3.denselayer9.norm2.bias, %0.densenet.features.denseblock3.denselayer9.norm2.running_mean, %0.densenet.features.denseblock3.denselayer9.norm2.running_var) %978 = Relu(%977) %979 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%978, %0.densenet.features.denseblock3.denselayer9.conv2.weight) %980 = Concat[axis = 1](%973, %979) %981 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%980, %0.densenet.features.denseblock3.denselayer10.norm1.weight, %0.densenet.features.denseblock3.denselayer10.norm1.bias, %0.densenet.features.denseblock3.denselayer10.norm1.running_mean, %0.densenet.features.denseblock3.denselayer10.norm1.running_var) %982 = Relu(%981) %983 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%982, %0.densenet.features.denseblock3.denselayer10.conv1.weight) %984 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%983, %0.densenet.features.denseblock3.denselayer10.norm2.weight, %0.densenet.features.denseblock3.denselayer10.norm2.bias, %0.densenet.features.denseblock3.denselayer10.norm2.running_mean, %0.densenet.features.denseblock3.denselayer10.norm2.running_var) %985 = Relu(%984) %986 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%985, %0.densenet.features.denseblock3.denselayer10.conv2.weight) %987 = Concat[axis = 1](%980, %986) %988 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%987, %0.densenet.features.denseblock3.denselayer11.norm1.weight, %0.densenet.features.denseblock3.denselayer11.norm1.bias, %0.densenet.features.denseblock3.denselayer11.norm1.running_mean, %0.densenet.features.denseblock3.denselayer11.norm1.running_var) %989 = Relu(%988) %990 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%989, %0.densenet.features.denseblock3.denselayer11.conv1.weight) %991 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%990, %0.densenet.features.denseblock3.denselayer11.norm2.weight, %0.densenet.features.denseblock3.denselayer11.norm2.bias, %0.densenet.features.denseblock3.denselayer11.norm2.running_mean, %0.densenet.features.denseblock3.denselayer11.norm2.running_var) %992 = Relu(%991) %993 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%992, %0.densenet.features.denseblock3.denselayer11.conv2.weight) %994 = Concat[axis = 1](%987, %993) %995 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%994, %0.densenet.features.denseblock3.denselayer12.norm1.weight, %0.densenet.features.denseblock3.denselayer12.norm1.bias, %0.densenet.features.denseblock3.denselayer12.norm1.running_mean, %0.densenet.features.denseblock3.denselayer12.norm1.running_var) %996 = Relu(%995) %997 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%996, %0.densenet.features.denseblock3.denselayer12.conv1.weight) %998 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%997, %0.densenet.features.denseblock3.denselayer12.norm2.weight, %0.densenet.features.denseblock3.denselayer12.norm2.bias, %0.densenet.features.denseblock3.denselayer12.norm2.running_mean, %0.densenet.features.denseblock3.denselayer12.norm2.running_var) %999 = Relu(%998) %1000 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%999, %0.densenet.features.denseblock3.denselayer12.conv2.weight) %1001 = Concat[axis = 1](%994, %1000) %1002 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1001, %0.densenet.features.denseblock3.denselayer13.norm1.weight, %0.densenet.features.denseblock3.denselayer13.norm1.bias, %0.densenet.features.denseblock3.denselayer13.norm1.running_mean, %0.densenet.features.denseblock3.denselayer13.norm1.running_var) %1003 = Relu(%1002) %1004 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1003, %0.densenet.features.denseblock3.denselayer13.conv1.weight) %1005 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1004, %0.densenet.features.denseblock3.denselayer13.norm2.weight, %0.densenet.features.denseblock3.denselayer13.norm2.bias, %0.densenet.features.denseblock3.denselayer13.norm2.running_mean, %0.densenet.features.denseblock3.denselayer13.norm2.running_var) %1006 = Relu(%1005) %1007 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1006, %0.densenet.features.denseblock3.denselayer13.conv2.weight) %1008 = Concat[axis = 1](%1001, %1007) %1009 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1008, %0.densenet.features.denseblock3.denselayer14.norm1.weight, %0.densenet.features.denseblock3.denselayer14.norm1.bias, %0.densenet.features.denseblock3.denselayer14.norm1.running_mean, %0.densenet.features.denseblock3.denselayer14.norm1.running_var) %1010 = Relu(%1009) %1011 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1010, %0.densenet.features.denseblock3.denselayer14.conv1.weight) %1012 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1011, %0.densenet.features.denseblock3.denselayer14.norm2.weight, %0.densenet.features.denseblock3.denselayer14.norm2.bias, %0.densenet.features.denseblock3.denselayer14.norm2.running_mean, %0.densenet.features.denseblock3.denselayer14.norm2.running_var) %1013 = Relu(%1012) %1014 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1013, %0.densenet.features.denseblock3.denselayer14.conv2.weight) %1015 = Concat[axis = 1](%1008, %1014) %1016 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1015, %0.densenet.features.denseblock3.denselayer15.norm1.weight, %0.densenet.features.denseblock3.denselayer15.norm1.bias, %0.densenet.features.denseblock3.denselayer15.norm1.running_mean, %0.densenet.features.denseblock3.denselayer15.norm1.running_var) %1017 = Relu(%1016) %1018 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1017, %0.densenet.features.denseblock3.denselayer15.conv1.weight) %1019 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1018, %0.densenet.features.denseblock3.denselayer15.norm2.weight, %0.densenet.features.denseblock3.denselayer15.norm2.bias, %0.densenet.features.denseblock3.denselayer15.norm2.running_mean, %0.densenet.features.denseblock3.denselayer15.norm2.running_var) %1020 = Relu(%1019) %1021 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1020, %0.densenet.features.denseblock3.denselayer15.conv2.weight) %1022 = Concat[axis = 1](%1015, %1021) %1023 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1022, %0.densenet.features.denseblock3.denselayer16.norm1.weight, %0.densenet.features.denseblock3.denselayer16.norm1.bias, %0.densenet.features.denseblock3.denselayer16.norm1.running_mean, %0.densenet.features.denseblock3.denselayer16.norm1.running_var) %1024 = Relu(%1023) %1025 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1024, %0.densenet.features.denseblock3.denselayer16.conv1.weight) %1026 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1025, %0.densenet.features.denseblock3.denselayer16.norm2.weight, %0.densenet.features.denseblock3.denselayer16.norm2.bias, %0.densenet.features.denseblock3.denselayer16.norm2.running_mean, %0.densenet.features.denseblock3.denselayer16.norm2.running_var) %1027 = Relu(%1026) %1028 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1027, %0.densenet.features.denseblock3.denselayer16.conv2.weight) %1029 = Concat[axis = 1](%1022, %1028) %1030 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1029, %0.densenet.features.denseblock3.denselayer17.norm1.weight, %0.densenet.features.denseblock3.denselayer17.norm1.bias, %0.densenet.features.denseblock3.denselayer17.norm1.running_mean, %0.densenet.features.denseblock3.denselayer17.norm1.running_var) %1031 = Relu(%1030) %1032 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1031, %0.densenet.features.denseblock3.denselayer17.conv1.weight) %1033 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1032, %0.densenet.features.denseblock3.denselayer17.norm2.weight, %0.densenet.features.denseblock3.denselayer17.norm2.bias, %0.densenet.features.denseblock3.denselayer17.norm2.running_mean, %0.densenet.features.denseblock3.denselayer17.norm2.running_var) %1034 = Relu(%1033) %1035 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1034, %0.densenet.features.denseblock3.denselayer17.conv2.weight) %1036 = Concat[axis = 1](%1029, %1035) %1037 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1036, %0.densenet.features.denseblock3.denselayer18.norm1.weight, %0.densenet.features.denseblock3.denselayer18.norm1.bias, %0.densenet.features.denseblock3.denselayer18.norm1.running_mean, %0.densenet.features.denseblock3.denselayer18.norm1.running_var) %1038 = Relu(%1037) %1039 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1038, %0.densenet.features.denseblock3.denselayer18.conv1.weight) %1040 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1039, %0.densenet.features.denseblock3.denselayer18.norm2.weight, %0.densenet.features.denseblock3.denselayer18.norm2.bias, %0.densenet.features.denseblock3.denselayer18.norm2.running_mean, %0.densenet.features.denseblock3.denselayer18.norm2.running_var) %1041 = Relu(%1040) %1042 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1041, %0.densenet.features.denseblock3.denselayer18.conv2.weight) %1043 = Concat[axis = 1](%1036, %1042) %1044 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1043, %0.densenet.features.denseblock3.denselayer19.norm1.weight, %0.densenet.features.denseblock3.denselayer19.norm1.bias, %0.densenet.features.denseblock3.denselayer19.norm1.running_mean, %0.densenet.features.denseblock3.denselayer19.norm1.running_var) %1045 = Relu(%1044) %1046 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1045, %0.densenet.features.denseblock3.denselayer19.conv1.weight) %1047 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1046, %0.densenet.features.denseblock3.denselayer19.norm2.weight, %0.densenet.features.denseblock3.denselayer19.norm2.bias, %0.densenet.features.denseblock3.denselayer19.norm2.running_mean, %0.densenet.features.denseblock3.denselayer19.norm2.running_var) %1048 = Relu(%1047) %1049 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1048, %0.densenet.features.denseblock3.denselayer19.conv2.weight) %1050 = Concat[axis = 1](%1043, %1049) %1051 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1050, %0.densenet.features.denseblock3.denselayer20.norm1.weight, %0.densenet.features.denseblock3.denselayer20.norm1.bias, %0.densenet.features.denseblock3.denselayer20.norm1.running_mean, %0.densenet.features.denseblock3.denselayer20.norm1.running_var) %1052 = Relu(%1051) %1053 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1052, %0.densenet.features.denseblock3.denselayer20.conv1.weight) %1054 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1053, %0.densenet.features.denseblock3.denselayer20.norm2.weight, %0.densenet.features.denseblock3.denselayer20.norm2.bias, %0.densenet.features.denseblock3.denselayer20.norm2.running_mean, %0.densenet.features.denseblock3.denselayer20.norm2.running_var) %1055 = Relu(%1054) %1056 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1055, %0.densenet.features.denseblock3.denselayer20.conv2.weight) %1057 = Concat[axis = 1](%1050, %1056) %1058 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1057, %0.densenet.features.denseblock3.denselayer21.norm1.weight, %0.densenet.features.denseblock3.denselayer21.norm1.bias, %0.densenet.features.denseblock3.denselayer21.norm1.running_mean, %0.densenet.features.denseblock3.denselayer21.norm1.running_var) %1059 = Relu(%1058) %1060 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1059, %0.densenet.features.denseblock3.denselayer21.conv1.weight) %1061 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1060, %0.densenet.features.denseblock3.denselayer21.norm2.weight, %0.densenet.features.denseblock3.denselayer21.norm2.bias, %0.densenet.features.denseblock3.denselayer21.norm2.running_mean, %0.densenet.features.denseblock3.denselayer21.norm2.running_var) %1062 = Relu(%1061) %1063 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1062, %0.densenet.features.denseblock3.denselayer21.conv2.weight) %1064 = Concat[axis = 1](%1057, %1063) %1065 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1064, %0.densenet.features.denseblock3.denselayer22.norm1.weight, %0.densenet.features.denseblock3.denselayer22.norm1.bias, %0.densenet.features.denseblock3.denselayer22.norm1.running_mean, %0.densenet.features.denseblock3.denselayer22.norm1.running_var) %1066 = Relu(%1065) %1067 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1066, %0.densenet.features.denseblock3.denselayer22.conv1.weight) %1068 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1067, %0.densenet.features.denseblock3.denselayer22.norm2.weight, %0.densenet.features.denseblock3.denselayer22.norm2.bias, %0.densenet.features.denseblock3.denselayer22.norm2.running_mean, %0.densenet.features.denseblock3.denselayer22.norm2.running_var) %1069 = Relu(%1068) %1070 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1069, %0.densenet.features.denseblock3.denselayer22.conv2.weight) %1071 = Concat[axis = 1](%1064, %1070) %1072 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1071, %0.densenet.features.denseblock3.denselayer23.norm1.weight, %0.densenet.features.denseblock3.denselayer23.norm1.bias, %0.densenet.features.denseblock3.denselayer23.norm1.running_mean, %0.densenet.features.denseblock3.denselayer23.norm1.running_var) %1073 = Relu(%1072) %1074 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1073, %0.densenet.features.denseblock3.denselayer23.conv1.weight) %1075 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1074, %0.densenet.features.denseblock3.denselayer23.norm2.weight, %0.densenet.features.denseblock3.denselayer23.norm2.bias, %0.densenet.features.denseblock3.denselayer23.norm2.running_mean, %0.densenet.features.denseblock3.denselayer23.norm2.running_var) %1076 = Relu(%1075) %1077 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1076, %0.densenet.features.denseblock3.denselayer23.conv2.weight) %1078 = Concat[axis = 1](%1071, %1077) %1079 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1078, %0.densenet.features.denseblock3.denselayer24.norm1.weight, %0.densenet.features.denseblock3.denselayer24.norm1.bias, %0.densenet.features.denseblock3.denselayer24.norm1.running_mean, %0.densenet.features.denseblock3.denselayer24.norm1.running_var) %1080 = Relu(%1079) %1081 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1080, %0.densenet.features.denseblock3.denselayer24.conv1.weight) %1082 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1081, %0.densenet.features.denseblock3.denselayer24.norm2.weight, %0.densenet.features.denseblock3.denselayer24.norm2.bias, %0.densenet.features.denseblock3.denselayer24.norm2.running_mean, %0.densenet.features.denseblock3.denselayer24.norm2.running_var) %1083 = Relu(%1082) %1084 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1083, %0.densenet.features.denseblock3.denselayer24.conv2.weight) %1085 = Concat[axis = 1](%1078, %1084) %1086 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1085, %0.densenet.features.transition3.norm.weight, %0.densenet.features.transition3.norm.bias, %0.densenet.features.transition3.norm.running_mean, %0.densenet.features.transition3.norm.running_var) %1087 = Relu(%1086) %1088 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1087, %0.densenet.features.transition3.conv.weight) %1089 = Pad[mode = 'constant', pads = [0, 0, 0, 0, 0, 0, 0, 0], value = 0](%1088) %1090 = AveragePool[kernel_shape = [2, 2], pads = [0, 0, 0, 0], strides = [2, 2]](%1089) %1091 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1090, %0.densenet.features.denseblock4.denselayer1.norm1.weight, %0.densenet.features.denseblock4.denselayer1.norm1.bias, %0.densenet.features.denseblock4.denselayer1.norm1.running_mean, %0.densenet.features.denseblock4.denselayer1.norm1.running_var) %1092 = Relu(%1091) %1093 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1092, %0.densenet.features.denseblock4.denselayer1.conv1.weight) %1094 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1093, %0.densenet.features.denseblock4.denselayer1.norm2.weight, %0.densenet.features.denseblock4.denselayer1.norm2.bias, %0.densenet.features.denseblock4.denselayer1.norm2.running_mean, %0.densenet.features.denseblock4.denselayer1.norm2.running_var) %1095 = Relu(%1094) %1096 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1095, %0.densenet.features.denseblock4.denselayer1.conv2.weight) %1097 = Concat[axis = 1](%1090, %1096) %1098 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1097, %0.densenet.features.denseblock4.denselayer2.norm1.weight, %0.densenet.features.denseblock4.denselayer2.norm1.bias, %0.densenet.features.denseblock4.denselayer2.norm1.running_mean, %0.densenet.features.denseblock4.denselayer2.norm1.running_var) %1099 = Relu(%1098) %1100 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1099, %0.densenet.features.denseblock4.denselayer2.conv1.weight) %1101 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1100, %0.densenet.features.denseblock4.denselayer2.norm2.weight, %0.densenet.features.denseblock4.denselayer2.norm2.bias, %0.densenet.features.denseblock4.denselayer2.norm2.running_mean, %0.densenet.features.denseblock4.denselayer2.norm2.running_var) %1102 = Relu(%1101) %1103 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1102, %0.densenet.features.denseblock4.denselayer2.conv2.weight) %1104 = Concat[axis = 1](%1097, %1103) %1105 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1104, %0.densenet.features.denseblock4.denselayer3.norm1.weight, %0.densenet.features.denseblock4.denselayer3.norm1.bias, %0.densenet.features.denseblock4.denselayer3.norm1.running_mean, %0.densenet.features.denseblock4.denselayer3.norm1.running_var) %1106 = Relu(%1105) %1107 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1106, %0.densenet.features.denseblock4.denselayer3.conv1.weight) %1108 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1107, %0.densenet.features.denseblock4.denselayer3.norm2.weight, %0.densenet.features.denseblock4.denselayer3.norm2.bias, %0.densenet.features.denseblock4.denselayer3.norm2.running_mean, %0.densenet.features.denseblock4.denselayer3.norm2.running_var) %1109 = Relu(%1108) %1110 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1109, %0.densenet.features.denseblock4.denselayer3.conv2.weight) %1111 = Concat[axis = 1](%1104, %1110) %1112 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1111, %0.densenet.features.denseblock4.denselayer4.norm1.weight, %0.densenet.features.denseblock4.denselayer4.norm1.bias, %0.densenet.features.denseblock4.denselayer4.norm1.running_mean, %0.densenet.features.denseblock4.denselayer4.norm1.running_var) %1113 = Relu(%1112) %1114 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1113, %0.densenet.features.denseblock4.denselayer4.conv1.weight) %1115 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1114, %0.densenet.features.denseblock4.denselayer4.norm2.weight, %0.densenet.features.denseblock4.denselayer4.norm2.bias, %0.densenet.features.denseblock4.denselayer4.norm2.running_mean, %0.densenet.features.denseblock4.denselayer4.norm2.running_var) %1116 = Relu(%1115) %1117 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1116, %0.densenet.features.denseblock4.denselayer4.conv2.weight) %1118 = Concat[axis = 1](%1111, %1117) %1119 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1118, %0.densenet.features.denseblock4.denselayer5.norm1.weight, %0.densenet.features.denseblock4.denselayer5.norm1.bias, %0.densenet.features.denseblock4.denselayer5.norm1.running_mean, %0.densenet.features.denseblock4.denselayer5.norm1.running_var) %1120 = Relu(%1119) %1121 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1120, %0.densenet.features.denseblock4.denselayer5.conv1.weight) %1122 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1121, %0.densenet.features.denseblock4.denselayer5.norm2.weight, %0.densenet.features.denseblock4.denselayer5.norm2.bias, %0.densenet.features.denseblock4.denselayer5.norm2.running_mean, %0.densenet.features.denseblock4.denselayer5.norm2.running_var) %1123 = Relu(%1122) %1124 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1123, %0.densenet.features.denseblock4.denselayer5.conv2.weight) %1125 = Concat[axis = 1](%1118, %1124) %1126 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1125, %0.densenet.features.denseblock4.denselayer6.norm1.weight, %0.densenet.features.denseblock4.denselayer6.norm1.bias, %0.densenet.features.denseblock4.denselayer6.norm1.running_mean, %0.densenet.features.denseblock4.denselayer6.norm1.running_var) %1127 = Relu(%1126) %1128 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1127, %0.densenet.features.denseblock4.denselayer6.conv1.weight) %1129 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1128, %0.densenet.features.denseblock4.denselayer6.norm2.weight, %0.densenet.features.denseblock4.denselayer6.norm2.bias, %0.densenet.features.denseblock4.denselayer6.norm2.running_mean, %0.densenet.features.denseblock4.denselayer6.norm2.running_var) %1130 = Relu(%1129) %1131 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1130, %0.densenet.features.denseblock4.denselayer6.conv2.weight) %1132 = Concat[axis = 1](%1125, %1131) %1133 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1132, %0.densenet.features.denseblock4.denselayer7.norm1.weight, %0.densenet.features.denseblock4.denselayer7.norm1.bias, %0.densenet.features.denseblock4.denselayer7.norm1.running_mean, %0.densenet.features.denseblock4.denselayer7.norm1.running_var) %1134 = Relu(%1133) %1135 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1134, %0.densenet.features.denseblock4.denselayer7.conv1.weight) %1136 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1135, %0.densenet.features.denseblock4.denselayer7.norm2.weight, %0.densenet.features.denseblock4.denselayer7.norm2.bias, %0.densenet.features.denseblock4.denselayer7.norm2.running_mean, %0.densenet.features.denseblock4.denselayer7.norm2.running_var) %1137 = Relu(%1136) %1138 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1137, %0.densenet.features.denseblock4.denselayer7.conv2.weight) %1139 = Concat[axis = 1](%1132, %1138) %1140 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1139, %0.densenet.features.denseblock4.denselayer8.norm1.weight, %0.densenet.features.denseblock4.denselayer8.norm1.bias, %0.densenet.features.denseblock4.denselayer8.norm1.running_mean, %0.densenet.features.denseblock4.denselayer8.norm1.running_var) %1141 = Relu(%1140) %1142 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1141, %0.densenet.features.denseblock4.denselayer8.conv1.weight) %1143 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1142, %0.densenet.features.denseblock4.denselayer8.norm2.weight, %0.densenet.features.denseblock4.denselayer8.norm2.bias, %0.densenet.features.denseblock4.denselayer8.norm2.running_mean, %0.densenet.features.denseblock4.denselayer8.norm2.running_var) %1144 = Relu(%1143) %1145 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1144, %0.densenet.features.denseblock4.denselayer8.conv2.weight) %1146 = Concat[axis = 1](%1139, %1145) %1147 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1146, %0.densenet.features.denseblock4.denselayer9.norm1.weight, %0.densenet.features.denseblock4.denselayer9.norm1.bias, %0.densenet.features.denseblock4.denselayer9.norm1.running_mean, %0.densenet.features.denseblock4.denselayer9.norm1.running_var) %1148 = Relu(%1147) %1149 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1148, %0.densenet.features.denseblock4.denselayer9.conv1.weight) %1150 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1149, %0.densenet.features.denseblock4.denselayer9.norm2.weight, %0.densenet.features.denseblock4.denselayer9.norm2.bias, %0.densenet.features.denseblock4.denselayer9.norm2.running_mean, %0.densenet.features.denseblock4.denselayer9.norm2.running_var) %1151 = Relu(%1150) %1152 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1151, %0.densenet.features.denseblock4.denselayer9.conv2.weight) %1153 = Concat[axis = 1](%1146, %1152) %1154 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1153, %0.densenet.features.denseblock4.denselayer10.norm1.weight, %0.densenet.features.denseblock4.denselayer10.norm1.bias, %0.densenet.features.denseblock4.denselayer10.norm1.running_mean, %0.densenet.features.denseblock4.denselayer10.norm1.running_var) %1155 = Relu(%1154) %1156 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1155, %0.densenet.features.denseblock4.denselayer10.conv1.weight) %1157 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1156, %0.densenet.features.denseblock4.denselayer10.norm2.weight, %0.densenet.features.denseblock4.denselayer10.norm2.bias, %0.densenet.features.denseblock4.denselayer10.norm2.running_mean, %0.densenet.features.denseblock4.denselayer10.norm2.running_var) %1158 = Relu(%1157) %1159 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1158, %0.densenet.features.denseblock4.denselayer10.conv2.weight) %1160 = Concat[axis = 1](%1153, %1159) %1161 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1160, %0.densenet.features.denseblock4.denselayer11.norm1.weight, %0.densenet.features.denseblock4.denselayer11.norm1.bias, %0.densenet.features.denseblock4.denselayer11.norm1.running_mean, %0.densenet.features.denseblock4.denselayer11.norm1.running_var) %1162 = Relu(%1161) %1163 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1162, %0.densenet.features.denseblock4.denselayer11.conv1.weight) %1164 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1163, %0.densenet.features.denseblock4.denselayer11.norm2.weight, %0.densenet.features.denseblock4.denselayer11.norm2.bias, %0.densenet.features.denseblock4.denselayer11.norm2.running_mean, %0.densenet.features.denseblock4.denselayer11.norm2.running_var) %1165 = Relu(%1164) %1166 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1165, %0.densenet.features.denseblock4.denselayer11.conv2.weight) %1167 = Concat[axis = 1](%1160, %1166) %1168 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1167, %0.densenet.features.denseblock4.denselayer12.norm1.weight, %0.densenet.features.denseblock4.denselayer12.norm1.bias, %0.densenet.features.denseblock4.denselayer12.norm1.running_mean, %0.densenet.features.denseblock4.denselayer12.norm1.running_var) %1169 = Relu(%1168) %1170 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1169, %0.densenet.features.denseblock4.denselayer12.conv1.weight) %1171 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1170, %0.densenet.features.denseblock4.denselayer12.norm2.weight, %0.densenet.features.denseblock4.denselayer12.norm2.bias, %0.densenet.features.denseblock4.denselayer12.norm2.running_mean, %0.densenet.features.denseblock4.denselayer12.norm2.running_var) %1172 = Relu(%1171) %1173 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1172, %0.densenet.features.denseblock4.denselayer12.conv2.weight) %1174 = Concat[axis = 1](%1167, %1173) %1175 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1174, %0.densenet.features.denseblock4.denselayer13.norm1.weight, %0.densenet.features.denseblock4.denselayer13.norm1.bias, %0.densenet.features.denseblock4.denselayer13.norm1.running_mean, %0.densenet.features.denseblock4.denselayer13.norm1.running_var) %1176 = Relu(%1175) %1177 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1176, %0.densenet.features.denseblock4.denselayer13.conv1.weight) %1178 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1177, %0.densenet.features.denseblock4.denselayer13.norm2.weight, %0.densenet.features.denseblock4.denselayer13.norm2.bias, %0.densenet.features.denseblock4.denselayer13.norm2.running_mean, %0.densenet.features.denseblock4.denselayer13.norm2.running_var) %1179 = Relu(%1178) %1180 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1179, %0.densenet.features.denseblock4.denselayer13.conv2.weight) %1181 = Concat[axis = 1](%1174, %1180) %1182 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1181, %0.densenet.features.denseblock4.denselayer14.norm1.weight, %0.densenet.features.denseblock4.denselayer14.norm1.bias, %0.densenet.features.denseblock4.denselayer14.norm1.running_mean, %0.densenet.features.denseblock4.denselayer14.norm1.running_var) %1183 = Relu(%1182) %1184 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1183, %0.densenet.features.denseblock4.denselayer14.conv1.weight) %1185 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1184, %0.densenet.features.denseblock4.denselayer14.norm2.weight, %0.densenet.features.denseblock4.denselayer14.norm2.bias, %0.densenet.features.denseblock4.denselayer14.norm2.running_mean, %0.densenet.features.denseblock4.denselayer14.norm2.running_var) %1186 = Relu(%1185) %1187 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1186, %0.densenet.features.denseblock4.denselayer14.conv2.weight) %1188 = Concat[axis = 1](%1181, %1187) %1189 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1188, %0.densenet.features.denseblock4.denselayer15.norm1.weight, %0.densenet.features.denseblock4.denselayer15.norm1.bias, %0.densenet.features.denseblock4.denselayer15.norm1.running_mean, %0.densenet.features.denseblock4.denselayer15.norm1.running_var) %1190 = Relu(%1189) %1191 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1190, %0.densenet.features.denseblock4.denselayer15.conv1.weight) %1192 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1191, %0.densenet.features.denseblock4.denselayer15.norm2.weight, %0.densenet.features.denseblock4.denselayer15.norm2.bias, %0.densenet.features.denseblock4.denselayer15.norm2.running_mean, %0.densenet.features.denseblock4.denselayer15.norm2.running_var) %1193 = Relu(%1192) %1194 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1193, %0.densenet.features.denseblock4.denselayer15.conv2.weight) %1195 = Concat[axis = 1](%1188, %1194) %1196 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1195, %0.densenet.features.denseblock4.denselayer16.norm1.weight, %0.densenet.features.denseblock4.denselayer16.norm1.bias, %0.densenet.features.denseblock4.denselayer16.norm1.running_mean, %0.densenet.features.denseblock4.denselayer16.norm1.running_var) %1197 = Relu(%1196) %1198 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1197, %0.densenet.features.denseblock4.denselayer16.conv1.weight) %1199 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1198, %0.densenet.features.denseblock4.denselayer16.norm2.weight, %0.densenet.features.denseblock4.denselayer16.norm2.bias, %0.densenet.features.denseblock4.denselayer16.norm2.running_mean, %0.densenet.features.denseblock4.denselayer16.norm2.running_var) %1200 = Relu(%1199) %1201 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1200, %0.densenet.features.denseblock4.denselayer16.conv2.weight) %1202 = Concat[axis = 1](%1195, %1201) %1203 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1202, %0.densenet.features.norm5.weight, %0.densenet.features.norm5.bias, %0.densenet.features.norm5.running_mean, %0.densenet.features.norm5.running_var) %1204 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1203, %1.cmap_up.0.weight, %1.cmap_up.0.bias) %1205 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1204, %1.cmap_up.1.weight, %1.cmap_up.1.bias, %1.cmap_up.1.running_mean, %1.cmap_up.1.running_var) %1206 = Relu(%1205) %1207 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1206, %1.cmap_up.3.weight, %1.cmap_up.3.bias) %1208 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1207, %1.cmap_up.4.weight, %1.cmap_up.4.bias, %1.cmap_up.4.running_mean, %1.cmap_up.4.running_var) %1209 = Relu(%1208) %1210 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1209, %1.cmap_up.6.weight, %1.cmap_up.6.bias) %1211 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1210, %1.cmap_up.7.weight, %1.cmap_up.7.bias, %1.cmap_up.7.running_mean, %1.cmap_up.7.running_var) %1212 = Relu(%1211) %1213 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1212, %1.cmap_att.weight, %1.cmap_att.bias) %1214 = Sigmoid(%1213) %1215 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1203, %1.paf_up.0.weight, %1.paf_up.0.bias) %1216 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1215, %1.paf_up.1.weight, %1.paf_up.1.bias, %1.paf_up.1.running_mean, %1.paf_up.1.running_var) %1217 = Relu(%1216) %1218 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1217, %1.paf_up.3.weight, %1.paf_up.3.bias) %1219 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1218, %1.paf_up.4.weight, %1.paf_up.4.bias, %1.paf_up.4.running_mean, %1.paf_up.4.running_var) %1220 = Relu(%1219) %1221 = ConvTranspose[dilations = [1, 1], group = 1, kernel_shape = [4, 4], pads = [1, 1, 1, 1], strides = [2, 2]](%1220, %1.paf_up.6.weight, %1.paf_up.6.bias) %1222 = BatchNormalization[epsilon = 9.99999974737875e-06, momentum = 0.899999976158142](%1221, %1.paf_up.7.weight, %1.paf_up.7.bias, %1.paf_up.7.running_mean, %1.paf_up.7.running_var) %1223 = Relu(%1222) %1224 = Conv[dilations = [1, 1], group = 1, kernel_shape = [3, 3], pads = [1, 1, 1, 1], strides = [1, 1]](%1223, %1.paf_att.weight, %1.paf_att.bias) %1225 = Tanh(%1224) %1226 = Mul(%1212, %1214) %1227 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1226, %1.cmap_conv.weight, %1.cmap_conv.bias) %1228 = Mul(%1223, %1225) %1229 = Conv[dilations = [1, 1], group = 1, kernel_shape = [1, 1], pads = [0, 0, 0, 0], strides = [1, 1]](%1228, %1.paf_conv.weight, %1.paf_conv.bias) return %1227, %1229 }
NLP_with_PyTorch/3_document-embedding/3-2. ELMo.ipynb
###Markdown 3-2. ELMo1&nbsp;&nbsp;Prepare dataset: Gutenberg1.1&nbsp;&nbsp;For pretraining1.2&nbsp;&nbsp;For training2&nbsp;&nbsp;Build the model2.1&nbsp;&nbsp;Bidirectional language model2.2&nbsp;&nbsp;ELMo3&nbsp;&nbsp;Train the model3.1&nbsp;&nbsp;Pretrain bidirectional language model3.2&nbsp;&nbsp;Train ELMo for sentiment analysis Prepare dataset: Gutenberg ###Code from torchtext.experimental.datasets import IMDB from torchtext.data.utils import get_tokenizer tokenizer = get_tokenizer("spacy") train, test = IMDB(tokenizer=tokenizer) vocab = train.get_vocab() ngrams = 2 x = [] y = [] for _, words in train: for i in range(len(words)-ngrams): text = words[i:i+ngrams] label = words[i+ngrams] x.append(text.tolist()) y.append(label.tolist()) ###Output _____no_output_____ ###Markdown ```pythonwith open("./IMBD_bigram.json", "w") as w: json.dump({"data": x, "label": y}, w)``` For pretraining * transform to character-level n-gram dataset * original script```%load https://gist.githubusercontent.com/akurniawan/30719686669dced49e7ced720329a616/raw/7b9f9967c01ce87ac505520a5aa58d3b24c55c66/translation_char_example.py``` * modified```%load https://gist.github.com/naturale0/6bb3b8a5c682bd281de87e408fa71bf1/raw/df8b7e198f149f81c4f72af977760b2eb3226cdf/translation_char_example.py``` ###Code # Modified a little to fit classification import itertools from torchtext.experimental.datasets import TextClassificationDataset from torchtext.vocab import build_vocab_from_iterator from torchtext.experimental.functional import sequential_transforms def build_char_vocab(data, index, bow="<w>", eow="</w>"): """ build character level vocabulary """ tok_list = [ [bow], [eow], ] for line in data: tokens = list(itertools.chain.from_iterable(line[index])) tok_list.append(tokens) return build_vocab_from_iterator(tok_list) def stoi(vocab): """ change string to index """ def func(tok_iter): return [[vocab[char] for char in word]\ for word in tok_iter] return func def tokenize_char(bow="<w>", eow="</w>", max_word_length=20): """ attach bow, eow token and pad with token """ def func(tok_iter): result = np.empty((max(len_seq), max_word_length+2), dtype=object) # "≥" for padding result[:len(tok_iter)] = [ [bow] + word + [eow] \ + ["<pad>"] * (max_word_length - len(word)) \ if len(word) < max_word_length \ else [bow] + word[:max_word_length] + [eow] for word in tok_iter] return result return func # Cache training data for vocabulary construction train_data = [(line[0], [vocab.itos[ix] for ix in line[1]]) for line in zip(y, x)] train_data[:3] # Setup vocabularies (both words and chars) char_vocab = build_char_vocab(train_data, index=1) # Building the dataset with character level tokenization def char_tokenizer(words): return [list(word) for word in words] char_transform = sequential_transforms( char_tokenizer, tokenize_char(), stoi(char_vocab), lambda x: torch.tensor(x) ) trainset = TextClassificationDataset( train_data, char_vocab, (lambda x: x, char_transform), ) # Prepare DataLoader def collate_fn(batch): label, text = zip(*batch) label = torch.LongTensor(label) text = torch.stack(text) #lens = list(map(lambda x: len(x[(x != 0).all(dim=1)]), text)) return label, text pretrainloader = data.DataLoader(trainset, batch_size=32, collate_fn=collate_fn) ###Output _____no_output_____ ###Markdown For training ###Code # Modified a little to fit classification import itertools from torchtext.experimental.datasets import TextClassificationDataset from torchtext.vocab import build_vocab_from_iterator from torchtext.experimental.functional import sequential_transforms def build_char_vocab(data, index, bow="<w>", eow="</w>"): """ build character level vocabulary """ tok_list = [ [bow], [eow], ] for line in data: tokens = list(itertools.chain.from_iterable(line[index])) tok_list.append(tokens) return build_vocab_from_iterator(tok_list) def stoi(vocab): """ change string to index """ def func(tok_iter): return [[vocab[char] for char in word]\ for word in tok_iter] return func def tokenize_char(bow="<w>", eow="</w>", max_word_length=20): """ attach bow, eow token and pad with token """ def func(tok_iter): result = np.empty((max(len_seq), max_word_length+2), dtype=object) # "≥" for padding result[:len(tok_iter)] = [ [bow] + word + [eow] \ + ["<pad>"] * (max_word_length - len(word)) \ if len(word) < max_word_length \ else [bow] + word[:max_word_length] + [eow] for word in tok_iter] return result return func # Cache training data for vocabulary construction train_data = [(line[0], [vocab.itos[ix] for ix in line[1]]) for line in train] # store list of seq length for packing later len_seq = list(map(lambda x: len(x), train_data)) # Setup vocabularies (both words and chars) char_vocab = build_char_vocab(train_data, index=1) # Building the dataset with character level tokenization def char_tokenizer(words): return [list(word) for word in words] char_transform = sequential_transforms( char_tokenizer, tokenize_char(), stoi(char_vocab), lambda x: torch.tensor(x) ) trainset = TextClassificationDataset( train_data, char_vocab, (lambda x: x, char_transform), ) # Prepare DataLoader def collate_fn(batch): label, text = zip(*batch) label = torch.stack(label) text = torch.stack(text) #lens = list(map(lambda x: len(x[(x != 0).all(dim=1)]), text)) return label, text trainloader = data.DataLoader(trainset, batch_size=32, collate_fn=collate_fn) ###Output _____no_output_____ ###Markdown Build the model Bidirectional language model ###Code x = next(iter(pretrainloader))[1] x.shape x2 = nn.Embedding(len(char_vocab), 4)(x) x2.shape x2.permute(0,3,1,2).shape x3 = nn.Conv2d(4, 5, (1, 3))(x2.permute(0,3,1,2)) x3.shape x4 = F.max_pool2d(x3, kernel_size=(1, x3.shape[3])) x4.shape x5 = torch.squeeze(x4) x5.shape, x5.view(-1, ngrams*5).shape, x5.permute(2, 0, 1).shape # (seq_len, batch, input_size) x6 = nn.Linear(ngrams*5, 10)(x5.view(-1, ngrams*5)) x6.shape o, h = nn.LSTM(5, 6)(x5.permute(2, 0, 1)) len(h), o.shape class CharConv(nn.Module): def __init__(self): super(self, BiLM).__init__() # Embedding layer CHAR_EMBEDDING_DIM = 16 self.char_embedding = nn.Embedding(len(char_vocab), CHAR_EMBEDDING_DIM) # Conv layers self.convs = [ nn.Conv2d(CHAR_EMBEDDING_DIM, 4, 1), nn.Conv2d(CHAR_EMBEDDING_DIM, 4, (1, 2)), nn.Conv2d(CHAR_EMBEDDING_DIM, 8, (1, 3)), nn.Conv2d(CHAR_EMBEDDING_DIM, 16, (1, 4)), nn.Conv2d(CHAR_EMBEDDING_DIM, 32, (1, 5)), nn.Conv2d(CHAR_EMBEDDING_DIM, 64, (1, 6)), nn.Conv2d(CHAR_EMBEDDING_DIM, 128, (1, 7)) ] def forward(self, x): # character-level convolution x = self.char_embedding(x).permute(0,3,1,2) x = [conv(x) for conv in self.convs] x = [F.max_pool2d(x_c, kernel_size=x_c.shape[3]) for x_c in x] x = [torch.squeeze(x_p) for x_p in x] x = torch.vstack(x) # 1, n_batch, concat_length x = x.permute(2, 0, 1) return x class BiLSTM(nn.Module): def __init__(self): # Bi-LSTM self.lstm1 = nn.LSTM(256, 1024, bidirectional=True) self.proj = nn.Linear(1024, 128, bias=False) self.lstm2 = nn.LSTM(128, 1024, bidirectional=True) def forward(self, x): pass class BiLM(nn.Module): def __init__(self, char_cnn, bi_lstm): # Highway connection CHAR_EMBEDDING_DIM = 16 self.highway = nn.Linear(ngrams * 256, 256) self.transform = nn.Linear(ngrams * 256, 256) self.char_cnn = char_cnn self.bi_lstm = bi_lstm def forward(self, x): # Character-level convolution x = self.char_cnn(x) x = x.view(1, -1) # highway h = self.highway(x) t_gate = torch.sigmoid(self.transform(x)) c_gate = 1 - t_gate x = h * t_gate + x * c_gate # Bi-LSTM self.bi_lstm(x) ###Output _____no_output_____
examples/tutorials/research/02_domain.ipynb
###Markdown Advanced Usage of Domain [`Domain`](https://analysiscenter.github.io/batchflow/api/batchflow.research.htmlbatchflow.research.Domain) and auxiliary classes ([`Alias`](https://analysiscenter.github.io/batchflow/api/batchflow.research.htmlbatchflow.research.Alias), [`Option`](https://analysiscenter.github.io/batchflow/api/batchflow.research.htmlbatchflow.research.Option), [`ConfigAlias`](https://analysiscenter.github.io/batchflow/api/batchflow.research.htmlbatchflow.research.ConfigAlias)) are used to define combinations of parameters to try in `Research`. We start with some useful imports. ###Code import sys import os import shutil import matplotlib %matplotlib inline sys.path.append('../../../..') from batchflow import NumpySampler as NS from batchflow.research import Alias, Option, Domain ###Output _____no_output_____ ###Markdown Basic usage `Domain` is a class to define domain of parameters. In the simplest case, it is for parameter name and values that will be used in a `Research`. Values for the parameter can be defined as array or [`Sampler`](https://analysiscenter.github.io/batchflow/api/batchflow.sampler.html). ###Code domain = Domain(p=['v1', 'v2']) ###Output _____no_output_____ ###Markdown Each instance of `Domain` class has attribute `iterator` which produces configs from the domain. ###Code list(domain.iterator) ###Output _____no_output_____ ###Markdown All configs from domain have several additional keys: `'repetition'` and `'updates'`. The first one defines the serial number of the repetition for the config (see `n_reps` below). The key `'updates'` defines the number of domain updates before getting of the current config (see `set_update` [documentation](https://analysiscenter.github.io/batchflow/api/batchflow.research.htmlbatchflow.research.Domain.set_update) and [tutorial 6](https://github.com/analysiscenter/batchflow/blob/research/examples/tutorials/research/06_update_domain.ipynb)) Each item generated by `Domain` is `ConfigAlias` instance: wrapper for `Config` with methods `config` and `alias`. That methods return wrapped `Config` and corresponding dict with `str` representations of values.To set or reset `iterator` use `set_iter` method. It also accepts some parameters that will be described below.If you get attribute `iterator` without `set_iter_params`, firstly it will be called with default parameters. ###Code domain.set_iter_params() config = next(domain.iterator) config.config(), config.alias() ###Output _____no_output_____ ###Markdown `Alias` is used to create `str` representation of each value of the domain because they will be used as folder names and to have more readable representation of configs with non-string values.`Alias` is `__name__` attribute of the value or `str` representation. One can define custom alias by using `Alias` class. ###Code domain = Domain(p=[Alias('v1', 'alias'), NS]) config = next(domain.iterator) print('alias: {:14} value: {}'.format(config.alias()['p'], config.config()['p'])) config = next(domain.iterator) print('alias: {:14} value: {}'.format(config.alias()['p'], config.config()['p'])) ###Output alias: alias value: v1 alias: NumpySampler value: <class 'batchflow.batchflow.sampler.NumpySampler'> ###Markdown You can define the number of times to produce each item of the domain as `n_reps` parameter of `set_iter`. Each produced `ConfigAlias` will have `'repetition'` key. ###Code domain.set_iter_params(n_reps=2) list(domain.iterator) ###Output _____no_output_____ ###Markdown Also you can define `n_iters` parameter to define the number of configs that we will get from `Domain`. By default it is equel to the actual number of unique elements. ###Code domain.set_iter_params(n_items=3, n_reps=2) list(domain.iterator) ###Output _____no_output_____ ###Markdown The period of the repetitions can be defined by `repeat_each` parameter. By default, for array-like parameter values all configs will be genereated one time and then repeated. In the case of samplers `repeat_each=100`. ###Code domain.set_iter_params(n_items=3, n_reps=2, repeat_each=1) list(domain.iterator) ###Output _____no_output_____ ###Markdown Operations MultiplicationThe resulting `Domain` will produce configs from Cartesian product of values. It means that we will get all possible combinations of parameter values. Here and below we will pop `'repetition'` and `'updates'` keys from configs to make cell output simpler except the cases while `n_reps != 1` (by setting `additional=False`). ###Code domain = Option('p1', ['v1', 'v2']) * Option('p2', ['v3', 'v4']) domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown SumPlus unites lists of values. ###Code domain = Option('p1', ['v1', 'v2']) + Option('p2', ['v3', 'v4']) domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown `@` multiplication Result is a scalar product of options. ###Code op1 = Option('p1', ['v1', 'v2']) op2 = Option('p2', ['v3', 'v4']) op3 = Option('p3', ['v5', 'v6']) domain = op1 @ op2 @ op3 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown You also can combine all operations because all of them can be applied to resulting domains. ###Code op1 = Option('p1', ['v1', 'v2']) op2 = Option('p2', ['v3', 'v4']) op3 = Option('p3', list(range(2))) op4 = Option('p4', list(range(3, 5))) domain = (op1 @ op2 + op3) * op4 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown `size` attribute will return the size of resulting domain ###Code print(domain.size) ###Output 8 ###Markdown Note that you will get the total number of produced confgs. For example, if you have one `Option` with two values and `n_iters=5` and `n_reps=2` in `set_iter` then the size will be 10. ###Code domain = Domain(p1=list(range(3))) domain.set_iter_params(n_items=5, n_reps=2) domain.size ###Output _____no_output_____ ###Markdown Options with Samplers Instead of array-like options you can use `Sampler` instances as `Option` value. Iterator will produce independent samples from domain. ###Code domain = Domain(p1=NS('n')) domain.set_iter_params(n_items=3, additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown If `n_reps > 1` then samples will be repeated. ###Code domain.set_iter_params(n_items=3, n_reps=2, additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown If `set_iter_params` will be called with `n_items=None` then resulting iterator will be infinite. ###Code domain.set_iter_params(n_items=None, additional=False) print('size: ', domain.size) for _ in range(5): print(next(domain.iterator)) ###Output size: None {'p1': '-0.2899207280882731'} {'p1': '0.2600709832908798'} {'p1': '-2.661256482222706'} {'p1': '-1.991252358812105'} {'p1': '0.427651230662582'} ###Markdown `repeat_each` parameter defines how often elements from infinite generator will be repeated (by default, `repeat_each=100`). ###Code domain.set_iter_params(n_items=None, n_reps=2, repeat_each=2) print('Domain size: {} \n'.format(domain.size)) for _ in range(8): print(next(domain.iterator)) ###Output Domain size: None {'p1': '2.5545455103045875', 'repetition': '0', 'updates': '0'} {'p1': '-2.256729995007879', 'repetition': '0', 'updates': '0'} {'p1': '2.5545455103045875', 'repetition': '1', 'updates': '0'} {'p1': '-2.256729995007879', 'repetition': '1', 'updates': '0'} {'p1': '-0.05577228813667809', 'repetition': '0', 'updates': '0'} {'p1': '0.17618486668664568', 'repetition': '0', 'updates': '0'} {'p1': '-0.05577228813667809', 'repetition': '1', 'updates': '0'} {'p1': '0.17618486668664568', 'repetition': '1', 'updates': '0'} ###Markdown If one multiply array-like options and sampler options, resulting iterator will produce combinations of array-like options with independent sampler from sampler options. ###Code domain = Option('p1', NS('n')) * Option('p2', NS('u')) * Option('p3', [1, 2, 3]) domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown Domains with Weights By default configs are consequently produced from option in a sum from the left to the right. ###Code op1 = Option('p1', ['v1', 'v2']) op2 = Option('p2', ['v3', 'v4']) op3 = Option('p3', ['v5', 'v6']) domain = op1 + op2 + op3 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown To sample options from sum independently with some probabilities you can multiply corresponding options by float. ###Code domain = 0.3 * op1 + 0.2 * op2 + 0.5 * op3 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown If you sum options with and without weights,* they are grouped into consequent groups where all options has or not weights,* consequently for each group configs are generated consequently (for groups with weights) or sampled as described above. ###Code domain = op1 + 1.0 * op2 + 1.0 * op3 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown Thus, we firstly get all configs from `op1`, then configs uniformly sampled from `op2` and `op3`. Obviously, if we define some weight too large, firstly we get all samples from corresponding option. ###Code domain = op1 + 1.0 * op2 + 100.0 * op3 domain.set_iter_params(additional=False) list(domain.iterator) ###Output _____no_output_____ ###Markdown Consider more dificult situation. We will get* all configs from `options[0]`* configs will be sampled from `1.2 * options[1] + 2.3 * options[2]`* all configs from `options[3]`* configs will be sampled from `1.7 * options[4] + 3.4 * options[5]` ###Code options = [Option('p'+str(i), ['v'+str(i)]) for i in range(6)] domain = options[0] + 1.2 * options[1] + 2.3 * options[2] + options[3] + 1.7 * options[4] + 3.4 * options[5] domain.set_iter_params(12, additional=False) list(domain.iterator) ###Output _____no_output_____
Taylor-Swift-Demo.ipynb
###Markdown Taylor Swift Song Matching Demo First, import the packages you'll need If you don't have numpy, you'll need to get it, but it should come with most standard python packages. ###Code from taylorswift import * ###Output _____no_output_____ ###Markdown Then run the code! The example below demonstrates the author's representation of their relationship with the James Webb Space Telescope. When you run the code, you'll be able to input your own answers and get your own personalized song list based on the details of your relationship. ###Code taylorswift() ###Output For these first four questions, if you are in a relationship, answer them with respect to your current relationship. If you are not currently in a relationship, answer them by considering either your most recent past relationship, or a potential relationship on the horizon, whichever you prefer. Which of these best describes your relationship? 1 - Our relationship ended because of cataclysmic past offenses. OR Our relationship has some serious problems. 2 - My feelings were a bit hurt when our relationship ended. OR Our relationship is going ok but has some problems. 3 - Our relationship ended, but not in a horribly bad way. It just ended. OR I feel pretty mediocre about the quality of our relationship. 4 - I wish I was in a relationship, but I don't think it will happen right now. OR I'm happy without a relationship right now. 5 - My relationship is pretty casual at the moment, not official or anything. OR I look back fondly on my past relationship, without feeling hurt or angry. 6 - My relationship is going well and we're thinking about long-term commitment. 7 - I'm getting married and/or comitting to this relationship for the rest of my life.
work/ch08/ch08.ipynb
###Markdown Chapter 8 Attention 1. Attentionの仕組み1. Attention付きseq2seqの実装1. Attentionの評価1. Attentionに関する残りのテーマ1. Attentionの応用1. まとめ Attentionレイヤの実装 ###Code import sys sys.path.append('..') from common.np import * # import numpy as np from common.layers import Softmax class WeightSum: def __init__(self): self.params, self.grads = [], [] self.cache = None def forward(self, hs, a): N, T, H = hs.shape ar = a.reshape(N, T, 1)#.repeat(T, axis=1) t = hs * ar c = np.sum(t, axis=1) self.cache = (hs, ar) return c def backward(self, dc): hs, ar = self.cache N, T, H = hs.shape dt = dc.reshape(N, 1, H).repeat(T, axis=1) dar = dt * hs dhs = dt * ar da = np.sum(dar, axis=2) return dhs, da class AttentionWeight: def __init__(self): self.params, self.grads = [], [] self.softmax = Softmax() self.cache = None def forward(self, hs, h): N, T, H = hs.shape hr = h.reshape(N, 1, H)#.repeat(T, axis=1) t = hs * hr s = np.sum(t, axis=2) a = self.softmax.forward(s) self.cache = (hs, hr) return a def backward(self, da): hs, hr = self.cache N, T, H = hs.shape ds = self.softmax.backward(da) dt = ds.reshape(N, T, 1).repeat(H, axis=2) dhs = dt * hr dhr = dt * hs dh = np.sum(dhr, axis=1) return dhs, dh class Attention: def __init__(self): self.params, self.grads = [], [] self.attention_weight_layer = AttentionWeight() self.weight_sum_layer = WeightSum() self.attention_weight = None def forward(self, hs, h): a = self.attention_weight_layer.forward(hs, h) out = self.weight_sum_layer.forward(hs, a) self.attention_weight = a return out def backward(self, dout): dhs0, da = self.weight_sum_layer.backward(dout) dhs1, dh = self.attention_weight_layer.backward(da) dhs = dhs0 + dhs1 return dhs, dh class TimeAttention: def __init__(self): self.params, self.grads = [], [] self.layers = None self.attention_weights = None def forward(self, hs_enc, hs_dec): N, T, H = hs_dec.shape out = np.empty_like(hs_dec) self.layers = [] self.attention_weights = [] for t in range(T): layer = Attention() out[:, t, :] = layer.forward(hs_enc, hs_dec[:,t,:]) self.layers.append(layer) self.attention_weights.append(layer.attention_weight) return out def backward(self, dout): N, T, H = dout.shape dhs_enc = 0 dhs_dec = np.empty_like(dout) for t in range(T): layer = self.layers[t] dhs, dh = layer.backward(dout[:, t, :]) dhs_enc += dhs dhs_dec[:,t,:] = dh return dhs_enc, dhs_dec ###Output _____no_output_____ ###Markdown Attention付きseq2seqの実装 ###Code import sys sys.path.append('..') from common.time_layers import * from ch07.seq2seq import Encoder, Seq2seq class AttentionEncoder(Encoder): def forward(self, xs): xs = self.embed.forward(xs) hs = self.lstm.forward(xs) return hs def backward(self, dhs): dout = self.lstm.backward(dhs) dout = self.embed.backward(dout) return dout class AttentionDecoder: def __init__(self, vocab_size, wordvec_size, hidden_size): V, D, H = vocab_size, wordvec_size, hidden_size rn = np.random.randn embed_W = (rn(V, D) / 100).astype('f') lstm_Wx = (rn(D, 4 * H) / np.sqrt(D)).astype('f') lstm_Wh = (rn(H, 4 * H) / np.sqrt(H)).astype('f') lstm_b = np.zeros(4 * H).astype('f') affine_W = (rn(2*H, V) / np.sqrt(2*H)).astype('f') affine_b = np.zeros(V).astype('f') self.embed = TimeEmbedding(embed_W) self.lstm = TimeLSTM(lstm_Wx, lstm_Wh, lstm_b, stateful=True) self.attention = TimeAttention() self.affine = TimeAffine(affine_W, affine_b) layers = [self.embed, self.lstm, self.attention, self.affine] self.params, self.grads = [], [] for layer in layers: self.params += layer.params self.grads += layer.grads def forward(self, xs, enc_hs): h = enc_hs[:,-1] self.lstm.set_state(h) out = self.embed.forward(xs) dec_hs = self.lstm.forward(out) c = self.attention.forward(enc_hs, dec_hs) out = np.concatenate((c, dec_hs), axis=2) score = self.affine.forward(out) return score def backward(self, dscore): dout = self.affine.backward(dscore) N, T, H2 = dout.shape H = H2 // 2 dc, ddec_hs0 = dout[:,:,:H], dout[:,:,H:] denc_hs, ddec_hs1 = self.attention.backward(dc) ddec_hs = ddec_hs0 + ddec_hs1 dout = self.lstm.backward(ddec_hs) dh = self.lstm.dh denc_hs[:, -1] += dh self.embed.backward(dout) return denc_hs def generate(self, enc_hs, start_id, sample_size): sampled = [] sample_id = start_id h = enc_hs[:, -1] self.lstm.set_state(h) for _ in range(sample_size): x = np.array([sample_id]).reshape((1, 1)) out = self.embed.forward(x) dec_hs = self.lstm.forward(out) c = self.attention.forward(enc_hs, dec_hs) out = np.concatenate((c, dec_hs), axis=2) score = self.affine.forward(out) sample_id = np.argmax(score.flatten()) sampled.append(sample_id) return sampled class AttentionSeq2seq(Seq2seq): def __init__(self, vocab_size, wordvec_size, hidden_size): args = vocab_size, wordvec_size, hidden_size self.encoder = AttentionEncoder(*args) self.decoder = AttentionDecoder(*args) self.softmax = TimeSoftmaxWithLoss() self.params = self.encoder.params + self.decoder.params self.grads = self.encoder.grads + self.decoder.grads ###Output _____no_output_____ ###Markdown Attention付きseq2seqの学習 ###Code import numpy as np import matplotlib.pyplot as plt from dataset import sequence from common.optimizer import Adam from common.trainer import Trainer from common.util import eval_seq2seq from ch07.seq2seq import Seq2seq from ch07.peeky_seq2seq import PeekySeq2seq # データの読み込み (x_train, t_train), (x_test, t_test) = sequence.load_data('date.txt') char_to_id, id_to_char = sequence.get_vocab() # 入力文を反転 x_train, x_test = x_train[:, ::-1], x_test[:, ::-1] # ハイパーパラメータの設定 vocab_size = len(char_to_id) wordvec_size = 16 hidden_size = 256 batch_size = 128 max_epoch = 10 max_grad = 5.0 model = AttentionSeq2seq(vocab_size, wordvec_size, hidden_size) # model = Seq2seq(vocab_size, wordvec_size, hidden_size) # model = PeekySeq2seq(vocab_size, wordvec_size, hidden_size) optimizer = Adam() trainer = Trainer(model, optimizer) acc_list = [] for epoch in range(max_epoch): trainer.fit(x_train, t_train, max_epoch=1, batch_size=batch_size, max_grad=max_grad) correct_num = 0 for i in range(len(x_test)): question, correct = x_test[[i]], t_test[[i]] verbose = i < 10 correct_num += eval_seq2seq(model, question, correct, id_to_char, verbose, is_reverse=True) acc = float(correct_num) / len(x_test) acc_list.append(acc) print('val acc %.3f%%' % (acc * 100)) model.save_params() # グラフの描画 x = np.arange(len(acc_list)) plt.plot(x, acc_list, marker='o') plt.xlabel('epochs') plt.ylabel('accuracy') plt.ylim(-0.05, 1.05) plt.show() ###Output | epoch 1 | iter 1 / 351 | time 1[s] | loss 4.08 ###Markdown Attentionの可視化 ###Code from dataset import sequence import matplotlib.pyplot as plt (x_train, t_train), (x_test, t_test) = \ sequence.load_data('date.txt') char_to_id, id_to_char = sequence.get_vocab() # Reverse input x_train, x_test = x_train[:, ::-1], x_test[:, ::-1] vocab_size = len(char_to_id) wordvec_size = 16 hidden_size = 256 model = AttentionSeq2seq(vocab_size, wordvec_size, hidden_size) model.load_params() _idx = 0 def visualize(attention_map, row_labels, column_labels): fig, ax = plt.subplots() ax.pcolor(attention_map, cmap=plt.cm.Greys_r, vmin=0.0, vmax=1.0) ax.patch.set_facecolor('black') ax.set_yticks(np.arange(attention_map.shape[0])+0.5, minor=False) ax.set_xticks(np.arange(attention_map.shape[1])+0.5, minor=False) ax.invert_yaxis() ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(column_labels, minor=False) global _idx _idx += 1 plt.show() np.random.seed(1984) for _ in range(5): idx = [np.random.randint(0, len(x_test))] x = x_test[idx] t = t_test[idx] model.forward(x, t) d = model.decoder.attention.attention_weights d = np.array(d) attention_map = d.reshape(d.shape[0], d.shape[2]) # reverse for print attention_map = attention_map[:,::-1] x = x[:,::-1] row_labels = [id_to_char[i] for i in x[0]] column_labels = [id_to_char[i] for i in t[0]] column_labels = column_labels[1:] visualize(attention_map, row_labels, column_labels) ###Output _____no_output_____
2-supervised_learning.ipynb
###Markdown Synthetic Dataset ###Code import numpy as np import matplotlib.pyplot as plt import mglearn # Generate Dataset for Classification X, y = mglearn.datasets.make_forge() # Plot Dataset mglearn.discrete_scatter(X[:,0],X[:,1],y) plt.legend(['Class 0', "Class 1"], loc=4) plt.xlabel("Feature 1") plt.ylabel("Feature 2") print("X.shape: {}".format(X.shape)) # Generate Dataset for Regression X, y = mglearn.datasets.make_wave(n_samples=40) plt.plot(X,y,'o') plt.ylim(-3,3) plt.xlabel("Feature") plt.ylabel("Target") ###Output _____no_output_____ ###Markdown Real World Dataset ###Code # Data for Classification - Cancer from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() print("Cancer Keys: {}".format(cancer.keys())) print("Shape of the cancer.data: {}".format(cancer.data.shape)) print("Sample Counts per class: {}".format({n: v for n,v in zip(cancer.target_names, np.bincount(cancer.target))})) print("Features {}".format(cancer.feature_names)) print(cancer.DESCR +"\n") # Data for Regression - Boston Housing from sklearn.datasets import load_boston boston = load_boston() print("Data Shape: {}".format(boston.data.shape)) print(boston.DESCR +"\n") # Extending the features using Feature Engineering X, y = mglearn.datasets.load_extended_boston() print("X.shape: {}".format(X.shape)) ###Output X.shape: (506, 104) ###Markdown **K-Nearest Neighbors** ###Code # Plotting the basic knn with 1 nearest neighbor mglearn.plots.plot_knn_classification(n_neighbors=1) # with k nearest neighbors mglearn.plots.plot_knn_classification(n_neighbors=3) # Performing kNN using scikit-learn from sklearn.model_selection import train_test_split X, y = mglearn.datasets.make_forge() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=3) clf.fit(X_train, y_train) print("Test set pred: {}".format(clf.predict(X_test))) # Evaluate the performance of the model print("Test Set Accuracy: {:.2f}".format(clf.score(X_test, y_test))) # Visualizing the prediction fig, axes = plt.subplots(1,3, figsize=(10,3)) for n_neighbors, ax in zip([1,3,9], axes): # Instantiate and fit in a single line clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X,y) mglearn.plots.plot_2d_separator(clf, X, fill=True, eps=0.5, ax=ax, alpha=0.4) mglearn.discrete_scatter(X[:,0], X[:,1], y, ax=ax) ax.set_title("{} neighbors".format(n_neighbors)) ax.set_xlabel("feature 0") ax.set_ylabel("feature 1") axes[0].legend(loc=3) # fitting kNN to a real dataset classification from sklearn.datasets import load_breast_cancer # Load and split the data cancer = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify=cancer.target, random_state=42) # Fitting and scoring using diff neighbors training_accuracy = [] test_accuracy = [] n_neighbors = range(1,11) # Using ranges of values for neighbors for n_neighbor in n_neighbors: clf = KNeighborsClassifier(n_neighbors=n_neighbor).fit(X_train, y_train) training_accuracy.append(clf.score(X_train, y_train)) test_accuracy.append(clf.score(X_test, y_test)) plt.plot(n_neighbors, training_accuracy, label="training accuracy") plt.plot(n_neighbors, test_accuracy, label="test accuracy") plt.xlabel("n_neighbors") plt.ylabel("Accuracy") plt.legend() # Regression using kNN mglearn.plots.plot_knn_regression(n_neighbors=1) # for more no of neighbors it takes the avg or mean of the target variables mglearn.plots.plot_knn_regression(n_neighbors=3) # Fitting kNN to the sample data wave from sklearn.neighbors import KNeighborsRegressor X, y = mglearn.datasets.make_wave(n_samples=40) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) reg = KNeighborsRegressor(n_neighbors=3) reg.fit(X_train, y_train) print("Test set predictions: {}".format(reg.predict(X_test))) print("Test set R^2; {:.2f}".format(reg.score(X_test, y_test))) # Analysis of kNN for regression fig, axes = plt.subplots(1,3, figsize=(15,4)) line = np.linspace(-3,3,1000).reshape(-1,1) # Create 1000 data points, evenly spaced between -3 and 3, and change the shape for n_neighbors, ax in zip([1,3,9], axes): reg = KNeighborsRegressor(n_neighbors=n_neighbors) reg.fit(X_train, y_train) ax.plot(line, reg.predict(line)) ax.plot(X_train, y_train, '^', c=mglearn.cm2(0), markersize=8) ax.plot(X_test, y_test, 'v', c=mglearn.cm2(1), markersize=8) ax.set_title("{} neighbors\n Train Score: {:.2f} Test Score: {:.2f}" .format(n_neighbors, reg.score(X_train, y_train), reg.score(X_test, y_test))) ax.set_xlabel("Feature") ax.set_ylabel("Target") axes[0].legend(["Model predictions", "Training data/target", "Test data/target"], loc='best') ###Output _____no_output_____
01-python/04-CLASES.ipynb
###Markdown **CLASES** ###Code class Nada: pass una_nada = Nada() print(una_nada) print(type(una_nada)) class Auto: color = None # Declaración atributo Público __numero_chasis = 1 # Declaración atributo Privado def __init__(self, color): # Constructor print("Empezo el Constructor") # Self = this, debe ser declarado self.color = color nuevo_auto = Auto("Rosado") print(nuevo_auto.color) class Auto: color = None # Atributos Públicos __numero_chasis = 1 # Atributos Privados def __init__(self, color): # Constructor self = this print("Empezo el Constructor") self.color = color def setear_chasis(self, nuevo_chasis): # Métodos Pública self.__numero_chasis = nuevo_chasis return self.__calculo_chasis() # Devuelve Método Privado def __calculo_chasis(self): # Métodos Privado return self.__numero_chasis * 1.17 nuevo_auto = Auto("Rosado") print(nuevo_auto.color) print(nuevo_auto.setear_chasis(100)) class Auto: color = None # Atributos Públicos __numero_chasis = 1 # Atributos Privados def __init__(self, color): # Constructor self = this print("Empezo el Constructor") self.color = color def setear_chasis(self, nuevo_chasis): # Métodos Pública self.__numero_chasis = nuevo_chasis return self.__calculo_chasis() # Devuelve Método Privado def __calculo_chasis(self): # Métodos Privado return self.__numero_chasis * 1.17 def __str__(self): # To String - Sobreescribir parte_uno = f"Color: {self.color} \n" parte_dos = f"Numero Chasis: {self.__numero_chasis}" return parte_uno + parte_dos nuevo_auto = Auto("Rosado") #print(nuevo_auto.color) print(nuevo_auto.setear_chasis(100)) print(nuevo_auto) # Heredar Clase class BMW(Auto): def __init__(self, color, chasis): print("Iniciar constructor hijo") super().__init__(color) # Llamar Constructor Padre super().setear_chasis(chasis) # Llamar a Método nuevo_bmw = BMW("Blanco", 150) print(nuevo_bmw) ###Output Iniciar constructor hijo Empezo el Constructor Color: Blanco Numero Chasis: 150
Implementations/FY21/ACC_GTFS_accessibility_analysis_Cap_Haitien_Haiti/Step1_build_graph_and_add_ferries2_w_adv_snap.ipynb
###Markdown Step 1: Extract and merge walk graph and ferries graphExtract the walk network via OSMNX within the AOI, and then add ferries to the network ###Code %load_ext autoreload %autoreload 2 import osmnx as ox import pandas as pd import geopandas as gpd import networkx as nx import numpy as np from shapely.geometry import Point import os, sys sys.path.append(r'C:\repos\GOSTnets') import GOSTnets as gn # configuring ferry as a useful tag ox.utils.config(useful_tags_way= [ "bridge", "tunnel", "oneway", "lanes", "ref", "name", "highway", "maxspeed", "service", "access", "area", "landuse", "width", "est_width", "junction", "ferry" ]) ###Output _____no_output_____ ###Markdown Extract Walk network via OSMNX ###Code # import extent cap_haitian_extent = gpd.read_file(r"input_folder/cap_haitien_study_area_w_buffer.shp") extent = cap_haitian_extent.geometry[0] extent # Pull in the walk network with OSMnx %time Gwalk = ox.graph_from_polygon(extent, network_type='walk') #Gwalk.graph # Visually inspect (takes a minute or two) ox.plot_graph(Gwalk) ###Output _____no_output_____ ###Markdown Extract Ferries over AOIVisited https://overpass-turbo.eu/ and manually ran a query for ferries (way["ferry"]) within Cap Haitien. Detected the only ferries near Pointe Labadie, so a bounding box was manually created in QGIS that covered all of the ferries. ###Code # import extent cap_haitien_extent = gpd.read_file("input_folder/cap_haitien_ferry_extent.shp") extent = cap_haitien_extent.geometry[0] extent walk_custom = '["ferry"]' # Pull in the walk network with OSMNX %time Gferries = ox.graph_from_polygon(extent, custom_filter=walk_custom) print(nx.info(Gferries)) Gferries Gferries.edges # test Gferries.edges[616085737, 6733460125,0] Gferries.nodes ###Output _____no_output_____ ###Markdown Add ferry nodes and edges to the walking graph ###Code # add each osm node to the graph # even if the node already exists in the graph, it won't create duplicates for node, data in Gferries.nodes.items(): #print(node,data) Gwalk.add_node(node, **data) # add each osm edge to the graph for edge, data in Gferries.edges.items(): print(edge,data) Gwalk.add_edges_from([edge], **data) print(nx.info(Gwalk)) Gwalk.nodes[6770195160] # save again and inspect #gn.save(Gwalk,"cap_haitien_walk_w_ferries_via_osmnx",r"temp") ###Output _____no_output_____ ###Markdown Advanced SnappingNow we want to take our population grid vector points and use them to expand the graph. ###Code # load origins origins = gpd.read_file(r"input_folder\cap_haitien_worldpop_pts2.shp") ###Output _____no_output_____ ###Markdown Make the node_ID really high in order to not interfere with exisiting OSMIDs from the graph ###Code origins['node_ID'] = 1110000000 + origins.index origins # find graph utm zone G_utm = gn.utm_of_graph(Gwalk) G_utm # testing # for edge, data in Gwalk.edges.items(): # print(edge,data) ###Output _____no_output_____ ###Markdown This is the GOSTnets advanced_snap function. note on GOSTnets implementation detail:As of now make sure node_key_col='node_ID' because gn.advanced_snap does node_gdf_from_graph(G) and node_gdf_from_graph has node_ID for the ID column ###Code # example of nodes in Gwalk gn.example_node(Gwalk,n=5) %%time G2, pois_meter, new_footway_edges = gn.advanced_snap(Gwalk, origins, u_tag = 'stnode', v_tag = 'endnode', node_key_col='node_ID', poi_key_col='node_ID', path=None, threshold=2000, measure_crs=G_utm) print(nx.info(G2)) G2_edges = gn.edge_gdf_from_graph(G2) #G2_edges #list(G2.edges(data=True))[:10] ###Output _____no_output_____ ###Markdown save for Step 2 ###Code gn.save(G2,"cap_haitien_walk_w_ferries_via_osmnx_origins_adv_snap",r"temp") # testing #nodes = gn.node_gdf_from_graph(G2) # testing #G2.nodes[6770195160] ###Output _____no_output_____ ###Markdown new_poi_nodes will be used for the origin nodes when calculating an OD matrix ###Code new_footway_edges.head() ###Output _____no_output_____ ###Markdown The edges that were longer than the threshold of 2000m were already eliminated from the new_footway_edges DF, therefore we will eliminate the new_poi_nodes that don't exist in the new_footway_edges ###Code # yields the elements in `list_2` that are NOT in `list_1` elim_new_poi_nodes = np.setdiff1d(list(new_poi_nodes.node_ID),list(new_footway_edges.node_ID)) len(elim_new_poi_nodes) new_poi_nodes2 = new_poi_nodes[~new_poi_nodes['node_ID'].isin(elim_new_poi_nodes)] new_poi_nodes2 new_poi_nodes2 = new_poi_nodes2[['node_ID','VALUE','geometry']] # save new_nodes new_poi_nodes2.to_csv(r"temp/origin_nodes.csv") ###Output _____no_output_____ ###Markdown Inspecting disconnected subgraphs ###Code # compatible with NetworkX 2.4 list_of_subgraphs = list(G2.subgraph(c).copy() for c in nx.weakly_connected_components(G2)) max_graph = None max_edges = 0 # To sort the list in place... list_of_subgraphs.sort(key=lambda x: x.number_of_edges(), reverse=True) for subgraph in list_of_subgraphs: print(len(subgraph)) # to inspect gn.save(subgraph,f"{len(subgraph)}_inspect",r"temp", pickle = False, edges = True, nodes = False) ###Output 267226
Code/8.1-MultinomialLogitAndProbitModels/01-biogeme-basics.ipynb
###Markdown An introduction to Biogeme Biogeme Basics: Logit Model ###Code import pandas as pd import numpy as np import biogeme.database as db import biogeme.biogeme as bio import biogeme.models as models import biogeme.expressions as exp import seaborn as sns import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown **Import Swissmetro data** ###Code pandas = pd.read_csv("../../Data/6-Discrete Choice Models/swissmetro.dat",sep='\t') database = db.Database("data/swissmetro", pandas) ###Output _____no_output_____ ###Markdown Let's see what this dataset has * dataset consists of survey data collected on the trains between St. Gallen and Geneva, Switzerland, during March 1998* It is necessary to obtain data from surveys of hypothetical markets/situations, which include the innovation, to assess the impact. * Survey data were collected on rail-based travels, interviewing 470 respondents. Due to data problems, only 441 are used here. A similar method for relevant car trips. A total of 1070 persons filled in the survey completely and were willing to participate in the second SP survey, which was generated using the same approach used for the rail interviews. 750 usable SP surveys were returned, from the license-plate based survey.* Nine stated choice situations were generated for each the respondents, offering three alternatives: rail, Swissmetro and carBierlaire, M., Axhausen, K. and Abay, G. (2001), The acceptance of modal innovation: The case of Swissmetro, in ‘Proceedings of the Swiss Transport Research Conference’, Ascona, Switzerland. ![](img/swissmetro_var1.png) ![](img/swissmetro_var2.png) ###Code plt.figure(figsize=(10,5)) chart = sns.countplot(pandas['PURPOSE']) chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right'); chart.set_xticklabels(['Commuter', 'Shopping', 'Business', 'Leisure', 'Return from work','Return from shopping', 'Return from business','Return from leisure','Other']); ###Output _____no_output_____ ###Markdown **Use collumn names as variables** ###Code globals().update(database.variables) ###Output _____no_output_____ ###Markdown **Exclude some unwanted entries** ###Code exclude = (( PURPOSE != 1 ) * ( PURPOSE != 3 ) + ( CHOICE == 0 )) > 0 database.remove(exclude) ###Output _____no_output_____ ###Markdown **Define some dummy variables** ###Code SM_COST = SM_CO * ( GA == 0 ) TRAIN_COST = TRAIN_CO * ( GA == 0 ) CAR_AV_SP = exp.DefineVariable ('CAR_AV_SP', CAR_AV * ( SP !=0 ), database) TRAIN_AV_SP = exp.DefineVariable ('TRAIN_AV_SP', TRAIN_AV * ( SP != 0 ), database) ###Output _____no_output_____ ###Markdown **Rescale some data** ###Code TRAIN_TT_SCALED = exp.DefineVariable('TRAIN_TT_SCALED', TRAIN_TT / 100.0, database) TRAIN_COST_SCALED = exp.DefineVariable('TRAIN_COST_SCALED', TRAIN_COST / 100, database) SM_TT_SCALED = exp.DefineVariable('SM_TT_SCALED', SM_TT / 100.0 , database) SM_COST_SCALED = exp.DefineVariable('SM_COST_SCALED', SM_COST / 100 , database) CAR_TT_SCALED = exp.DefineVariable('CAR_TT_SCALED', CAR_TT / 100 , database) CAR_CO_SCALED = exp.DefineVariable('CAR_CO_SCALED', CAR_CO / 100 , database) pandas = database.data plt.figure(figsize=(10,5)) chart = sns.countplot(pandas['PURPOSE']) chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right'); chart.set_xticklabels(['Commuter', 'Business']); plt.figure(1, figsize=(10,5)) chart = sns.countplot(pandas['TRAIN_AV']) chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right'); chart.set_xticklabels(['Yes']); chart.set(title='Train Availability', xlabel="Available", ylabel = "Count"); plt.figure(2, figsize=(10,5)) chart = sns.countplot(pandas['CAR_AV']) chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right'); chart.set_xticklabels(['No', 'Yes']); chart.set(title='Car Availability', xlabel="Available", ylabel = "Count"); plt.figure(3, figsize=(10,5)) chart = sns.countplot(pandas['SM_AV']) chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right'); chart.set_xticklabels(['Yes']); chart.set(title='Swissmetro Availability', xlabel="Available", ylabel = "Count"); pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) pandas.describe() ###Output _____no_output_____ ###Markdown **Define the utility functions** \begin{align}V_1 & = \beta_{Train} + \beta_{time}X_{Train_{TT}} + \beta_{cost}X_{Train_{cost}}\\V_2 & = \beta_{SM} + \beta_{time}X_{SM_{TT}} + \beta_{cost}X_{SM_{cost}}\\V_3 & = \beta_{Car} + \beta_{time}X_{Car_{TT}} + \beta_{cost}X_{Car_{cost}}\\\end{align} **Create parameters to be estimated**`Beta`1. name of parameter2. default value for the parameter3. lower bound4. upper bound5. flag indicating if parameter is to be estimated ###Code ASC_CAR = exp.Beta('ASC_CAR',0,None ,None ,0) ASC_TRAIN = exp.Beta('ASC_TRAIN',0,None ,None ,0) ASC_SM = exp.Beta('ASC_SM',0,None ,None ,1) B_TIME = exp.Beta('B_TIME',0,None ,None ,0) B_COST = exp.Beta('B_COST',0,None ,None ,0) ###Output _____no_output_____ ###Markdown **Define the utility functions** ###Code V1 = ASC_TRAIN + \ B_TIME * TRAIN_TT_SCALED + \ B_COST * TRAIN_COST_SCALED V2 = ASC_SM + \ B_TIME * SM_TT_SCALED + \ B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME * CAR_TT_SCALED + \ B_COST * CAR_CO_SCALED ###Output _____no_output_____ ###Markdown **Associate utility functions with alternatives and associate availability of alternatives**Create a python dictionary with all utility functionsCreate a python dictionary with availability of choices ###Code V = {1: V1, 2: V2, 3: V3} av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} ###Output _____no_output_____ ###Markdown **Define the model** ###Code logprob = models.loglogit(V, av, CHOICE) ###Output _____no_output_____ ###Markdown **Define the Biogeme object*** Give the database with all variables* Give the log likelihood model ###Code biogeme = bio.BIOGEME(database, logprob) biogeme.modelName = "swissmetro_logit_basic" ###Output _____no_output_____ ###Markdown **Estimate the model**1. A `.html` can be generated with a report of the results and can be opened with a browser2. A `.pickle` file can also be generaetd with a snapshot with the results. This file can then be used in other scripts ###Code biogeme.generateHtml = True biogeme.generatePickle = False results = biogeme.estimate() print(f"HTML file: {results.data.htmlFileName}") print(f"Pickle file: {results.data.pickleFileName }") ###Output HTML file: swissmetro_logit_basic.html Pickle file: None ###Markdown **Print results** ###Code betas = results.getBetaValues() for k,v in betas.items(): print(f"{k:10}=\t{v:.3g}") ###Output ASC_CAR = -0.155 ASC_TRAIN = -0.701 B_COST = -1.08 B_TIME = -1.28 ###Markdown **Get the variance-covariance matrix** ###Code results.getVarCovar() ###Output _____no_output_____
.ipynb_checkpoints/NB5_check_brain_heart_expression_210419-checkpoint.ipynb
###Markdown Check the brain and heart expression of network genesRequires downloading GTEX data (https://gtexportal.org/home/datasets). Large files ###Code import numpy as np import matplotlib.pyplot as plt import seaborn as sns import networkx as nx import pandas as pd import random # latex rendering of text in graphs import matplotlib as mpl mpl.rc('text', usetex = False) mpl.rc('font', family = 'serif') from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Arial'] sns.set_style('white') sns.set_style("ticks", {"xtick.major.size": 15, "ytick.major.size": 15}) plt.rcParams['svg.fonttype'] = 'none' import sys % matplotlib inline ###Output _____no_output_____ ###Markdown Load the ASD-CHD network genes ###Code ASD_CHD_df = pd.read_excel('data/supplemental_tables_cell_systems_210416.xlsx',sheet_name='Table S4',skiprows=1) ASD_CHD_df.index=ASD_CHD_df['gene'] print(len(ASD_CHD_df)) display(ASD_CHD_df.head()) ASD_CHD_genes = ASD_CHD_df.index.tolist() len(ASD_CHD_genes) ###Output _____no_output_____ ###Markdown Load Gtex sample metadataFilter by brain, heart samples, so we don't have to load full GTEX ###Code gtex_meta = pd.read_csv('/Users/brinrosenthal/Documents/CCBB_tickets_data/GTEX/RNAseq/GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt', sep='\t') gtex_meta.index=gtex_meta['SAMPID'] gtex_meta.head() gtex_meta_brain_heart = gtex_meta[gtex_meta['SMTS'].isin(['Brain','Heart'])] print(len(gtex_meta_brain_heart)) gtex_samps_keep = gtex_meta_brain_heart.index.tolist() gtex_meta_brain_heart['SMTS'].value_counts() gtex_meta['SMTS'].value_counts() ###Output _____no_output_____ ###Markdown Try just reading the whole fileThis chunk is parsing GTEX file... skip to next section if we don't need to do this. Can just read in exp_brain_heart protein coding ###Code # Skip to read in exp_gtex_brain_heart if pre-computed exp_gtex_df = pd.read_csv('/Users/brinrosenthal/Documents/CCBB_tickets_data/GTEX/RNAseq/GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_reads.gct.gz', sep='\t',skiprows=2) exp_gtex_df.head() gtex_samps_keep = list(np.intersect1d(gtex_samps_keep,exp_gtex_df.columns.tolist())) print(len(gtex_samps_keep)) exp_gtex_brain_heart = exp_gtex_df[['Description']+gtex_samps_keep] exp_gtex_brain_heart.head() # drop the duplicate gene names print(len(exp_gtex_brain_heart)) exp_gtex_brain_heart=exp_gtex_brain_heart.drop_duplicates(subset='Description') print(len(exp_gtex_brain_heart)) # exp_gtex_brain_heart.to_csv('/Users/brin/Documents/CCBB_tickets_data/GTEX/RNAseq/GTEX_counts_brain_heart.txt',sep='\t') ###Output _____no_output_____ ###Markdown Load the interactomePCnet downloaded from ndex and parsed to networkx format https://ndexbio.org//network/f93f402c-86d4-11e7-a10d-0ac135e8bacf ###Code # filter by protein coding genes in PCnet G_pcnet = nx.read_gpickle('/Users/brinrosenthal/Documents/CCBB_tickets_data/PCnet/G_PCnet.gpickle') print(len(G_pcnet.nodes())) print(len(G_pcnet.edges())) genes_gtex_pcnet=list(np.intersect1d(exp_gtex_brain_heart.index.tolist(),G_pcnet.nodes())) print(len(genes_gtex_pcnet)) exp_gtex_brain_heart.index=exp_gtex_brain_heart['Description'] exp_gtex_brain_heart = exp_gtex_brain_heart.loc[genes_gtex_pcnet] print(len(exp_gtex_brain_heart)) exp_gtex_brain_heart.head() # save the protein coding (also pcnet) genes # exp_gtex_brain_heart.to_csv('/Users/brin/Documents/CCBB_tickets_data/GTEX/RNAseq/GTEX_counts_brain_heart_pc.txt',sep='\t') ###Output _____no_output_____ ###Markdown Load the filtered GTEX brain, heart, other tissues exp data ###Code exp_gtex_brain_heart = pd.read_csv('/Users/brinrosenthal/Documents/CCBB_tickets_data/GTEX/RNAseq/GTEX_counts_brain_heart_pc.txt', sep='\t',) exp_gtex_brain_heart.index=exp_gtex_brain_heart['Description'] exp_gtex_brain_heart = exp_gtex_brain_heart[exp_gtex_brain_heart.columns.tolist()[2:]] exp_gtex_brain_heart.head() # normalize expression by sample (convert to counts per million) cpm_gtex_brain_heart = exp_gtex_brain_heart.copy(deep=True) cpm_gtex_brain_heart = cpm_gtex_brain_heart.divide(exp_gtex_brain_heart.sum())*1000000 cpm_gtex_brain_heart.head() # now calculate the average tissue-specific expression brain_samps = list(np.intersect1d(gtex_meta_brain_heart[gtex_meta_brain_heart['SMTS']=='Brain'].index.tolist(), cpm_gtex_brain_heart.columns.tolist())) print(len(brain_samps)) heart_samps = list(np.intersect1d(gtex_meta_brain_heart[gtex_meta_brain_heart['SMTS']=='Heart'].index.tolist(), cpm_gtex_brain_heart.columns.tolist())) print(len(heart_samps)) cpm_gtex_brain = cpm_gtex_brain_heart[brain_samps] cpm_gtex_brain.head() cpm_gtex_heart = cpm_gtex_brain_heart[heart_samps] cpm_gtex_heart.head() gtex_brain_avg_exp = cpm_gtex_brain.mean(axis=1) gtex_brain_avg_exp.head() gtex_heart_avg_exp = cpm_gtex_heart.mean(axis=1) gtex_heart_avg_exp.head() # sns.jointplot(gtex_heart_avg_exp.loc[ASD_CHD_genes],gtex_brain_avg_exp.loc[ASD_CHD_genes]) gtex_multi_tissue_avg_prank = pd.DataFrame(gtex_heart_avg_exp.rank(pct=True), columns=['heart_prank']).join(pd.DataFrame(gtex_brain_avg_exp.rank(pct=True), columns=['brain_prank'])) gtex_multi_tissue_avg_prank.head() gtex_multi_tissue_avg_prank.loc[['MYT1L','TBR1','CAPN12','TBL1XR1','AGAP1','HDGFRP2','PNPLA7','SCN2A']] jp = sns.jointplot(x='heart_prank',y='brain_prank',data=gtex_multi_tissue_avg_prank.loc[ASD_CHD_genes], kind='scatter',alpha=.3,color='gray',joint_kws={'s':6},marginal_kws={'color':'white'},height=4.5) plt.sca(jp.ax_marg_x) sns.distplot(gtex_multi_tissue_avg_prank['heart_prank'].loc[ASD_CHD_genes].dropna().tolist(),color='#C410C4',kde=False) plt.sca(jp.ax_marg_y) sns.distplot(gtex_multi_tissue_avg_prank['brain_prank'].loc[ASD_CHD_genes].dropna().tolist(),color='#0ED50A',kde=False,vertical=True) plt.sca(jp.ax_joint) plt.xlabel('GTEX heart percentile expression',fontsize=16) plt.ylabel('GTEX brain percentile expression',fontsize=16) plt.plot([0,1],[.75,.75],'--',color='gray') plt.plot([.75,.75],[0,1],'--',color='gray') # write out brain/heart avg percentile rank for loading to cytoscape # gtex_brain_heart_avg_prank.to_csv('gtex_brain_heart_avg_prank.csv') gtex_multi_tissue_avg_prank.loc[['SCN1A','SCN10A','SMARCA2']] min_brain_heart = gtex_multi_tissue_avg_prank[['brain_prank','heart_prank']].T.min() min_brain_heart.head() plt.figure(figsize=(2.08,1.69)) bins = np.linspace(0,1,11) dfig = sns.distplot(min_brain_heart,bins=bins,color='gray',label='all expressed genes') sns.distplot(min_brain_heart.loc[ASD_CHD_genes].dropna(),bins=bins,color='#FF7400',label='$z_{ASD-CHD}>3$') plt.xlim([0,1]) plt.xticks(np.linspace(0,1,6)) from scipy.stats import mannwhitneyu print(mannwhitneyu(min_brain_heart.tolist(),min_brain_heart.loc[ASD_CHD_genes].dropna().tolist())) plt.legend(loc='upper left',fontsize=6,frameon=False) plt.ylabel('density',fontsize=8) plt.xlabel('GTEX min(brain,heart) expression,\npercentile',fontsize=8) plt.xticks(fontsize=8) plt.yticks(fontsize=8) plt.savefig('../../manuscript/figures_1911/Figure4/Figure4_final assets/GTEX_min_brain_heart_dist.png',dpi=300,bbox_inches='tight') plt.savefig('../../manuscript/figures_1911/Figure4/Figure4_final assets/GTEX_min_brain_heart_dist.svg',dpi=300,bbox_inches='tight') # plt.savefig('../../manuscript/figures_1911/Figure4/GTEX_min_brain_heart_dist.pdf',dpi=300,bbox_inches='tight') bins = np.linspace(0,1,11) bins ###Output _____no_output_____
projects/learn-python3/notebooks/beginner/exercises/exceptions_exercise.ipynb
###Markdown 1. Dealing with exceptionsFill `____` parts of the implementation below. `sum_of_list` function takes a list as argument and calculates the sum of values in the list. If some element in the list can not be converted to a numeric value, it should be ignored from the sum. ###Code def sum_of_list(values): sum = 0 for val in values: try: numeric_val = float(val) except: continue sum += numeric_val return sum list1 = [1, 2, 3] list2 = ['1', 2.5, '3.0'] list3 = ['', '1'] list4 = [] list5 = ['John', 'Doe', 'was', 'here'] nasty_list = [KeyError(), [], dict()] assert sum_of_list(list1) == 6 assert sum_of_list(list2) == 6.5 assert sum_of_list(list3) == 1 assert sum_of_list(list4) == 0 assert sum_of_list(list5) == 0 assert sum_of_list(nasty_list) == 0 ###Output _____no_output_____ ###Markdown 2. Using custom exceptionsImplement `verify_short_string` function which takes a single string as argument. If the length of the input string is more than ten characters, the function should raise `TooLongString` exception (note: you have to create `TooLongString` yourself). The function does not have to return anything. ###Code class TooLongString(Exception): pass def verify_short_string(string): if len(string) > 10: raise TooLongString # These should not raise verify_short_string('short') verify_short_string('10 chars') # This should raise try: verify_short_string('this is long') except TooLongString as e: # This is ok pass else: # This means that there was no exception assert False ###Output _____no_output_____
Marian_Vinas_Copy_of_LS_DS_222_assignment.ipynb
###Markdown Lambda School Data Science*Unit 2, Sprint 2, Module 2*--- Random Forests Assignment- [ ] Read [“Adopting a Hypothesis-Driven Workflow”](http://archive.is/Nu3EI), a blog post by a Lambda DS student about the Tanzania Waterpumps challenge.- [ ] Continue to participate in our Kaggle challenge.- [ ] Define a function to wrangle train, validate, and test sets in the same way. Clean outliers and engineer features.- [ ] Try Ordinal Encoding.- [ ] Try a Random Forest Classifier.- [ ] Submit your predictions to our Kaggle competition. (Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. Or you can use the Kaggle API to submit your predictions.)- [ ] Commit your notebook to your fork of the GitHub repo. Stretch Goals Doing- [ ] Add your own stretch goal(s) !- [ ] Do more exploratory data analysis, data cleaning, feature engineering, and feature selection.- [ ] Try other [categorical encodings](https://contrib.scikit-learn.org/category_encoders/).- [ ] Get and plot your feature importances.- [ ] Make visualizations and share on Slack. ReadingTop recommendations in _**bold italic:**_ Decision Trees- A Visual Introduction to Machine Learning, [Part 1: A Decision Tree](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/), and _**[Part 2: Bias and Variance](http://www.r2d3.us/visual-intro-to-machine-learning-part-2/)**_- [Decision Trees: Advantages & Disadvantages](https://christophm.github.io/interpretable-ml-book/tree.htmladvantages-2)- [How a Russian mathematician constructed a decision tree — by hand — to solve a medical problem](http://fastml.com/how-a-russian-mathematician-constructed-a-decision-tree-by-hand-to-solve-a-medical-problem/)- [How decision trees work](https://brohrer.github.io/how_decision_trees_work.html)- [Let’s Write a Decision Tree Classifier from Scratch](https://www.youtube.com/watch?v=LDRbO9a6XPU) Random Forests- [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/), Chapter 8: Tree-Based Methods- [Coloring with Random Forests](http://structuringtheunstructured.blogspot.com/2017/11/coloring-with-random-forests.html)- _**[Random Forests for Complete Beginners: The definitive guide to Random Forests and Decision Trees](https://victorzhou.com/blog/intro-to-random-forests/)**_ Categorical encoding for trees- [Are categorical variables getting lost in your random forests?](https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/)- [Beyond One-Hot: An Exploration of Categorical Variables](http://www.willmcginnis.com/2015/11/29/beyond-one-hot-an-exploration-of-categorical-variables/)- _**[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)**_- _**[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)**_- [Mean (likelihood) encodings: a comprehensive study](https://www.kaggle.com/vprokopev/mean-likelihood-encodings-a-comprehensive-study)- [The Mechanics of Machine Learning, Chapter 6: Categorically Speaking](https://mlbook.explained.ai/catvars.html) Imposter Syndrome- [Effort Shock and Reward Shock (How The Karate Kid Ruined The Modern World)](http://www.tempobook.com/2014/07/09/effort-shock-and-reward-shock/)- [How to manage impostor syndrome in data science](https://towardsdatascience.com/how-to-manage-impostor-syndrome-in-data-science-ad814809f068)- ["I am not a real data scientist"](https://brohrer.github.io/imposter_syndrome.html)- _**[Imposter Syndrome in Data Science](https://caitlinhudon.com/2018/01/19/imposter-syndrome-in-data-science/)**_ More Categorical Encodings**1.** The article **[Categorical Features and Encoding in Decision Trees](https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931)** mentions 4 encodings:- **"Categorical Encoding":** This means using the raw categorical values as-is, not encoded. Scikit-learn doesn't support this, but some tree algorithm implementations do. For example, [Catboost](https://catboost.ai/), or R's [rpart](https://cran.r-project.org/web/packages/rpart/index.html) package.- **Numeric Encoding:** Synonymous with Label Encoding, or "Ordinal" Encoding with random order. We can use [category_encoders.OrdinalEncoder](https://contrib.scikit-learn.org/category_encoders/ordinal.html).- **One-Hot Encoding:** We can use [category_encoders.OneHotEncoder](https://contrib.scikit-learn.org/category_encoders/onehot.html).- **Binary Encoding:** We can use [category_encoders.BinaryEncoder](https://contrib.scikit-learn.org/category_encoders/binary.html).**2.** The short video **[Coursera — How to Win a Data Science Competition: Learn from Top Kagglers — Concept of mean encoding](https://www.coursera.org/lecture/competitive-data-science/concept-of-mean-encoding-b5Gxv)** introduces an interesting idea: use both X _and_ y to encode categoricals.Category Encoders has multiple implementations of this general concept:- [CatBoost Encoder](https://contrib.scikit-learn.org/category_encoders/catboost.html)- [Generalized Linear Mixed Model Encoder](https://contrib.scikit-learn.org/category_encoders/glmm.html)- [James-Stein Encoder](https://contrib.scikit-learn.org/category_encoders/jamesstein.html)- [Leave One Out](https://contrib.scikit-learn.org/category_encoders/leaveoneout.html)- [M-estimate](https://contrib.scikit-learn.org/category_encoders/mestimate.html)- [Target Encoder](https://contrib.scikit-learn.org/category_encoders/targetencoder.html)- [Weight of Evidence](https://contrib.scikit-learn.org/category_encoders/woe.html)Category Encoder's mean encoding implementations work for regression problems or binary classification problems. For multi-class classification problems, you will need to temporarily reformulate it as binary classification. For example:```pythonencoder = ce.TargetEncoder(min_samples_leaf=..., smoothing=...) Both parameters > 1 to avoid overfittingX_train_encoded = encoder.fit_transform(X_train, y_train=='functional')X_val_encoded = encoder.transform(X_train, y_val=='functional')```For this reason, mean encoding won't work well within pipelines for multi-class classification problems.**3.** The **[dirty_cat](https://dirty-cat.github.io/stable/)** library has a Target Encoder implementation that works with multi-class classification.```python dirty_cat.TargetEncoder(clf_type='multiclass-clf')```It also implements an interesting idea called ["Similarity Encoder" for dirty categories](https://www.slideshare.net/GaelVaroquaux/machine-learning-on-non-curated-data-154905090).However, it seems like dirty_cat doesn't handle missing values or unknown categories as well as category_encoders does. And you may need to use it with one column at a time, instead of with your whole dataframe.**4. [Embeddings](https://www.kaggle.com/colinmorris/embedding-layers)** can work well with sparse / high cardinality categoricals._**I hope it’s not too frustrating or confusing that there’s not one “canonical” way to encode categoricals. It’s an active area of research and experimentation — maybe you can make your own contributions!**_ SetupYou can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab (run the code cell below). ###Code %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' import pandas as pd from sklearn.model_selection import train_test_split train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'), pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv')) test = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv') sample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv') train.shape, test.shape import numpy as np # Split train into train & val train, val = train_test_split(train, train_size=0.80, test_size=0.20, stratify=train['status_group'], random_state=42) def wrangle(X): """Wrangle train, validate, and test sets in the same way""" # Prevent SettingWithCopyWarning X = X.copy() # About 3% of the time, latitude has small values near zero, # outside Tanzania, so we'll treat these values like zero. X['latitude'] = X['latitude'].replace(-2e-08, 0) # When columns have zeros and shouldn't, they are like null values. # So we will replace the zeros with nulls, and impute missing values later. # Also create a "missing indicator" column, because the fact that # values are missing may be a predictive signal. cols_with_zeros = ['longitude', 'latitude', 'construction_year', 'gps_height', 'population'] for col in cols_with_zeros: X[col] = X[col].replace(0, np.nan) X[col+'_MISSING'] = X[col].isnull() # Drop duplicate columns duplicates = ['quantity_group', 'payment_type'] X = X.drop(columns=duplicates) # Drop recorded_by (never varies) and id (always varies, random) unusable_variance = ['recorded_by', 'id'] X = X.drop(columns=unusable_variance) # Convert date_recorded to datetime X['date_recorded'] = pd.to_datetime(X['date_recorded'], infer_datetime_format=True) # Extract components from date_recorded, then drop the original column X['year_recorded'] = X['date_recorded'].dt.year X['month_recorded'] = X['date_recorded'].dt.month X['day_recorded'] = X['date_recorded'].dt.day X = X.drop(columns='date_recorded') # Engineer feature: how many years from construction_year to date_recorded X['years'] = X['year_recorded'] - X['construction_year'] X['years_MISSING'] = X['years'].isnull() # return the wrangled dataframe return X train = wrangle(train) val = wrangle(val) test = wrangle(test) # The status_group column is the target target = 'status_group' # Get a dataframe with all train columns except the target train_features = train.drop(columns=[target]) # Get a list of the numeric features numeric_features = train_features.select_dtypes(include='number').columns.tolist() # Get a series with the cardinality of the nonnumeric features cardinality = train_features.select_dtypes(exclude='number').nunique() # Get a list of all categorical features with cardinality <= 50 categorical_features = cardinality[cardinality <= 50].index.tolist() # Combine the lists features = numeric_features + categorical_features # Arrange data into X features matrix and y target vector X_train = train[features] y_train = train[target] X_val = val[features] y_val = val[target] X_test = test[features] #Scikit-Learn import category_encoders as ce from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline pipeline = make_pipeline( ce.one_hot.OneHotEncoder(use_cat_names=True), SimpleImputer(), RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=42) ) pipeline.fit(X_train, y_train) print(f'Validation Accuracy: {pipeline.score(X_val, y_val)}') print(f'X_train before encoding: {X_train.shape}') encoder = pipeline.named_steps['onehotencoder'] X_train_enc = encoder.transform(X_train) print(f'X_train after encoding: {X_train_enc.shape}') import matplotlib.pyplot as plt rf = pipeline.named_steps['randomforestclassifier'] importances = pd.Series(rf.feature_importances_, X_train_enc.columns) n = 20 plt.figure(figsize=(10, n/2)) plt.title(f'Top {n} feature importances') importances.sort_values()[-n:].plot.barh() rf.feature_importances_.shape #Ordinal Encoding %%time X_train = train.drop(columns=target) y_train = train[target] X_val = val.drop(columns=target) y_val = val[target] X_test = test pipeline = make_pipeline( ce.ordinal.OrdinalEncoder(), SimpleImputer(), RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=42) ) pipeline.fit(X_train, y_train) print(f'Validation accuracy: {pipeline.score(X_val, y_val)}') print(f'X_train before encoding: {X_train.shape}') encoder = pipeline.named_steps['ordinalencoder'] X_train_enc = encoder.transform(X_train) print(f'X_train after encoding: {X_train_enc.shape}') rf = pipeline.named_steps['randomforestclassifier'] importances = pd.Series(rf.feature_importances_, X_train_enc.columns) n = 20 plt.figure(figsize=(10, n/2)) plt.title(f'Top {n} feature importances') importances.sort_values()[-n:].plot.barh() #categorical exploration, 1 feature at a time feature = 'extraction_type_class' X_train[feature].value_counts() import seaborn as sns plt.figure(figsize=(16,9)) sns.barplot( x=train[feature], y=train['status_group']=='functional', color='gray' ); X_train[feature].head(20) #One Hot Encoding X_train[[feature]].head() encoder = ce.OneHotEncoder(use_cat_names=True) encoded = encoder.fit_transform(X_train[[feature]]) print(f'{len(encoded.columns)} columns') encoded.head(20) #One-Hot encoding, logistic regression, validation accuracy from sklearn.linear_model import LogisticRegressionCV from sklearn.preprocessing import StandardScaler lr = make_pipeline( ce.OneHotEncoder(use_cat_names=True), SimpleImputer(), StandardScaler(), LogisticRegressionCV(multi_class='auto', solver='lbfgs', cv=5, n_jobs=-1) ) lr.fit(X_train[[feature]], y_train) score = lr.score(X_val[[feature]], y_val) print('Logistic Regression, Validation Accuracy', score) #One-Hot Encoding, Decision Tree, Validation Accuracy from sklearn.tree import DecisionTreeClassifier dt = make_pipeline( ce.OneHotEncoder(use_cat_names=True), SimpleImputer(), DecisionTreeClassifier(random_state=42) ) dt.fit(X_train[[feature]], y_train) score = dt.score(X_val[[feature]], y_val) print('Decision Tree, Validation Accuracy', score) #One-Hot Encoding, Logistic Regression, Model Interpretation model = lr.named_steps['logisticregressioncv'] encoder = lr.named_steps['onehotencoder'] encoded_columns = encoder.transform(X_val[[feature]]).columns coefficients = pd.Series(model.coef_[0], encoded_columns) coefficients.sort_values().plot.barh(color='grey'); #One-Hot Encoding, Decision Tree, Model Interpretation import graphviz from sklearn.tree import export_graphviz model = dt.named_steps['decisiontreeclassifier'] encoder = dt.named_steps['onehotencoder'] encoded_columns = encoder.transform(X_val[[feature]]).columns dot_data = export_graphviz(model, out_file=None, max_depth=7, feature_names=encoded_columns, class_names=model.classes_, impurity=False, filled=True, proportion=True, rounded=True) display(graphviz.Source(dot_data)) #Ordinal Encoding X_train[[feature]].head(10) encoder = ce.OrdinalEncoder() encoded = encoder.fit_transform(X_train[[feature]]) print(f'1 column, {encoded[feature].nunique()} unique values') encoded.head(20) #Ordinal Encoding, Logistic Regression, Validation Accuracy lr = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(), StandardScaler(), LogisticRegressionCV(multi_class='auto', solver='lbfgs', cv=5, n_jobs=-1) ) lr.fit(X_train[[feature]], y_train) score = lr.score(X_val[[feature]], y_val) print('Logistic Regression, Validation Accuracy', score) #Ordinal Encoding, Decision Tree, Validation Accuracy dt = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(), DecisionTreeClassifier(random_state=42) ) dt.fit(X_train[[feature]], y_train) score = dt.score(X_val[[feature]], y_val) print('Decision Tree, Validation Accuracy', score) #Ordinal Encoding, Logistic Regression, Model Interpretation model = lr.named_steps['logisticregressioncv'] encoder = lr.named_steps['ordinalencoder'] encoded_columns = encoder.transform(X_val[[feature]]).columns coefficients = pd.Series(model.coef_[0], encoded_columns) coefficients.sort_values().plot.barh(color='grey'); lr.named_steps['logisticregressioncv'].coef_ lr.named_steps['logisticregressioncv'].intercept_ #Ordinal Encoding, Decision Tree, Model Interpretation model = dt.named_steps['decisiontreeclassifier'] encoder = dt.named_steps['ordinalencoder'] encoded_columns = encoder.transform(X_val[[feature]]).columns dot_data = export_graphviz(model, out_file=None, max_depth=5, feature_names=encoded_columns, class_names=model.classes_, impurity=False, filled=True, proportion=True, rounded=True) display(graphviz.Source(dot_data)) from sklearn.metrics import accuracy_score y_pred = pipeline.predict(X_val) accuracy = accuracy_score(y_val, y_pred) print(f'Accuracy score = {accuracy * 100} %') predictions = pipeline.predict(X_test) submission = sample_submission.copy() submission['status_group'] = predictions submission.to_csv('submission.csv', index=False) ###Output _____no_output_____
tasks/Kurdyukova_Python_HW_1.ipynb
###Markdown Домашнее задание №1 (курс "Практикум по программированию на языке Python") Тема: Введение в язык Python.**Автор**: Мурат Апишев**Выдана**: 25 февраля 2021**Дедлайн**: 21:00 11 марта 2021**Среда выполнения**: Jupyter Notebook (Python 3.7+) Правила:Результат выполнения задания - Jupyter Notebook с кодом. __Максимальное число баллов за задание - 20__.Все ячейки должны быть "выполненными", при этом результат должен воспроизводиться при проверке (на Python 3.7). Если какой-то код не был запущен или отрабатывает с ошибками, то пункт не засчитывается. Задание, сданное после дедлайна, _не принимается_. Можно отправить недоделанное задание, выполненные пункты будут оценены.Готовое задание отправляется на почту [email protected].Задание выполняется самостоятельно. Если какие-то студенты будут уличены в списывании, все они автоматически получат за эту работу 0 баллов. Если вы нашли в Интернете какой-то специфичный код, который собираетесь заимствовать, обязательно укажите это в задании - наверняка вы не единственный, кто найдёт и использует эту информацию.__Удалять фрагменты формулировок заданий запрещается.__ Постановка задачи:- В данной работе нужно решить набор задач, проверяющих владение базовыми инструментами языка.- Каждая задача представляет собой написание одной или более функций, а также набора тестов, проверяющих работу этой функции в общих и крайних случаях.- Отсутствие тестов автоматически уменьшает количество баллов за задание как минимум в два раза, некачественные тесты также будут штрафоваться.- Если в задании указано использовать несколько разных вариантов решения, подразумевается использование различных инструментов (циклы, списковые включения, генераторы, встроенные функции, функции модулей стандартной библотеки и т.п.), замена, например, цикла for на цикл while не является иным способом решения.- Даже если это не указано явно в требованиях, код должен быть по возможности неизбыточным, работать с разумной сложностью и объёмом потребялемой памяти, проверяющие могут снизить балл за задание, выполненное без учёта этого требования.- Результирующий код должен быть читаемым, с единой системой отступов и адеквантными названиями переменных, проверяющие могут снизить балл за задание, выполненное без учёта этого требования. __Задание 1 (0.5 балла):__ Дано натуральное число. Требуется определить, является ли год с данным номером високосным. Если год является високосным, то выведите YES, иначе выведите NO. Напомним, что в соответствии с григорианским календарем, год является високосным, если его номер кратен 4, но не кратен 100, а также если он кратен 400. ###Code def task_01_func(year): print('YES' if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0) else 'NO') #Тесты task_01_func(1200) #Число делится на 400 task_01_func(1700) #Число не делится на 400, делится на 4, но делится на 100 task_01_func(2016) #Число не делится на 100 и делится на 4 task_01_func(2005) #Число не делится на 100 и делится на 4 ###Output YES NO YES NO ###Markdown __Задание 2 (0.5 балла):__ Дано натуральное число. Найдите число знаков в его десятичной записи. Предложите как минимум два различных решения. ###Code import math def task_02_func(number): #Способ 1 count = 0 while number >= 1: number /= 10 count += 1 print(count) #Тесты task_02_func(33) task_02_func(123456789) task_02_func(4) print('\n') def task_02_f(number): #Способ 2, идея подсмотрена тут https://coderoad.ru/2189800/Длина-целого-числа-в-Python number = int(math.log10(number)) + 1 print(number) #Тесты task_02_f(66) task_02_f(3123231231) task_02_f(2) ###Output 2 9 1 2 10 1 ###Markdown __Задание 3 (0.5 балла):__ По данному натуральном n вычислите сумму 1!+2!+3!+...+n!. В решении этой задачи с помощью циклов можно использовать только один цикл. Предложите как минимум два различных решения. ###Code import math def task_03_func(n): #Способ 1, используем цикл s = 0 for i in range(1, n + 1): s += math.factorial(i) print(s) #Тесты task_03_func(1) task_03_func(4) task_03_func(8) print('\n') def task_03_f(n): #Способ 2, опрерируем списком lst = [math.factorial(i) for i in range(1, n)] return sum(lst) #Тесты task_03_func(1) task_03_func(4) task_03_func(8) ###Output 1 33 46233 1 33 46233 ###Markdown __Задание 4 (0.5 балла):__ Определить, является ли введённая строка палиндромом (то есть одинаково читается с обеих сторон). Предложите как минимум три различных решения. ###Code def task_04_func(s): #Способ 1 print('s is a palindromo' if s == s[::-1] else "s isn't a palindromo") #Тесты task_04_func('abba') task_04_func('abcba') task_04_func('abcde') print('\n') def task_04_f(s): #Способ 2 count = 0 for i in range(len(s) // 2 + 1): if s[i] != s[len(s) - i - 1]: count += 1 print('s is a palindromo' if count == 0 else "s isn't a palindromo") #Тесты task_04_f('abba') task_04_f('abcba') task_04_f('abcdd') print('\n') def task_04_function(s): #Способ 3 print('s is a palindromo' if s[:len(s) // 2][::-1] == s[len(s) - (len(s) // 2):] else "s isn't a palindromo") #Тесты task_04_function('abba') task_04_function('abcba') task_04_function('abcdd') ###Output s is a palindromo s is a palindromo s isn't a palindromo s is a palindromo s is a palindromo s isn't a palindromo s is a palindromo s is a palindromo s isn't a palindromo ###Markdown __Задание 5 (1 балл):__ Дан текст в виде строки. Напишите функцию, которая возвращает словарь, где ключами являются уникальные слова из этого текста, а значениями - число раз, которое данное слово встретилось в тексте. Считать, что слова разделяются пробелами. Предложите как минимум два различных решения. ###Code def task_05_func(text): #Способ 1 text = text.lower() lst = text.split() d = dict.fromkeys(lst, 1) for e in d.keys(): for r in lst: if(e == r): d[e] += 1 d[e] -= 1 print(d) #Тесты task_05_func('В первый день весны') task_05_func('На краешке Земли') task_05_func('Я не знаю что это такое если бы я знала что это такое я не знаю что это такое') print('\n') def task_05_f(text): #Способ 2, идею подсмотрела тут https://www.cyberforum.ru/python-beginners/thread2587116.html text = text.lower() lst = text.split() s = set(lst) d ={} for e in s: d[e] = lst.count(e) print(d) #Тесты task_05_f('В первый день весны') task_05_f('На краешке Земли') task_05_f('Я не знаю что это такое если бы я знала что это такое я не знаю что это такое') ###Output {'в': 1, 'первый': 1, 'день': 1, 'весны': 1} {'на': 1, 'краешке': 1, 'земли': 1} {'я': 3, 'не': 2, 'знаю': 2, 'что': 3, 'это': 3, 'такое': 3, 'если': 1, 'бы': 1, 'знала': 1} {'весны': 1, 'первый': 1, 'в': 1, 'день': 1} {'земли': 1, 'краешке': 1, 'на': 1} {'что': 3, 'знала': 1, 'не': 2, 'я': 3, 'бы': 1, 'если': 1, 'знаю': 2, 'это': 3, 'такое': 3} ###Markdown __Задание 6 (1 балл):__ Напишите функцию, которая принимает на вход строку и символ и возвращает:- если символ встретился в строке один раз - кортеж (индекс вхождения, None);- если два и более раз - кортеж (индекс первого вхождения, индекс последнего вхождения);- если ни разу - кортеж (None, None).Запрещается делать более одного прохода по каждому элементу строки. ###Code def task_06_func(s, char): #Код подсмотрела здесь https://ru.stackoverflow.com/questions/779572/Первое-и-последнее-вхождение-без-метода-count-и-циклов tpl = ([None, None]) a = s.find(char) b = s.rfind(char) if a == -1: print(tpl) elif a == b: tpl[0] = a print(tpl) else: tpl[0] = a tpl[1] = b print(tpl) #Тетсы task_06_func('молоко', 'о') task_06_func('солнышко', 'а') task_06_func('ёжик', 'и') ###Output [1, 5] [None, None] [2, None] ###Markdown __Задание 7 (1 балл):__ Дан список целых чисел. Напишите функцию, которая возвращает копию этого списка, из которой удалены отрицательные числа, а все прочие числа возведены в квадрат. Также возвращаемая последовательность должна быть отсортирована по убыванию. Предложите как минимум три различных решения. ###Code def task_07_func(lst): #Способ 1 l = [] for e in lst: if e >= 0: l.append(e * e) l.sort(reverse = True) print(l) #Тест task_07_func([2, 5, -1, 7, 8, -4]) def task_07_f(lst): #Способ 2 l = lst.copy() j = 0 for i, e in enumerate(lst): if e < 0: l.remove(e) else: l[j] *= l[j] j += 1 l.sort(reverse = True) print(l) #Тест task_07_f([2, 5, -1, 7, 8, -4]) def task_07_function(lst): #Способ 3 f = filter(lambda x: x >= 0, lst) m = map(lambda x: x ** 2, f) l = list(m) l.sort(reverse = True) print(l) #Тест task_07_function([2, 5, -1, 7, 8, -4]) ###Output [64, 49, 25, 4] [64, 49, 25, 4] [64, 49, 25, 4] ###Markdown __Задание 8 (1 балл):__ Напишите функцию, которая принимает на вход список кортежей одинаковой длины и индекс `index` элемента в кортеже и возвращает генератор, итерирование по которому позволит получит все кортежи входного списка, отсортированные по убыванию элементов этих кортежей с индексом `index`. ###Code def task_08_func(lst, index): lst = sorted(lst, key = lambda x: x[index], reverse = True) for tpl in lst: yield tpl #Тесты for e in task_08_func([(1, 2, 3), (7, 8, 9), (4, 5, 6)], 1): print(e) print('\n') for e in task_08_func([(1, 'A', None), (4, 'X', 7), (7, 'R', 10)], 0): print(e) ###Output (7, 8, 9) (4, 5, 6) (1, 2, 3) (7, 'R', 10) (4, 'X', 7) (1, 'A', None) ###Markdown __Задание 9 (1 балл):__ Напишите функцию, которая получает на вход натуральное число `n` и выводит первые `n` строк треугольника Паскаля. ###Code def current_row(n): #Идею подсмотрела тут https://www.cyberforum.ru/python-beginners/thread2164097.html row = [] for i in range(n): if i == 0 or i == n-1: row.append(1) else: c_row = current_row(n-1) row.append(c_row[i-1] + c_row[i]) return(row) def task_09_func(n): for i in range(1, n+1): print(current_row(i)) task_09_func(5) ###Output [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] ###Markdown __Задание 10 (1 балл):__ Напишите функцию, которая принимает на вход абсолютный путь к директории и две строки с расширениями файлов. В результате её выполнения у всех файлов в указанной директории, имеющих первое расширение, расширение должно измениться на второе. В конце работы функция должна возвращать кортеж из двух элементов:1. сколько всего в директории файлов (именно файлов, не директорий);2. у скольки из них расширение было изменено.Допускается только один проход по каждому файлу из указанной директории. ###Code import pathlib from pathlib import Path import os def task_10_func(dir_path, prev_extension, next_extension): t1 = 0 t2 = 0 for r, d, f in os.walk(dir_path): for e in f: t1 += 1 if os.path.splitext(e)[1] == prev_extension: name = os.path.splitext(e)[0] os.rename(e, name + next_extension) t2 += 1 return(tuple([t1, t2])) ###Output _____no_output_____ ###Markdown __Задание 11 (1 балл):__ Описать функцию, которая принимает на вход два списка и возвращает список уникальных элементов, которые есть в первом входном списке и отсутствуют во втором. Запрещается использовать циклы и списковые включения/генераторы списков. ###Code def task_11_func(first_list, second_list): A = set(first_list) B = set(second_list) A = A - B print(list(A)) task_11_func(['a', 'b', 'c'], ['a', 'c', 'd']) print('\n') task_11_func([1, 1, 3, 5, 6, 10, 5], [1, 10]) ###Output ['b'] [3, 5, 6] ###Markdown __Задание 12 (1 балл):__ Напишите функцию, которая получает на вход путь к файлу, в котором в каждой строке записано одно вещественное число, а также путь к выходному файлу. Функция должна прочитать содержимое файла, игнорировать строки с нечётными индексами, а строки с чётными индексами должна увеличить на минимальное из чисел, содержащихся в этом файле. Полученные числа нужно записать в выходной файл с точностью 5 знаков после запятой.Требуется сделать не более двух проходов по входному файлу, расход памяти на протяжении работы должен быть O(1) (то есть никак не зависеть от числа строк во входном файле). ###Code import os import ntpath def task_12_func(input_path, output_path): with open(ntpath.basename(input_path), 'r') as f1: with open(ntpath.basename(output_path), 'a') as f2: m1 = f1.readlines() m2 = list(map(lambda x: float(x[:len(x) - 1]), m1)) MIN = min(m2) for i, e in enumerate(m2): if i % 2 == 0: l = e + MIN f2.write('{:.5f}\n'.format(l)) f2.close() f1.close() ###Output _____no_output_____ ###Markdown __Задание 13 (1 балл):__ Написать функцию, которая принимает на вход число `n`, которое может быть либо натуральным, либо -1, и возвращает генератор чисел Фиббоначи. Если входной параметр равен натуральному числу, то генератор должен выдавать последовательно числа Фиббоначи до `n`-го. Если `n` равно -1, то генератор должен быть бесконечным. ###Code from itertools import count def task_13_func(n): f1 = 1 f2 = 1 for i in count(start = 0): c = f1 f1 = f2 f2 += c if(i == n): break yield c #Тесты for e in task_13_func(10): print(e) print('\n') for e in task_13_func(-1): print(e) if e == 2584: #Останавливаем бесконечный генератор, например, на таком числе фиббоначи break ###Output 1 1 2 3 5 8 13 21 34 55 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 ###Markdown __Задание 14 (1 балл):__ Написать функцию, которая принимает на вход произвольный объект, проверяет его тип, и для целого числа возвращает список всех магических методов объекта, начинающихся с `__a`, для строк - с `__s`. Для всех прочих типов должен возвращаться список немагических методов. В задании запрещается использовать циклы и списковые включения/генераторы списков. ###Code def task_14_func(n): if(type(n) == type(5)): print(list(filter(lambda x: x[:3] == '__a', dir(n)))) elif(type(n) == type('yuy')): print(list(filter(lambda x: x[:3] == '__s', dir(n)))) else: print(list(filter(lambda x: x[:2] != '__', dir(n)))) #Тесты task_14_func(5) print(list(dir(5))) print('\n') task_14_func('abc') print(list(dir('abc'))) print('\n') task_14_func([1, 3, 4, 6]) print(list(dir([1, 3, 4, 6]))) ###Output ['__abs__', '__add__', '__and__'] ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] ['__setattr__', '__sizeof__', '__str__', '__subclasshook__'] ['__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__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ###Markdown __Задание 15 (1.5 балла):__ Написать функцию, которая во входной строке заменяет вхождения всех английских заглавных букв на их номер в таблице ASCII, затем производит сплит по минимальной из цифр строки. Предложите как минимум два различных решения, одно из которых не должно использовать циклы. При использовании циклов допускается не более двух проходов по строке. ###Code #Способ 1 def task_15_func(n): n1 = "" m = 10 for e in n: if ord(e) >= 65 and ord(e) <= 90: n1 += str(ord(e)) a = ord(e) // 10 b = ord(e) - a * 10 if min(a, b) < m: m = min(a, b) else: n1 += e if ord(e) >= 48 and ord(e) <= 57 and int(e) < m: m = int(e) print(n1) #для тестов print(n1.split(str(m))) #Тесты task_15_func('adsdvrAdcsSdvdAcdcsdEfv') print('\n') task_15_func('fvf1svsv1fvadfvGfvdfvCdfs343') print('\n') task_15_func('vfkvndfkjvdfk') print('\n') task_15_func('vvmslk1mvvlkm5vf') ###Output adsdvr65dcs83dvd65cdcsd69fv ['adsdvr65dcs8', 'dvd65cdcsd69fv'] fvf1svsv1fvadfv71fvdfv67dfs343 ['fvf', 'svsv', 'fvadfv7', 'fvdfv67dfs343'] vfkvndfkjvdfk ['vfkvndfkjvdfk'] vvmslk1mvvlkm5vf ['vvmslk', 'mvvlkm5vf'] ###Markdown __Задание 16 (1.5 балла):__ Написать функцию, которая принимает на вход строку и извлекает из неё мобильные телефонные номера с помощью регулярных выражений. Функция должна поддерживать общепринятые варианты написания номера, как со всевозможными разделителями, так и без них (обеспечьте поддержку не менее 10 различных случаев). Возвращаемым значением функции является список всех найденных в строке номеров, если их не было, нужно вернуть пустой список. ###Code def task_16_func(n): ... ###Output _____no_output_____ ###Markdown __Задание 17 (5 баллов):__ Опишем бинарное дерево, представленное в виде вложенных кортежей, в каждом узле дерева хранится вещественное число и ссылка на левое и правое поддерево.Пример: для сбалансированного дерева``` v_0 / \ v_11 v_12 / \ / \v_21 v_22 v_23 v_24```представление в виде кортежей будет выглядеть так:```(v_0, (v_11, (v_21, None, None), (v_22, None, None) ), (v_12, (v_23, None, None), (v_24, None, None) ))```Необходимо написать функцию, которая принимает на вход бинарное дерево (не обязательно сбалансированное), закодированное описанным способом в виде кортежа, производит его обход в глубину и для каждой листовой вершины вычисляет сумму всех значений от корня до неё включительно. Функция ничего не возвращает, вместо этого она выводит получаемые суммы в порядке следования листовых вершин (слева направо).Реализуйте два решения: на основе рекурсии и на основе циклов. ###Code def task_17_func(n): ... ###Output _____no_output_____
Cross Validation/Heart disease predictor with k-fold cross validation.ipynb
###Markdown K-Fold Cross Validation ###Code from sklearn.model_selection import cross_val_score #cross validation for model gaussianNB (naive bayes) cv_score_NB= cross_val_score(model,x,y,cv=10) #if there is alphabetical value or catagorical value then we have to preprocess the dataset with encoder or vectorizer cv_score_NB cv_score_NB.mean() #cross validation for Random forest classifier cv_score_RFC= cross_val_score(Rclf,x,y,cv=10) #if there is alphabetical value or catagorical value then we have to preprocess the dataset with encoder or vectorizer cv_score_RFC ###Output _____no_output_____
mnist/visualize-clusters-mnist.ipynb
###Markdown Load the data. ###Code import gzip import numpy as np import matplotlib.pyplot as plt def load_data(filename, dims): with gzip.open(filename, "rb") as infile: # consume magic number infile.read(4) # consume dimensions data infile.read(4 * len(dims)) return np.frombuffer(infile.read(np.prod(dims)), dtype=np.uint8).reshape(dims) # training data train_images = load_data("data/train-images-idx3-ubyte.gz", [60000, 28, 28]) train_labels = load_data("data/train-labels-idx1-ubyte.gz", [60000]) # testing data test_images = load_data("data/t10k-images-idx3-ubyte.gz", [10000, 28, 28]) test_labels = load_data("data/t10k-labels-idx1-ubyte.gz", [10000]) ###Output _____no_output_____ ###Markdown Process the data for training and testing. ###Code train_x = train_images.astype(np.float) / 255 train_y = np.zeros((60000, 10)) train_y[np.arange(60000),train_labels] = 1 test_x = test_images.astype(np.float) / 255 test_y = np.zeros((10000, 10)) test_y[np.arange(10000),test_labels] = 1 ###Output _____no_output_____ ###Markdown Create embeddings for the training data. ###Code import os import pickle from umap import UMAP from sklearn.decomposition import PCA def create_embeddings(data, ignore_cache=False): umap_dir = "cache/umap.pickle" pca_dir = "cache/pca.pickle" if not os.path.isfile(umap_dir) or ignore_cache: umap_reducer = UMAP(random_state=42).fit(data) pickle.dump(umap_reducer, open(umap_dir, "wb")) else: umap_reducer = pickle.load(open(umap_dir, "rb")) if not os.path.isfile(pca_dir) or ignore_cache: pca_reducer = PCA(n_components=2, random_state=42).fit(data) pickle.dump(pca_reducer, open(pca_dir, "wb")) else: pca_reducer = pickle.load(open(pca_dir, "rb")) return umap_reducer, pca_reducer umap_reducer, pca_reducer = create_embeddings(train_x.reshape(-1, 784), ignore_cache=False) umap_data = umap_reducer.transform(train_x.reshape(-1, 784)) pca_data = pca_reducer.transform(train_x.reshape(-1, 784)) def plot_embeddings(): fig, axes = plt.subplots(1, 2, squeeze=True, figsize=(8,4)) axes[0].scatter(umap_data[:,0], umap_data[:,1], s=1, c=train_labels, cmap='Spectral') axes[0].set_title("UMAP Embedding") axes[1].scatter(pca_data[:,0], pca_data[:,1], s=1, c=train_labels, cmap='Spectral') axes[1].set_title("PCA Embedding") plt.setp(axes, xticks=[], yticks=[]) plt.tight_layout() plot_embeddings() ###Output _____no_output_____ ###Markdown Train the model with random weights. ###Code import keras import keras.layers as layers import keras.models as models from model import GaussMembership, normalized_product_fn def plot_cluster_movement(ax, data, init, current): change = current - init ax.scatter(data[:,0], data[:,1], s=1, c=train_labels, cmap='Spectral') s1 = ax.scatter(init[:,0], init[:,1], s=100, c="k", marker="^") s2 = ax.scatter(current[:,0], current[:,1], s=100, c="r", marker="^") for i in range(change.shape[0]): ax.arrow(init[i,0], init[i,1], change[i,0], change[i,1]) ax.legend([s1, s2], ["Before Training", "After Training"]) # create the model model = keras.Sequential([ layers.Reshape((784,), input_shape=(28,28)), GaussMembership(10), layers.Lambda(lambda x: normalized_product_fn(x)), layers.Dense(10, activation="sigmoid"),]) # set weights randomly model.layers[1].set_weights(( # multiplying the by the mean is a way to ensure that the centers occupy the same subset of the # feature space as the input data np.random.normal(1., 0.1, size=(10,784)) * np.mean(train_x.reshape(-1, 784), axis=0, keepdims=True), np.random.normal(1., 0.1, size=(10,784)))) model.compile( optimizer="adam", loss="binary_crossentropy", metrics=[keras.metrics.categorical_accuracy]) init_mu, init_sigma = model.layers[1].get_weights() # train the model history = model.fit( x=train_x, y=train_y, batch_size=64, epochs=50, validation_data=(test_x, test_y), verbose=1, shuffle=True) final_mu, final_sigma = model.layers[1].get_weights() # plot the cluster movement fig, axes = plt.subplots(1, 2, squeeze=True, figsize=(8,4)) axes[0].set_title("Cluster Movement (UMAP)") plot_cluster_movement( axes[0], umap_data, umap_reducer.transform(init_mu), umap_reducer.transform(final_mu)) axes[1].set_title("Cluster Movement (PCA)") plot_cluster_movement( axes[1], pca_data, pca_reducer.transform(init_mu), pca_reducer.transform(final_mu)) # plot the loss and accuracy fig, axes = plt.subplots(1, 2, figsize=(8, 4), squeeze=True) axes[0].set_title("Loss") axes[0].plot(history.history["loss"], c="b") axes[0].plot(history.history["val_loss"], c="r") axes[1].set_title("Accuracy") #axes[1].set_ylim((0.8, 1)) axes[1].plot(history.history["categorical_accuracy"], c="b") axes[1].plot(history.history["val_categorical_accuracy"], c="r") ###Output Using TensorFlow backend. WARNING: Logging before flag parsing goes to stderr. W0214 10:31:57.238629 140593226557248 deprecation.py:323] From /home/ryan-desktop/anaconda3/envs/keras/lib/python3.7/site-packages/tensorflow/python/ops/math_grad.py:102: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Deprecated in favor of operator or tf.math.divide. ###Markdown The clusters still do not seem to occupy logical locations. We will create images from the mu and sigma parameters to try and figure out why this is. ###Code fig, axes = plt.subplots(2, 10, figsize=(16,3)) for i in range(10): axes[0][i].imshow(final_mu[i,:].reshape(28, 28), cmap="Greys", interpolation="none") axes[1][i].imshow(final_sigma[i,:].reshape(28, 28), cmap="Greys", interpolation="none") plt.setp(axes, xticks=[], yticks=[], frame_on=False) plt.tight_layout(h_pad=0, w_pad=0) ###Output _____no_output_____ ###Markdown The images above offer some insight as to why the centers learned by the network do not make sense. The mu plots (on the top row) show that the the centers learned hardly resemble handwritten digits. This means gives some insight to why they appear in weird locations on the 2D embeddings. UMAP learns a 2D manifold close to the data in the original feature space and then uses the manifold to project the data to 2D. Since these centers do not resemble the original data, it is likely that they are not near this manifold and UMAP maps them to locations that are not near the original digits.I believe something similar is occuring with PCA, where the clusters exist outside of the subset of space where the original data exists meaning PCA cannot meaningfully transform them. ###Code import skfuzzy as skf # create the model model = keras.Sequential([ layers.Reshape((784,), input_shape=(28,28)), GaussMembership(10), layers.Lambda(lambda x: normalized_product_fn(x)), layers.Dense(10, activation="sigmoid"),]) init_mu, memberships, u0, d, jm, p, fpc = skf.cmeans( train_x.reshape(-1, 784).T, 10, 1.1, 1e-8, 1000, seed=0) # set weights with fcm model.layers[1].set_weights(( init_mu, np.random.normal(1., 0.1, size=(10,784)))) model.compile( optimizer="adam", loss="binary_crossentropy", metrics=[keras.metrics.categorical_accuracy]) init_mu, init_sigma = model.layers[1].get_weights() # train the model history = model.fit( x=train_x, y=train_y, batch_size=64, epochs=50, validation_data=(test_x, test_y), verbose=1, shuffle=True) final_mu, final_sigma = model.layers[1].get_weights() # plot the cluster movement fig, axes = plt.subplots(1, 2, squeeze=True, figsize=(8,4)) axes[0].set_title("Cluster Movement (UMAP)") plot_cluster_movement( axes[0], umap_data, umap_reducer.transform(init_mu), umap_reducer.transform(final_mu)) axes[1].set_title("Cluster Movement (PCA)") plot_cluster_movement( axes[1], pca_data, pca_reducer.transform(init_mu), pca_reducer.transform(final_mu)) # plot the loss and accuracy fig, axes = plt.subplots(1, 2, figsize=(8, 4), squeeze=True) axes[0].set_title("Loss") axes[0].plot(history.history["loss"], c="b") axes[0].plot(history.history["val_loss"], c="r") axes[1].set_title("Accuracy") #axes[1].set_ylim((0.8, 1)) axes[1].plot(history.history["categorical_accuracy"], c="b") axes[1].plot(history.history["val_categorical_accuracy"], c="r") ###Output Train on 60000 samples, validate on 10000 samples Epoch 1/50 60000/60000 [==============================] - 3s 51us/step - loss: 0.4163 - categorical_accuracy: 0.1536 - val_loss: 0.3099 - val_categorical_accuracy: 0.2886 Epoch 2/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.2594 - categorical_accuracy: 0.5189 - val_loss: 0.2258 - val_categorical_accuracy: 0.6185 Epoch 3/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.2052 - categorical_accuracy: 0.6794 - val_loss: 0.1881 - val_categorical_accuracy: 0.7264 Epoch 4/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.1745 - categorical_accuracy: 0.7412 - val_loss: 0.1632 - val_categorical_accuracy: 0.7651 Epoch 5/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.1537 - categorical_accuracy: 0.7720 - val_loss: 0.1454 - val_categorical_accuracy: 0.7927 Epoch 6/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.1388 - categorical_accuracy: 0.8005 - val_loss: 0.1338 - val_categorical_accuracy: 0.8126 Epoch 7/50 60000/60000 [==============================] - 3s 49us/step - loss: 0.1265 - categorical_accuracy: 0.8259 - val_loss: 0.1210 - val_categorical_accuracy: 0.8461 Epoch 8/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.1155 - categorical_accuracy: 0.8513 - val_loss: 0.1109 - val_categorical_accuracy: 0.8582 Epoch 9/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.1061 - categorical_accuracy: 0.8632 - val_loss: 0.1030 - val_categorical_accuracy: 0.8737 Epoch 10/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0994 - categorical_accuracy: 0.8731 - val_loss: 0.0980 - val_categorical_accuracy: 0.8786 Epoch 11/50 60000/60000 [==============================] - 3s 49us/step - loss: 0.0945 - categorical_accuracy: 0.8799 - val_loss: 0.0934 - val_categorical_accuracy: 0.8831 Epoch 12/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0906 - categorical_accuracy: 0.8857 - val_loss: 0.0907 - val_categorical_accuracy: 0.8853 Epoch 13/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0873 - categorical_accuracy: 0.8894 - val_loss: 0.0873 - val_categorical_accuracy: 0.8904 Epoch 14/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0845 - categorical_accuracy: 0.8934 - val_loss: 0.0854 - val_categorical_accuracy: 0.8928 Epoch 15/50 60000/60000 [==============================] - 3s 49us/step - loss: 0.0819 - categorical_accuracy: 0.8962 - val_loss: 0.0831 - val_categorical_accuracy: 0.8946 Epoch 16/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0791 - categorical_accuracy: 0.8991 - val_loss: 0.0792 - val_categorical_accuracy: 0.8956 Epoch 17/50 60000/60000 [==============================] - 3s 50us/step - loss: 0.0747 - categorical_accuracy: 0.9031 - val_loss: 0.0750 - val_categorical_accuracy: 0.9039 Epoch 18/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0713 - categorical_accuracy: 0.9089 - val_loss: 0.0721 - val_categorical_accuracy: 0.9090 Epoch 19/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0685 - categorical_accuracy: 0.9127 - val_loss: 0.0707 - val_categorical_accuracy: 0.9126 Epoch 20/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0661 - categorical_accuracy: 0.9151 - val_loss: 0.0674 - val_categorical_accuracy: 0.9136 Epoch 21/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0638 - categorical_accuracy: 0.9179 - val_loss: 0.0668 - val_categorical_accuracy: 0.9146 Epoch 22/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0621 - categorical_accuracy: 0.9193 - val_loss: 0.0647 - val_categorical_accuracy: 0.9154 Epoch 23/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0602 - categorical_accuracy: 0.9221 - val_loss: 0.0640 - val_categorical_accuracy: 0.9185 Epoch 24/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0588 - categorical_accuracy: 0.9238 - val_loss: 0.0633 - val_categorical_accuracy: 0.9191 Epoch 25/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0571 - categorical_accuracy: 0.9257 - val_loss: 0.0614 - val_categorical_accuracy: 0.9208 Epoch 26/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0552 - categorical_accuracy: 0.9290 - val_loss: 0.0598 - val_categorical_accuracy: 0.9205 Epoch 27/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0533 - categorical_accuracy: 0.9296 - val_loss: 0.0584 - val_categorical_accuracy: 0.9243 Epoch 28/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0520 - categorical_accuracy: 0.9312 - val_loss: 0.0584 - val_categorical_accuracy: 0.9220 Epoch 29/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0507 - categorical_accuracy: 0.9329 - val_loss: 0.0569 - val_categorical_accuracy: 0.9247 Epoch 30/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0495 - categorical_accuracy: 0.9344 - val_loss: 0.0560 - val_categorical_accuracy: 0.9235 Epoch 31/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0485 - categorical_accuracy: 0.9350 - val_loss: 0.0554 - val_categorical_accuracy: 0.9265 Epoch 32/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0476 - categorical_accuracy: 0.9358 - val_loss: 0.0555 - val_categorical_accuracy: 0.9224 Epoch 33/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0467 - categorical_accuracy: 0.9377 - val_loss: 0.0548 - val_categorical_accuracy: 0.9236 Epoch 34/50 60000/60000 [==============================] - 3s 46us/step - loss: 0.0458 - categorical_accuracy: 0.9376 - val_loss: 0.0529 - val_categorical_accuracy: 0.9252 Epoch 35/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0450 - categorical_accuracy: 0.9391 - val_loss: 0.0520 - val_categorical_accuracy: 0.9293 Epoch 36/50 60000/60000 [==============================] - 3s 51us/step - loss: 0.0447 - categorical_accuracy: 0.9393 - val_loss: 0.0528 - val_categorical_accuracy: 0.9249 Epoch 37/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0437 - categorical_accuracy: 0.9410 - val_loss: 0.0522 - val_categorical_accuracy: 0.9291 Epoch 38/50 60000/60000 [==============================] - 3s 51us/step - loss: 0.0433 - categorical_accuracy: 0.9412 - val_loss: 0.0523 - val_categorical_accuracy: 0.9278 Epoch 39/50 60000/60000 [==============================] - 3s 49us/step - loss: 0.0428 - categorical_accuracy: 0.9420 - val_loss: 0.0512 - val_categorical_accuracy: 0.9301 Epoch 40/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0422 - categorical_accuracy: 0.9419 - val_loss: 0.0521 - val_categorical_accuracy: 0.9270 Epoch 41/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0420 - categorical_accuracy: 0.9422 - val_loss: 0.0511 - val_categorical_accuracy: 0.9299 Epoch 42/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0414 - categorical_accuracy: 0.9434 - val_loss: 0.0509 - val_categorical_accuracy: 0.9313 Epoch 43/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0410 - categorical_accuracy: 0.9435 - val_loss: 0.0504 - val_categorical_accuracy: 0.9292 Epoch 44/50 60000/60000 [==============================] - 3s 49us/step - loss: 0.0407 - categorical_accuracy: 0.9451 - val_loss: 0.0501 - val_categorical_accuracy: 0.9312 Epoch 45/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0403 - categorical_accuracy: 0.9446 - val_loss: 0.0496 - val_categorical_accuracy: 0.9307 Epoch 46/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0402 - categorical_accuracy: 0.9442 - val_loss: 0.0496 - val_categorical_accuracy: 0.9307 Epoch 47/50 60000/60000 [==============================] - 3s 47us/step - loss: 0.0397 - categorical_accuracy: 0.9451 - val_loss: 0.0495 - val_categorical_accuracy: 0.9312 Epoch 48/50 60000/60000 [==============================] - 3s 48us/step - loss: 0.0394 - categorical_accuracy: 0.9458 - val_loss: 0.0491 - val_categorical_accuracy: 0.9316 Epoch 49/50 60000/60000 [==============================] - 3s 50us/step - loss: 0.0391 - categorical_accuracy: 0.9466 - val_loss: 0.0486 - val_categorical_accuracy: 0.9308 Epoch 50/50 60000/60000 [==============================] - 3s 50us/step - loss: 0.0388 - categorical_accuracy: 0.9469 - val_loss: 0.0504 - val_categorical_accuracy: 0.9292 ###Markdown Here, the clusters start in locations that appear correct. However, as the model learns the clusters move away from the seemingly correct locations. I would assume this is because the centers found by FCM are near the UMAP manifold, but move away during training. ###Code fig, axes = plt.subplots(2, 10, figsize=(16,3)) for i in range(10): axes[0][i].imshow(final_mu[i,:].reshape(28, 28), cmap="Greys", interpolation="none") axes[1][i].imshow(final_sigma[i,:].reshape(28, 28), cmap="Greys", interpolation="none") plt.setp(axes, xticks=[], yticks=[], frame_on=False) plt.tight_layout(h_pad=0, w_pad=0) ###Output _____no_output_____ ###Markdown Of all the rules, the only one that resembles a digit is the rule for 0. The rest look random. This section was suppose to use gradient descent to train the input images to maximize each output. This would let us see what the network thinks is most important for each digit. Unfortunately, it is very inconsistent and rarely converges to the desired result (the network classifies it as something other than what the target was). ###Code # from keras import backend as K # prediction = 1 # while prediction != 0: # image = np.random.normal(0.5, 0.1, size=(1,28,28)) # # train the image to classifier as 0 # target = np.zeros((1,10)) # target[:,0] = 1 # # loss and gradients # loss = -K.sum(target * K.log(model.output) + (1 - target) * K.log(1 - model.output)) # grads = K.gradients(loss, model.inputs) # grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-8) # iterate = K.function(model.inputs, [loss, grads]) # for i in range(20): # loss_val, grads_val = iterate([image]) # image -= grads_val.reshape(1,28,28) ###Output _____no_output_____
Recommendation Systems/Recommendation System - Books.ipynb
###Markdown Book Recommendation System ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import warnings from keras.layers import Input, Embedding, Flatten, Dot, Dense from keras.models import Model %matplotlib inline dataset = pd.read_csv('D:/Personal/Practice Projects/Recommendation System/goodbooks/goodbooks-10k/ratings.csv') dataset.head() dataset.shape from sklearn.model_selection import train_test_split train, test = train_test_split(dataset, test_size=0.2, random_state=42) train.head() test.head() n_users = len(dataset.user_id.unique()) n_users n_books = len(dataset.book_id.unique()) n_books book_input = Input(shape=[1], name="Book-Input") book_embedding = Embedding(n_books+1, 5, name="Book-Embedding")(book_input) book_vec = Flatten(name="Flatten-Books")(book_embedding) user_input = Input(shape=[1], name="User-Input") user_embedding = Embedding(n_users+1, 5, name="User-Embedding")(user_input) user_vec = Flatten(name="Flatten-Users")(user_embedding) prod = Dot(name="Dot-Product", axes=1)([book_vec, user_vec]) model = Model([user_input, book_input], prod) model.compile('adam', 'mean_squared_error') from keras.models import load_model if os.path.exists('regression_model.h5'): model = load_model('regression_model.h5') else: history = model.fit([train.user_id, train.book_id], train.rating, epochs=5, verbose=1) model.save('regression_model.h5') plt.plot(history.history['loss']) plt.xlabel("Epochs") plt.ylabel("Training Error") model.evaluate([test.user_id, test.book_id], test.rating) predictions = model.predict([test.user_id.head(10), test.book_id.head(10)]) [print(predictions[i], test.rating.iloc[i]) for i in range(0,10)] ###Output [4.697358] 5 [3.7322755] 4 [3.161058] 3 [4.2724395] 5 [3.0228083] 3 [4.424722] 3 [3.9317112] 3 [4.8768115] 4 [3.9131103] 3 [4.5833607] 5 ###Markdown Visualizing Embeddings ###Code # Extract embeddings book_em = model.get_layer('Book-Embedding') book_em_weights = book_em.get_weights()[0] book_em_weights[:5] from sklearn.decomposition import PCA import seaborn as sns pca = PCA(n_components=2) pca_result = pca.fit_transform(book_em_weights) sns.scatterplot(x=pca_result[:,0], y=pca_result[:,1]) book_em_weights = book_em_weights / np.linalg.norm(book_em_weights, axis = 1).reshape((-1, 1)) book_em_weights[0][:10] np.sum(np.square(book_em_weights[0])) pca = PCA(n_components=2) pca_result = pca.fit_transform(book_em_weights) sns.scatterplot(x=pca_result[:,0], y=pca_result[:,1]) from sklearn.manifold import TSNE tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300) tnse_results = tsne.fit_transform(book_em_weights) sns.scatterplot(x=tnse_results[:,0], y=tnse_results[:,1]) ###Output _____no_output_____ ###Markdown Making Recommendations ###Code # Creating dataset for making recommendations for the first user book_data = np.array(list(set(dataset.book_id))) book_data[:5] user = np.array([1 for i in range(len(book_data))]) user[:5] predictions = model.predict([user, book_data]) predictions = np.array([a[0] for a in predictions]) recommended_book_ids = (-predictions).argsort()[:5] recommended_book_ids # print predicted scores predictions[recommended_book_ids] books = pd.read_csv('D:/Personal/Practice Projects/Recommendation System/goodbooks/goodbooks-10k/books.csv') books.head() books[books['id'].isin(recommended_book_ids)] ###Output _____no_output_____
notebooks/API DEVLOPMENT - FLASK.ipynb
###Markdown FLASK API DEVLOPMENT ###Code import os ## write the sample program to script file hello_world_api_script_file = os.path.join(os.path.pardir, 'src', 'models', 'hello_world_api.py') %%writefile $hello_world_api_script_file from flask import Flask, request app = Flask(__name__) @app.route('/api',methods=['POST']) def say_hello(): data = request.get_json(force=True) name = data['name'] return "hello {0}".format(name) if __name__ == '__main__': app.run(host = '0.0.0.0', port = 10001, debug=False) ###Output Overwriting ..\src\models\hello_world_api.py ###Markdown Call the API ###Code import json import requests url = 'http://127.0.0.1:10001/api' data = json.dumps({'name': 'vipin'}) r = requests.post(url, data) ##response r.text ###Output _____no_output_____