code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #imports # !pip install ipython-cache import cache_magic from random import randint import sys import math import json # + [markdown] colab_type="text" id="7ACJ4WcqAdRg" # # MDP Implementations # + colab={} colab_type="code" id="9iTAO20cOV7z" # Creating MDP representation for the grid world and organizing its functionalities class ActionResult: def __init__ (self, resultState, prob, reward): self.resultState = resultState self.prob = prob self.reward = reward def __str__(self): return "resultstate: {0}\nprobability: {1}\nReward: {2}".format(str(self.resultState), str(self.prob), str(self.reward)) class Action: # abstraction for an action. Expects a state on which this action # can be taken and a list of ActionResult def __init__ (self, state, results, label): self.state = state self.results = results self.label = label def __str__(self): s = "{0} - {1}\n".format(str(self.state), self.label) for r in self.results: s = s + str(r) + "\n" return s # return str(self.state) + " " + str([str(r) for r in self.results]) class State: def __init__(self, id, actions, value): self.id = id self.actions = actions self.value = value def __str__(self): return str(self.id) + " " + str(self.value) + " " + str(self.actions) class GridWorldMDP(object): def __init__ (self, rewards, rows, cols, actions): self.rows = rows self.cols = cols self.rewards = rewards self.policy = [['u' for j in range(cols)] for i in range(rows)] self.value = [[0 for j in range(cols)] for i in range(rows)] self.states = [[State((i, j), actions[(i, j)], 0) for j in range(cols)] for i in range(rows)] def getStateValue(self, state): return self.states[state[0]][state[1]].value def setStateValue(self, state, v): self.states[state[0]][state[1]].value = v def upadateStateValue(self, state): maxV = float("-inf") actions = self.states[state[0]][state[1]].actions for i in range(len(actions)): action = actions[i] resultState = action.results[0].resultState r = action.results[0].reward v = self.getStateValue(resultState) if r + v > maxV: maxV = r + v self.policy[state[0]][state[1]] = action.label self.setStateValue(state, v) def printValues(self): for r in self.value: print(r) def getPolicy(self): return self.policy def printPolicy(self): for r in self.policy: print(r) print() def iterateValues(self): for i in range(self.rows): for j in range(self.cols): self.upadateStateValue((i, j)) def iterateValuesUntilConverge(self, printSteps=False): while True: values = self.value self.iterateValues() if printSteps: print() self.printPolicy() if values == self.value: break def repeatIterateValues(self, n, printSteps=False): for i in range(n): self.iterateValues() if printSteps: print() self.printPolicy() class DeterministicGridWorldMDP(GridWorldMDP): transitions = [(0, 1), (0, -1), (1, 0), (-1, 0)] nTransitionsPerState = len(transitions) # creates a gridworld representation where the reward for every transition # is given in the rewards matrix which means the reward the agent gets when achieving that reward def __init__ (self, rewards, rows, cols): actions = DeterministicGridWorldMDP.getDeterministicGridWorldDefaultActions(rewards, rows, cols) super(DeterministicGridWorldMDP, self).__init__(rewards, rows, cols, actions) @staticmethod def getDeterministicGridWorldDefaultActions(rewards, rows, cols): keys = [] for j in range(cols): for i in range(rows): keys.append((i, j)) actions = {key: DeterministicGridWorldMDP.generateActions(key[0], key[1], rewards, rows, cols) for key in keys} return actions @staticmethod def isValidTransition(dest, rows, cols): return not ((dest[0] < 0 or dest[0] >= rows) or (dest[1] < 0 or dest[1] >= cols)) @staticmethod def generateActions(i, j, rewards, rows, cols): actions = [] prettyDirs = ['r', 'l', 'd', 'u'] for transition in range(DeterministicGridWorldMDP.nTransitionsPerState): resultState = (i + DeterministicGridWorldMDP.transitions[transition][0], j + DeterministicGridWorldMDP.transitions[transition][1]) if DeterministicGridWorldMDP.isValidTransition(resultState, rows, cols): actions.append(Action((i, j), [ActionResult(resultState, 1, rewards[resultState[0]][resultState[1]])], prettyDirs[transition])) return actions # + [markdown] colab_type="text" id="2Q0jChHJAwYW" # # Auxiliary functions # + colab={} colab_type="code" id="vrzTI84pA091" def printMatrix(matrix): for r in matrix: print(r) print() def generateRandomRewards(row, cols, goalReward, notGoalReward): goalCoordX, goalCoordY = randint(0, rows - 1), randint(0, cols - 1) rewards = [[notGoalReward for j in range(cols)] for i in range(rows)] rewards[goalCoordX][goalCoordY] = goalReward return rewards, (goalCoordX, goalCoordY) def generateRandomRewardsWithObstacles(row, cols, goalReward, notGoalReward, obstacleReward, nObstacles): rewards = [[notGoalReward for j in range(cols)] for i in range(rows)] goalCoordX, goalCoordY = randint(0, rows - 1), randint(0, cols - 1) goal = (goalCoordX, goalCoordY) rewards[goalCoordX][goalCoordY] = goalReward obstacles = [] while nObstacles > 0: obs = randint(0, rows - 1), randint(0, cols - 1) if not obs in obstacles and not obs == goal: obstacles.append(obs) nObstacles = nObstacles - 1 rewards[obs[0]][obs[1]] = obstacleReward return rewards, goal, obstacles def markGoalAndObstaclesOnGrid(grid, goal, obstacles): grid[goal[0]][goal[1]] = 'G' for o in obstacles: grid[o[0]][o[1]] = 'X' return grid # + [markdown] colab_type="text" id="evLPPBUGAmRU" # # Tests with deterministics gridworld environments # + colab={"base_uri": "https://localhost:8080/", "height": 2414} colab_type="code" id="SL4ajJPnOhZU" outputId="5dbdce19-efd8-4058-e620-13c0072a9a25" # First dummy smoke test to make sure everything is not absurdly wrong rewards = [ [-1, -1, -1], [-1, 100, -1], [-1, -1, -1] ] rows, cols = 3, 3 mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.printPolicy() mdp.repeatIterateValues(10) print () printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), (1,1), [])) # + colab={"base_uri": "https://localhost:8080/", "height": 2309} colab_type="code" id="LXzCBKj-O0pi" outputId="b109b700-c9eb-4c3e-d434-caf18acd7920" # Testing random test case for 10 rows and cols rows, cols = 10, 10 rewards, goal = generateRandomRewards(rows, cols, 100, 0) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.printPolicy() mdp.repeatIterateValues(5) printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, [])) # + colab={"base_uri": "https://localhost:8080/", "height": 833} colab_type="code" id="3Dyfhj1iRlY5" outputId="c633b0ff-eb8b-44e8-a5da-9a3f3382a9c7" # Grid world with obstacles (things are getting interesting) rows, cols = 5, 5 rewards, goal, obs = generateRandomRewardsWithObstacles(rows, cols, 100, 0, -1000, 5) print ("rewards") printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.printPolicy() mdp.repeatIterateValues(10) print() printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) # + colab={"base_uri": "https://localhost:8080/", "height": 5175} colab_type="code" id="FYJZ2xzpaUYw" outputId="39c2bbaa-1253-45d7-8972-fd468744b7f2" # This case proves my iterate until converge is not working propperly rewards = [ [0, 0, 0, -1000, 0], [0, -1000, 0, 0, -1000], [-1000, 0, 0, 0, 0], [0, -1000, 100, 0, 0], [0, 0, 0, 0, 0] ] goal = (3, 2) obs = [(1, 4), (3, 1), (2, 0), (1, 1), (0, 3)] print ("rewards") printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.iterateValuesUntilConverge() printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(10) printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) # + colab={"base_uri": "https://localhost:8080/", "height": 5175} colab_type="code" id="41V_R0MyZfEO" outputId="e342fdf7-a7c3-4baa-92e5-e5bd4d81d84c" # Another case where iterating until converge do not work rewards = [ [0, 0, 0, 0, 0], [0, 0, -1000, 0, -1000], [0, 0, 0, 0, 0], [0, -1000, -1000, -1000, -1000], [0, 0, 0, 0, 100] ] rows, cols = 5, 5 goal = (4, 4) obs = [(3, 1),(3, 2), (3, 3), (3, 4), (1, 2), (1, 4)] print ("rewards") printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.iterateValuesUntilConverge() printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(10) printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) # + colab={"base_uri": "https://localhost:8080/", "height": 5175} colab_type="code" id="9ltOyA_ef6vL" outputId="b182074a-6cc5-4a17-8c59-2eae7a183bba" # Lets have variable obstacles with variable penalties rewards = [ [0, 0, 0, 0, 0], [0, 0, -1000, 0, -1000], [0, 0, 0, 0, 0], [0, -250, -500, -750, -1000], [0, 0, 0, 0, 100] ] rows, cols = 5, 5 goal = (4, 4) obs = [(3, 1),(3, 2), (3, 3), (3, 4), (1, 2), (1, 4)] print ("rewards") printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.iterateValuesUntilConverge() printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(10) printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) # + colab={"base_uri": "https://localhost:8080/", "height": 9517} colab_type="code" id="J_rzSqXrgxKa" outputId="0e74447f-8465-48b7-ae49-8621d08b7eaf" # Lets now give negative reward for moving rewards = [ [-100, -100, -100, -100, -10], [-100, -100, -1000, -100, -1000], [-100, -100, -100, -100, -10], [-100, -250, -500, -750, -1000], [-100, -100, -100, -100, 100] ] rows, cols = 5, 5 goal = (4, 4) obs = [(3, 1),(3, 2), (3, 3), (3, 4), (1, 2), (1, 4)] print ("rewards") printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.iterateValuesUntilConverge() printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(20) printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) # + colab={"base_uri": "https://localhost:8080/", "height": 4889258} colab_type="code" id="Fexcl8xdd7LW" outputId="55e79d5d-663f-4717-afde-8d59409f46ce" # how long it takes to converge rows, cols = 100, 100 rewards, goal, obs = generateRandomRewardsWithObstacles(rows, cols, 100, 0, -1000, 100) print ("rewards") # printMatrix(rewards) print ("goal", goal) print ("obstacles", obs) print() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.iterateValuesUntilConverge() policy1 = mdp.getPolicy() # printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(10) policy2 = mdp.getPolicy() # printMatrix(markGoalAndObstaclesOnGrid(mdp.getPolicy(), goal, obs)) mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(50) policy3 = mdp.getPolicy() mdp = DeterministicGridWorldMDP(rewards, rows, cols) mdp.repeatIterateValues(100) policy4 = mdp.getPolicy() print(policy1 == policy2) print(policy2 == policy3) print(policy3 == policy4) # + # First dummy smoke test to make sure everything is not absurdly wrong rewards = [ [-1, -1, -1], [-1, 100, -1], [-1, -1, -1] ] rows, cols = 3, 3 stateActions = DeterministicGridWorldMDP.getDeterministicGridWorldDefaultActions(rewards, rows, cols) for s in stateActions: for a in stateActions[s]: print(str(a)) # print(stateActions.__dict__) # s = json.dumps(stateActions) # print(s)
Implementations/RLValueAndPolicyIterationGridWorld.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # San Francisco Housing Cost Analysis # # In this assignment, you will perform fundamental analysis for the San Francisco housing market to allow potential real estate investors to choose rental investment properties. # + # imports import panel as pn pn.extension('plotly') import plotly.express as px import pandas as pd import hvplot.pandas import matplotlib.pyplot as plt import numpy as np import os from pathlib import Path from dotenv import load_dotenv import warnings warnings.filterwarnings('ignore') # - # Read the Mapbox API key load_dotenv() map_box_api = os.getenv("mapbox") print(type(map_box_api)) # ## Load Data # Read the census data into a Pandas DataFrame file_path = Path("Data/sfo_neighborhoods_census_data.csv") sfo_data = pd.read_csv(file_path, index_col="year") sfo_data.head() # - - - # ## Housing Units Per Year # # In this section, you will calculate the number of housing units per year and visualize the results as a bar chart using the Pandas plot function. # # **Hint:** Use the Pandas `groupby` function. # # **Optional challenge:** Use the min, max, and std to scale the y limits of the chart. # # # Calculate the mean number of housing units per year (hint: use groupby) sfo_data_group = pd.DataFrame(sfo_data["housing_units"].groupby(by="year").mean() # Save the dataframe as a csv file file_path = Path("Output_Data/housing_units.csv") sfo_data_group.to_csv(file_path) # + # Use the Pandas plot function to plot the average housing units per year. # Note: You will need to manually adjust the y limit of the chart using the min and max values from above. sfo_data_group.hvplot(kind="bar",legend = False, title = "Housing Units in San Francisco from 2010 to 2016", ylabel = "Housing Units", xlabel ="Year") # Optional Challenge: Use the min, max, and std to scale the y limits of the chart # YOUR CODE HERE! # - # # - - - # ## Average Housing Costs in San Francisco Per Year # # In this section, you will calculate the average monthly rent and the average price per square foot for each year. An investor may wish to better understand the sales price of the rental property over time. For example, a customer will want to know if they should expect an increase or decrease in the property value over time so they can determine how long to hold the rental property. Plot the results as two line charts. # # **Optional challenge:** Plot each line chart in a different color. # + # Calculate the average sale price per square foot and average gross rent average_price = sfo_data[["sale_price_sqr_foot", "gross_rent"]].groupby(by = "year").mean() average_price all_price = sfo_data[["sale_price_sqr_foot", "gross_rent"]].groupby(by = "year") all_price.head() # + # Create two line charts, one to plot the average sale price per square foot and another for average montly rent # Line chart for average sale price per square foot sale_price = pd.DataFrame(sfo_data["sale_price_sqr_foot"].groupby(by="year").mean()) sale_price.hvplot(kind="line", title = "Average Price per SqFt by Year", xlabel = "Year", ylabel="Price per Sqft") # - filter_dataframe = combinedataframe[["column1","column2","column3"]].groupby(by="idstd") # Create .csv files file_path = Path("Output_Data/sale_price.csv") sale_price.to_csv(file_path) # + # Line chart for average montly rent gross_rent = pd.DataFrame(sfo_data["gross_rent"].groupby(by="year").mean()) gross_rent.hvplot(kind="line", title = "Average Gross Rent by Year", xlabel = "Year", ylabel = "Price per SqFt") # - # Create gross_rent.csv file_path = Path("Output_Data/gross_rent.csv") gross_rent.to_csv(file_path) # ## Average Prices by Neighborhood # # In this section, you will use hvplot to create two interactive visulizations of average prices with a dropdown selector for the neighborhood. The first visualization will be a line plot showing the trend of average price per square foot over time for each neighborhood. The second will be a line plot showing the trend of average montly rent over time for each neighborhood. # # **Hint:** It will be easier to create a new DataFrame from grouping the data and calculating the mean prices for each year and neighborhood # + # Group by year and neighborhood and then create a new dataframe of the mean values group_year = pd.DataFrame(sfo_data.groupby(["year","neighborhood"]).mean()) group_year.reset_index() # - # Use hvplot to create an interactive line chart of the average price per sq ft. # The plot should have a dropdown selector for the neighborhood avg_price_sqfoot = group_year["sale_price_sqr_foot"] avg_price_sqfoot.hvplot.line(groupby="neighborhood", label=" ",xlabel="Year", ylabel="Average Sale Price per Square Foot") # + ## Creates .csv file avg_price_sqfoot = pd.DataFrame(avg_price_sqfoot) file_path = Path("Output_Data/avg_sale_price.csv") avg_price_sqfoot.to_csv(file_path) # + # Use hvplot to create an interactive line chart of the average monthly rent. # The plot should have a dropdown selector for the neighborhood avg_monthly_rent = group_year["gross_rent"] avg_monthly_rent.hvplot.line(groupby="neighborhood", label=" ", ylabel="Average Rental Price per Square Foot", xlabel="Year") # - # ## The Top 10 Most Expensive Neighborhoods # # In this section, you will need to calculate the mean sale price per square foot for each neighborhood and then sort the values to obtain the top 10 most expensive neighborhoods on average. Plot the results as a bar chart. # + # Getting the data from the top 10 expensive neighborhoods to own group_neighborhood = sfo_data.groupby("neighborhood").mean() top_10 = group_neighborhood.sort_values("sale_price_sqr_foot",ascending=False).iloc[0:10] top_10_list = top_10.reset_index().iloc[0:10] top_10_graph # Create .csv file file_path = Path("Output_Data/top10_expensive.csv") top_10_graph.to_csv(file_path) # - # Plotting the data from the top 10 expensive neighborhoods top_10_bargraph = top_10_graph[["neighborhood","sale_price_sqr_foot"]].hvplot.bar(title = "Top 10 Expensive Neighborhoods in SFO",x="neighborhood",xlabel="Neighborhood", ylabel ="Avg Sale Price per Square Foot", rot=90, height=500) top_10_bargraph # - - - # ## Comparing cost to purchase versus rental income # # In this section, you will use `hvplot` to create an interactive visualization with a dropdown selector for the neighborhood. This visualization will feature a side-by-side comparison of average price per square foot versus average montly rent by year. # # **Hint:** Use the `hvplot` parameter, `groupby`, to create a dropdown selector for the neighborhood. # + # Fetch the previously generated DataFrame that was grouped by year and neighborhood group_year.head() # Create .csv file file_path = Path("Output_Data/most_expensive.csv") group_year.to_csv(file_path) # - # Plotting the data from the top 10 expensive neighborhoods group_year.hvplot.bar(groupby="neighborhood", x ="year", y = ['gross_rent','sale_price_sqr_foot'], rot = 90) # - - - top10_neighborhood_by_year = group_year[group_year["neighborhood"].isin(top_10_graph) # ## Neighborhood Map # # In this section, you will read in neighborhoods location data and build an interactive map with the average house value per neighborhood. Use a `scatter_mapbox` from Plotly express to create the visualization. Remember, you will need your Mapbox API key for this. # ### Load Location Data # Load neighborhoods coordinates data file_path = Path("Data/neighborhoods_coordinates.csv") neighbor_hood_coordinates = pd.read_csv(file_path, index_col = "Neighborhood").dropna() neighbor_hood_coordinates # ### Data Preparation # # You will need to join the location data with the mean values per neighborhood. # # 1. Calculate the mean values for each neighborhood. # # 2. Join the average values with the neighborhood locations. # + # Calculate the mean values for each neighborhood mean_neighborhood = sfo_data.groupby("neighborhood").mean() mean_neighborhood = mean_neighborhood.rename_axis(None, axis=1).rename_axis("Neighborhood",axis=0) mean_neighborhood = mean_neighborhood.round({'sale_price_sqr_foot':2, "gross_rent":2}) mean_neighborhood # + # Join the average values with the neighborhood locations coordinates_and_rent = pd.concat([mean_neighborhood,neighbor_hood_coordinates],axis=1,join="inner") # Create .csv file file_path = Path("Output_Data/neighbor_map.csv") coordinates_and_rent.to_csv(file_path) # - # ### Mapbox Visualization # # Plot the average values per neighborhood using a Plotly express `scatter_mapbox` visualization. # Set the mapbox access token px.set_mapbox_access_token(map_box_api) # Create a scatter mapbox to analyze neighborhood info map_plot = px.scatter_mapbox( coordinates_and_rent, lat = "Lat", lon = "Lon", size = "sale_price_sqr_foot", color = "gross_rent", title ="Average Sales Price per Square Foot and Gross Rent In San Francisco", zoom = 10, hover_name = coordinates_and_rent.index ) map_plot.show() # - - - # ## Cost Analysis - Optional Challenge # # In this section, you will use Plotly express to create visualizations that investors can use to interactively filter and explore various factors related to the house value of the San Francisco's neighborhoods. # # ### Create a DataFrame showing the most expensive neighborhoods in San Francisco by year # Fetch the data from all expensive neighborhoods per year. df_expensive_neighborhoods_per_year = group_year[group_year["neighborhood"].isin(top_10_graph["neighborhood"])] # ### Create a parallel coordinates plot and parallel categories plot of most expensive neighborhoods in San Francisco per year # # + # Parallel Categories Plot # YOUR CODE HERE! # + # Parallel Coordinates Plot # YOUR CODE HERE! # - # ### Create a sunburst chart to conduct a costs analysis of most expensive neighborhoods in San Francisco per year # + # Sunburst Plot # YOUR CODE HERE! # -
rental_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from IPython.core.display import display, HTML import pandas as pd import numpy as np import copy import os # %load_ext autoreload # %autoreload 2 results_df_2 = pd.read_csv('results_df_2.csv') from matplotlib.pyplot import hist hist(results_df_2["k"]) hist(results_df_2["p"]) from scipy.stats import kendalltau kendalltau(results_df_2["k"],results_df_2["metric_mean"]) kendalltau(results_df_2["p"],results_df_2["metric_mean"]) # + import matplotlib.pyplot as plt import numpy as np plt.scatter(results_df_2["metric_mean"], results_df_2["k"]) plt.xlabel("learn2rank performance") plt.ylabel("k") plt.legend(loc='upper left') plt.show() # + import sys sys.path.insert(0,"/local/rankability_toolbox") PATH_TO_RANKLIB='/local/ranklib' # - import pyrankability import pyltr with open('MQ2008-list/Fold1/train.txt') as trainfile, \ open('MQ2008-list/Fold1/vali.txt') as valifile, \ open('MQ2008-list/Fold1/test.txt') as evalfile: TX, Ty, Tqids, Tdids = pyltr.data.letor.read_dataset(trainfile) VX, Vy, Vqids, Vdids = pyltr.data.letor.read_dataset(valifile) EX, Ey, Eqids, Edids = pyltr.data.letor.read_dataset(evalfile) def subset_max_rank(X,y,qids,dids,max_rank = 10): keep_inxs = np.where(y<=max_rank)[0] X = X[keep_inxs,:] y = y[keep_inxs] qids = qids[keep_inxs] dids = dids[keep_inxs] return X,y,qids,dids TX10,Ty10,Tqids10,Tdids10 = subset_max_rank(TX,Ty,Tqids,Tdids) VX10,Vy10,Vqids10,Vdids10 = subset_max_rank(VX,Vy,Vqids,Vdids) EX10,Ey10,Eqids10,Edids10 = subset_max_rank(EX,Ey,Eqids,Edids) TX10.shape # + metric = pyltr.metrics.KendallTau() # Only needed if you want to perform validation (early stopping & trimming) monitor = pyltr.models.monitors.ValidationMonitor( VX10, Vy10, Vqids10, metric=metric, stop_after=250) model = pyltr.models.LambdaMART( metric=metric, n_estimators=1000, learning_rate=0.01, max_features=0.5, query_subsample=0.5, max_leaf_nodes=10, min_samples_leaf=64, verbose=1 ) model.fit(TX10, Ty10, Tqids10, monitor=monitor) # - joblib.dump(model,"model.joblib.z") def predict_process(model,metric,X,y,qids,dids): pred = model.predict(X) unique_qids = np.unique(qids) inxs_qid = {} rank_pred_qid = {} metric_mean_random_qid = {} metric_mean_qid = {} for qid in unique_qids: inxs_qid[qid] = np.where(qids == qid)[0] pred_qid = pred[inxs_qid[qid]] inxs_argsort = np.argsort(pred_qid) rank_pred_qid[qid] = np.zeros((len(inxs_qid[qid]),),dtype=int) rank_pred_qid[qid][inxs_argsort] = np.arange(rank_pred_qid[qid].shape[0],dtype=int)+1 metric_mean_random_qid[qid] = metric.calc_mean_random(qids[inxs_qid[qid]], y[inxs_qid[qid]]) metric_mean_qid[qid] = metric.calc_mean(qids[inxs_qid[qid]], y[inxs_qid[qid]], pred_qid) return rank_pred_qid, metric_mean_random_qid,metric_mean_qid rank_pred_qid,metric_mean_random_qid,metric_mean_qid = predict_process(model,metric,EX10,Ey10,Eqids10,Edids10) unique_qids = list(rank_pred_qid.keys()) results_df = pd.DataFrame({"qid": unique_qids,"metric_mean":[metric_mean_qid[k] for k in unique_qids],"metric_mean_random":[metric_mean_random_qid[k] for k in unique_qids]}) results_df.to_csv("results_df.csv",index=False) results_df np.savetxt('X.csv',EX10,"%.4f",delimiter=",") np.savetxt('qids.csv',Eqids10,'%s',delimiter=',') results_df.sort_values(by="metric_mean",ascending=False) def get_X(X,qids,qid): inxs = np.where(qids == qid)[0] return X[inxs,:] sorted_qids = results_df.sort_values(by="metric_mean",ascending=True)['qid'] def construct_D1(Xqid,frac=0.3): n = Xqid.shape[0] m = Xqid.shape[1] D = np.zeros((n,n),dtype=int) C = np.zeros((n,n),dtype=int) for i in range(n): for j in range(n): if i == j: continue C[i,j] = len(np.where(Xqid[i,:] > Xqid[j,:])[0]) D[C > m*frac] = 1 return D,C from sklearn.feature_selection import VarianceThreshold # + from dask.distributed import Client from scipy.stats import zscore client = Client("127.0.0.1:8786") # + ks = [] Ps = [] ps = [] i = 0 for qid in results_df["qid"]: var_thres = VarianceThreshold() Xqid = get_X(EX10,Eqids10,qid) var_thres.fit(Xqid) Xqid_norm = zscore(var_thres.transform(Xqid),axis=0) D,C = construct_D1(Xqid_norm,frac=0.4) np.savetxt("/dev/shm/D.csv",D,"%d",delimiter=",") k,P = pyrankability.pruning_paper_dask2.find_P("/dev/shm/D.csv",4,100,bilp_method="orig",prune_history=False,client=client) #k,P = pyrankability.bilp.bilp_orig(D) pyrankability.pruning_paper_dask3.find_P ks.append(k) Ps.append(P) ps.append(len(P)) results_df['k'] = ks results_df['p'] = ps # - results_df.to_csv("results_df.csv",index=False) ks,ps results_df['k'] = ks results_df['p'] = ps results_df var_thres = VarianceThreshold() Xqid = get_X(EX10,Eqids10,'18356') var_thres.fit(Xqid) Xqid_norm = np.round(10*zscore(var_thres.transform(Xqid),axis=0))/10 D,C = construct_D1(Xqid_norm) k,P = pyrankability.bilp.bilp_orig(D,max_solutions=100) k,len(P) D from scipy.stats import zscore from sklearn.feature_selection import VarianceThreshold var_thres = VarianceThreshold() var_thres.fit(Xqid) Xqid_norm = zscore(var_thres.transform(Xqid),axis=0) bilp_results = pyrankability.bilp.bilp_orig_opt_weights(Xqid_norm) AP = bilp_results[0] # ## Construct the D matrix Tdocids = [did.split()[2] for did in Tdids] Dmatrices = [] Dchanges = [] for qid in np.unique(Tqids): inxs = np.where(Tqids == qid)[0] docids = np.array(Tdocids)[inxs] D = np.zeros((len(docids),len(docids)),dtype=int) for i in range(len(docids)): for j in range(i+1,len(docids)): if Ty[i] != 0 and Ty[j] != 0: D[j,i] = 1 D[i,j] = 1 #D[i,j] = Ty[i]*1./Ty[j] #D[j,i] = Ty[j]*1./Ty[i] elif Ty[i] > Ty[j]: D[i,j] = 1 #D[i,j] = Ty[i] elif Ty[j] > Ty[i]: D[j,i] = 1 #D[j,i] = Ty[j] #np.round(10*D).astype(int) Dmatrices.append(D) Dtilde, changes, output = pyrankability.improve.greedy(D,1,verbose=False) Dchanges.append(changes) Ty_norm = Ty/np.max(Ty) np.min(Ty_norm) # + num_qids_to_include=20 unique_qids = np.unique(Tqids) qids_inxs = np.random.choice(len(unique_qids), num_qids_to_include) inxs_to_add = [] for qid in unique_qids[qids_inxs]: inxs_to_add += list(np.where(Tqids == qid)[0]) print(len(inxs_to_add)) TX_new = TX[inxs_to_add,:] Ty_new = Ty[inxs_to_add] Tqids_new = Tqids[inxs_to_add] Tdids_new = Tdids[inxs_to_add] # + import matplotlib.pyplot as plt pd.DataFrame(TX).corr() # - pyltr.models. # + #metric = pyltr.metrics.NDCG(k=10) metric = pyltr.metrics.KendallTau() # Only needed if you want to perform validation (early stopping & trimming) monitor = pyltr.models.monitors.ValidationMonitor( VX[:10000,:], Vy[:10000], Vqids[:10000], metric=metric, stop_after=250) model = pyltr.models.LambdaMART( metric=metric, n_estimators=2, learning_rate=0.5, max_features=0.5, query_subsample=0.5, max_leaf_nodes=10, min_samples_leaf=64, verbose=1 ) model.fit(TX[:1000,:], Ty_norm[:1000], Tqids[:1000], monitor=monitor) Epred = model.predict(EX) print('Random ranking:', metric.calc_mean_random(Eqids, Ey)) print('Our model:', metric.calc_mean(Eqids, Ey, Epred)) # - Ey # ## Now run the code that figures out what to select # import joblib results = joblib.load('results.joblib.z') def extract_did(did): return did.split(" ")[2] counts = {} for qid in results.keys(): i,j,action = results[qid]['changes'][0] inxs_i = results[qid]['inxs'][i] inxs_j = results[qid]['inxs'][j] did_i = extract_did(Tdids[inxs_i]) did_j = extract_did(Tdids[inxs_j]) if did_i not in counts: counts[did_i] = 0 if did_j not in counts: counts[did_j] = 0 counts[did_i]+=1 counts[did_j]+=1 counts_df = pd.DataFrame(list(counts.items()),columns=["docid","count"]) counts_df counts_df.sort_values(by="count",ascending=False) threshold=1 inxs = np.where(counts_df["count"] >= threshold)[0] n_add = len(inxs) Edocids = [extract_did(did) for did in Edids] counts_e_df = pd.DataFrame(list(dict(Counter(Edocids)).items()),columns=["docid","count"]) Edocids counts_df["docid"] "GX000-08-9442355" in counts_df["docid"].values # GX000-00-0000000 counts_e_df["include"] = 0 for i,docid in enumerate(counts_df["docid"].values): inx = np.where(counts_e_df["docid"] == docid)[0] if len(inx) > 0: counts_e_df["include"].iloc[inx] = 1 counts_e_df["qid"] = 0 unique_Eqids = np.unique(Eqids) qcounts = [] for qid in unique_Eqids: inxs = np.where(Eqids==qid)[0] qid_docs = np.array(Edocids)[inxs] c = 0 for docid in qid_docs: if docid in counts.keys(): c += counts[docid] qcounts.append(c) picking_qids = pd.DataFrame({"count":qcounts,"qid": unique_Eqids}) top = picking_qids.sort_values(by="count",ascending=False).iloc[0:10,:] inxs_to_add = [] for qid in top["qid"]: print(qid) inxs_to_add += list(np.where(Eqids == qid)[0]) TX_new = np.vstack((TX,EX[inxs_to_add,:])) Ty_new = np.array(list(Ty)+list(Ey[inxs_to_add])) Tqids_new = np.array(list(Tqids)+list(Eqids[inxs_to_add])) Tdids_new = np.array(list(Tdids)+list(Edids[inxs_to_add])) # + metric = pyltr.metrics.NDCG(k=10) # Only needed if you want to perform validation (early stopping & trimming) monitor = pyltr.models.monitors.ValidationMonitor( VX, Vy, Vqids, metric=metric, stop_after=250) model = pyltr.models.LambdaMART( metric=metric, n_estimators=1000, learning_rate=0.02, max_features=0.5, query_subsample=0.5, max_leaf_nodes=10, min_samples_leaf=64, verbose=1, ) model.fit(TX_new, Ty_new, Tqids_new, monitor=monitor) # - EX_new = np.delete(EX,inxs_to_add,axis=0) Eqids_new = np.delete(Eqids,inxs_to_add) Ey_new = np.delete(Ey,inxs_to_add) Epred = model.predict(EX_new) print('Random ranking:', metric.calc_mean_random(Eqids_new, Ey_new)) print('Our model:', metric.calc_mean(Eqids_new, Ey_new, Epred)) EX_new.shape,EX.shape,Eqids.shape,Eqids_new.shape,Ey_new.shape counts_e_df.sort_values(by="count",ascending=False) new_Ty = Ey[inxs] from collections import Counter results = dict(Counter(Tdocids)) np.sort(list(results.values())) # + from numpy import ix_ import numpy as np # - import pyrankability changes if D.shape[0] <= 8: # Only solve small problems search = pyrankability.exact.ExhaustiveSearch(Dsmall) search.find_P() print(pyrankability.common.as_json(search.k,search.P,{})) p = len(search.P) k = search.k def greedy(D,l): D = np.copy(D) # Leave the original untouched for niter in range(l): n=D.shape[0] k,P,X,Y,k2 = pyrankability.lp.lp(D) mult = 100 X = np.round(X*mult)/mult Y = np.round(Y*mult)/mult T0 = np.zeros((n,n)) T1 = np.zeros((n,n)) inxs = np.where(D + D.transpose() == 0) T0[inxs] = 1 inxs = np.where(D + D.transpose() == 2) T1[inxs] = 1 T0[np.arange(n),np.arange(n)]= 0 T1[np.arange(n),np.arange(n)] = 0 DOM = D + X - Y Madd=T0*DOM # note: DOM = P_> in paper M1 = Madd # Copy Madd into M, % Madd identifies values >0 in P_> that have 0-tied values in D M1[Madd<=0] = np.nan # Set anything <= 0 to NaN min_inx = np.nanargmin(M1) # Find min value and index bestlinktoadd_i, bestlinktoadd_j = np.unravel_index(min_inx,M1.shape) # adding (i,j) link associated with # smallest nonzero value in Madd is likely to produce greatest improvement in rankability minMadd = M1[bestlinktoadd_i, bestlinktoadd_j] Mdelete=T1*DOM # note: DOM = P_> in paper Mdelete=Mdelete*(Mdelete<1) # Mdelete identifies values <1 in P_> that have 1-tied values in D bestlinktodelete_i, bestlinktodelete_j=np.unravel_index(np.nanargmax(Mdelete), Mdelete.shape) # deleting (i,j) link associated with # largest non-unit (less than 1) value in Mdelete is likely to produce greatest improvement in rankability maxMdelete = Mdelete[bestlinktodelete_i, bestlinktodelete_j] # This next section modifies D to create Dtilde Dtilde = np.copy(D) # initialize Dtilde # choose whether to add or remove a link depending on which will have the biggest # impact on reducing the size of the set P # PAUL: Or if we only want to do link addition, you don't need to form # Mdelete and find the largest non-unit value in it. And vice versa, if # only link removal is desired, don't form Madd. if (1-minMadd)>maxMdelete and p>=2: formatSpec = 'The best one-link way to improve rankability is by adding a link from %d to %d.\nThis one modification removes about %.10f percent of the rankings in P.'%(bestlinktoadd_i,bestlinktoadd_j,(1-minMadd)*100) print(formatSpec) Dtilde[bestlinktoadd_i,bestlinktoadd_j]=1 # adds this link, creating one-mod Dtilde elif 1-minMadd<maxMdelete and p>=2: formatSpec = 'The best one-link way to improve rankability is by deleting the link from %d to %d.\nThis one modification removes about %.10f percent of the rankings in P.' % (bestlinktodelete_i,bestlinktodelete_j,maxMdelete*100) print(formatSpec) Dtilde[bestlinktodelete_i,bestlinktodelete_j] = 0 # removes this link, creating one-mod Dtilde D = Dtilde Dtilde = greedy(D,1) # + search = pyrankability.exact.ExhaustiveSearch(Dtilde) search.find_P() print(pyrankability.common.as_json(search.k,search.P,{})) # - bestlinktoadd_i, bestlinktoadd_j % Form modification matrices Madd (M_+) and Mdelete (M_-), which are used % to determine which link modification most improves rankability Mdelete=T1.*DOM; % note: DOM = P_> in paper Mdelete=Mdelete.*(Mdelete<1); % Mdelete identifies values <1 in P_> that have 1-tied values in D maxMdelete=max(max(Mdelete)); [bestlinktodelete_i bestlinktodelete_j]=find(Mdelete==maxMdelete); % deleting (i,j) link associated with % largest non-unit (less than 1) value in Mdelete is likely to produce greatest improvement in rankability % This next section modifies D to create Dtilde Dtilde=D; % initialize Dtilde % choose whether to add or remove a link depending on which will have the biggest % impact on reducing the size of the set P % PAUL: Or if we only want to do link addition, you don't need to form % Mdelete and find the largest non-unit value in it. And vice versa, if % only link removal is desired, don't form Madd. if 1-minMadd>maxMdelete & p>=2 formatSpec = 'The best one-link way to improve rankability is by adding a link from %4.f to %4.f.\nThis one modification removes about %2.f percent of the rankings in P.'; fprintf(formatSpec,bestlinktoadd_i(1),bestlinktoadd_j(1),(1-minMadd)*100) Dtilde(bestlinktoadd_i(1),bestlinktoadd_j(1))=1; % adds this link, creating one-mod Dtilde elseif 1-minMadd<maxMdelete & p>=2 formatSpec = 'The best one-link way to improve rankability is by deleting the link from %4.f to %4.f.\nThis one modification removes about %2.f percent of the rankings in P.'; fprintf(formatSpec,bestlinktodelete_i(1),bestlinktodelete_j(1),maxMdelete*100) Dtilde(bestlinktodelete_i(1),bestlinktodelete_j(1))=0; % removes this link, creating one-mod Dtilde end % set D=Dtilde and repeat until l link modifications have been made or % p=1 D=Dtilde;
misc/learn2rank.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/PrashantDandriyal/Speech-to-Text/blob/master/Kaldi_OpenDevLibrary.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="PNNs504vyZoD" colab_type="text" # Following reference like official OpenVINO v2020.1 docs for [Offline Demo](https://docs.openvinotoolkit.org/latest/_inference_engine_samples_speech_libs_and_demos_Offline_speech_recognition_demo.html) and [another](https://docs.openvinotoolkit.org/latest/_inference_engine_samples_speech_libs_and_demos_Speech_libs_and_demos.html) doc to understand this method thoroughly. # # **Note: The version for OpenVINO matters as it has been observed that different versions have slighly different information** # # To understand the KALDI files, see [this](https://stackoverflow.com/questions/54428601/kaldis-objects-explained-in-laymans-term) # + id="t_eL16xQgdKx" colab_type="code" outputId="4edcf583-ef96-4969-ad40-6df90120a4fb" colab={"base_uri": "https://localhost:8080/", "height": 1000} # #!cd "/content/" # !git clone "https://github.com/lowerquality/gentle.git" "/content/gentle" #For audio preprocessing and manipulation import wave # !apt-get install libsox-fmt-all libsox-dev sox # !pip install ffmpeg # + id="BL5atqo5ucnb" colab_type="code" colab={} # # !cd doesn't change the working directory for the entire environment. So, used % (see this: https://stackoverflow.com/questions/48298146/changing-directory-in-google-colab-breaking-out-of-the-python-interpreter) # ##%cd /content/gentle/ # #!/content/gentle/install.sh # + [markdown] id="-QIdgwxSYHxE" colab_type="text" # ###Install OpenVINO toolkit and dependencies # + id="m5pa8HAQSelr" colab_type="code" outputId="c729a41d-6fd1-439b-a850-f85f54fac1d5" colab={"base_uri": "https://localhost:8080/", "height": 1000} # #%cd /content/ # !wget "https://raw.githubusercontent.com/alihussainia/OpenDevLibrary/master/openvino_initialization_script.py" # !python openvino_initialization_script.py # + [markdown] id="YijAbaNCYZJ1" colab_type="text" # ###Download model files # + id="eYLQSxDyVkwH" colab_type="code" colab={} # #!wget --force-html -i "https://download.01.org/openvinotoolkit/models_contrib/speech/kaldi/wsj_dnn5b_smbr/" -P "/content/model_files" # + [markdown] id="EVMJG0KIYdy2" colab_type="text" # ###Convert model to IR format # *Not required in case of demo, as the IR files (.bin and .xml) are already provided.* # + id="QYvqp5ZfVtVd" colab_type="code" colab={} # #!python3 /opt/intel/openvino/deployment_tools/model_optimizer/mo.py --input_model /content/model_files/wsj_dnn5b.nnet --counts /content/model_files/wsj_dnn5b.counts # + [markdown] id="m3iFqQYJcBCe" colab_type="text" # ###Convert WAV file to input feature containing ARK file using the [docs](https://docs.openvinotoolkit.org/latest/_docs_MO_DG_prepare_model_convert_model_kaldi_specific_Aspire_Tdnn_Model.html) here. # # # # 1. Download a Kaldi repository. # 2. Build it using instructions in README.md in the repository. # # 2.1. Go to *tools/* and follow INSTALL instructions there. # # 2.2. Go to *src/* and follow INSTALL instructions there. # 3. Prepare Data (Convert .wav file to .ark) # # # + [markdown] id="0U4nAGtu8A-g" colab_type="text" # ###1. Download a Kaldi repository. # + id="Iv2pcYb1XDse" colab_type="code" outputId="a7054a51-4ced-4b79-cd86-ba62af5415da" colab={"base_uri": "https://localhost:8080/", "height": 127} # !git clone "https://github.com/kaldi-asr/kaldi.git" # + [markdown] id="aCjkqBbJ8GVN" colab_type="text" # ###2. Build it using instructions in README.md in the repository. # # The instructions for the LINUX version, as per the README, can be found [HERE](https://github.com/kaldi-asr/kaldi/blob/master/tools/INSTALL) # # First, change the working directory # + id="ReQ_3BWgIII9" colab_type="code" colab={} # #%cd /content/kaldi/tools # + [markdown] id="aBGHmT1cH2C5" colab_type="text" # ####2.1 Go to *tools/* and follow INSTALL instructions there. # # 2.1.1 Run *check_dependencies.sh* # + id="-igavFk8eTAg" colab_type="code" colab={} # #!extras/check_dependencies.sh # + [markdown] id="andmyFAa_i5u" colab_type="text" # ###Missing packages are manually installed below, depending on the output of the above cell, until the *check_dependencies.sh* returns **all OK** # + id="AktB0QaC_lB2" colab_type="code" colab={} # #!sudo apt-get install sox subversion #Asked to be installed by output # #!/content/kaldi/tools/extras/install_mkl.sh #Asked to be installed by output # + id="SNUoUW14zfc7" colab_type="code" colab={} # #!extras/check_dependencies.sh # + [markdown] id="AJHfRfrSHpDK" colab_type="text" # 2.1.2 Run Make # # + id="SMKcovYPzo9A" colab_type="code" colab={} # #!make -j 4 #Using multiple CPUs as it Takes a LONG time to run. #Replace with simply "!make" if an error is logged. # + [markdown] id="fn6fuF6WM9wX" colab_type="text" # 2.2. Go to *src/* and follow INSTALL instructions there. # + id="ILk6VQwb0fQT" colab_type="code" outputId="fd4cb8bd-b204-4c6c-9ffc-1ca3c5f55253" colab={"base_uri": "https://localhost:8080/", "height": 35} '''%cd /content/kaldi/src !./configure --shared !make depend -j 8 !make -j 8''' # + [markdown] id="XvAApO_qL1Ih" colab_type="text" # ###Downloading reduired files # - Intel Models # - Create configuration file # - Required pre-requisites for LibriSpeech Model # - Related Model files # + id="3TdYLc4MxrHu" colab_type="code" colab={} # #!cp "/blowup.wav" "/opt/intel/openvino_2020.1.023/deployment_tools/demo/" # + [markdown] id="tcET4FGcd27T" colab_type="text" # ###Initialize the OpenVINO environment before running the actual demo. The script will run and test **Online** and **Offline** demos to validate if everything went normal. # # **Note: If working on Google Collab, the online demo may not work and hence the execution may seem to get entrapped into a never ending cycle. To avoid this you must replace the "demo_speech_recognition.sh" file with a custom one.** # # So, we replace the command by commenting it # # # ``` # #/opt/intel/openvino_2020.1.023/deployment_tools/demo/demo_speech_recognition.sh # ``` # and run the below command instead. # # # + id="JUKqLJ1PdHiW" colab_type="code" outputId="04057e87-b31d-41c3-d770-1c9a0b1ba080" colab={"base_uri": "https://localhost:8080/", "height": 239} # #!wget -P "/content/" "https://raw.githubusercontent.com/PrashantDandriyal/Speech-to-Text/master/demo_speech_recognition.sh" # #!rm "/opt/intel/openvino_2020.1.023/deployment_tools/demo/demo_speech_recognition.sh" # #!cp -f "/content/demo_speech_recognition.sh" "/opt/intel/openvino_2020.1.023/deployment_tools/demo/demo_speech_recognition.sh" # + id="M2JX3Z0vYAey" colab_type="code" outputId="2f087265-9118-411e-e4a0-ba2f41ff375f" colab={"base_uri": "https://localhost:8080/", "height": 55} # !/opt/intel/openvino_2020.1.023/deployment_tools/demo/demo_speech_recognition.sh # + [markdown] id="Wth8Takp4gHe" colab_type="text" # ###Running Offline DEMO # *(To use it for custom WAV file, edit the "run_demo.sh" file and add the path to your file)* # # The output generated by the *run_demo.sh* is similar to : # # # >[ INFO ] Using feature transformation /root/openvino_models/ir/intel/lspeech_s5_ext/FP32/lspeech_s5_ext.feature_transform # [ INFO ] InferenceEngine API ver. 2.1 (build: 37988) # [ INFO ] Device info: # [ INFO ] CPU: MKLDNNPlugin ver. 2.1 # [ INFO ] Batch size: 8 # [ INFO ] Model loading time: 49.93 ms # Recognition result: # **HOW ARE YOU DOING** # # We extract this output (in a naive way) by simply asking *sed* method to filter the console output as we wish to use only the text generated from the speech. # # Next, we save this output to a txt file for areanas. # # # + id="m3ZTBcwZ0DON" colab_type="code" outputId="78dbedc5-b8e9-404c-f2e3-8d7ba46a255f" colab={"base_uri": "https://localhost:8080/", "height": 257} import os #Add the path to your WAV file # !wget "https://raw.githubusercontent.com/PrashantDandriyal/Speech-Censor-Bot/master/negan.wav" wav_path = "/content/negan.wav" #wav_path = "/content/trump_cussing.wav" fixed_name = "/content/how_are_you_doing.wav" old_name = os.path.basename(wav_path) print(old_name) new_name = "how_are_you_doing.wav" text_path = "/content/out_text.txt" # + [markdown] id="dsR0jFzXQ55V" colab_type="text" # As per the OpenVINO v2020.1 docs [here](https://docs.openvinotoolkit.org/latest/_inference_engine_samples_speech_libs_and_demos_Offline_speech_recognition_demo.html), WAV file needs to be in following format: RIFF WAVE PCM 16bit, 16kHz, 1 channel i.e., # # >Sample size : 16bit # Sampling Rate : 16kHz # Number of channels : 1 # # We preprocess audio and convert it if needed and replace the old file with new # ref [link1](https://explainshell.com/explain?cmd=sox+-r+48000+-b+16+-e+unsigned-integer+IMG_5367.raw+image.ogg+) # + id="XdRhp_A2JWWV" colab_type="code" outputId="64a5c703-10d8-40e6-c956-ea6098ade970" colab={"base_uri": "https://localhost:8080/", "height": 476} import wave def preprocess(org_aud_path): tx = wave.open(org_aud_path, 'r') print ("Initial Parameters:") # !sox --i "$org_aud_path" if(tx.getnchannels() > 1): #Convert stereo to mono #and replace the original with new # !sox "$org_aud_path" processed.wav channels 1 # !rm -r "$org_aud_path" # !mv "processed.wav" "$org_aud_path" print("Converted Stereo to Mono") if(tx.getframerate() != 16000): #Downsample (if > 16k) and Upsample (if < 16k) #and replace the original with new # !sox "$org_aud_path" processed.wav rate 16000 #sox "$org_aud_path"-48000.wav -r 12000 output.wav downsample 4 # !rm -r "$org_aud_path" # !mv "processed.wav" "$org_aud_path" print("Changed sample rate to 16k") print("Processed file into the same path with name 'processed.wav' ") preprocess(wav_path) print("Update file parameters") # !sox --i "$wav_path" # + id="btGtRO5KdOh4" colab_type="code" outputId="862b3b81-37aa-4b70-fe09-f878cb8d2cb1" colab={"base_uri": "https://localhost:8080/", "height": 35} # %cd "/content/" #Rename file here OR edit the bash file # !mv "$wav_path" "how_are_you_doing.wav" #Replace the file for test on custom file by removing it first # !rm -r "/opt/intel/openvino/deployment_tools/demo/how_are_you_doing.wav" # !cp "/content/how_are_you_doing.wav" "/opt/intel/openvino/deployment_tools/demo/" # + [markdown] id="y7g3KAVYpEWU" colab_type="text" # # + id="yHXnrFW-3a2H" colab_type="code" outputId="f0ced344-fd1d-4ef9-941d-52beafcd0643" colab={"base_uri": "https://localhost:8080/", "height": 109} # !/opt/intel/openvino/data_processing/audio/speech_recognition/demos/offline_speech_recognition_demo/run_demo.sh #Running again to save the output # !/opt/intel/openvino/data_processing/audio/speech_recognition/demos/offline_speech_recognition_demo/run_demo.sh | sed '1,/Recognition result/d' > /content/out_text.txt # + [markdown] id="3MIlKEWWeJxH" colab_type="text" # ###*aeneas* automatically generates a synchronization map between a list of text fragments and an audio file containing the narration of the text. In computer science this task is known as (automatically computing a) forced alignment. # + [markdown] id="e24_xOZvpjaz" colab_type="text" # ####WAV file path: # **"/opt/intel/openvino/deployment_tools/demo/how_are_you_doing.wav"** # # ####Configuration file path: # **"/root/openvino_models/ir/intel/lspeech_s5_ext/FP32/speech_lib.cfg"** # + id="E4eMPJZn5zOX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="d5197627-a440-4b33-b094-02525a82d531" # !sox --i "$wav_path" # + id="EdspONrp_t5P" colab_type="code" colab={} # #!find / -iname out_text.txt # !git clone --help # + [markdown] id="gtdipOPyPyop" colab_type="text" # ##This part currently doesn't work.. So manually downloading the syncmap form "http://gentle-demo.lowerquality.com/transcriptions/416f5371/" # # + id="4FNFcN7101nY" colab_type="code" colab={} # #!cd "/content/" # #!git clone "https://github.com/lowerquality/gentle.git" "/content/gentle" # # !cd doesn't change the working directory for the entire environment. So, used % (see this: https://stackoverflow.com/questions/48298146/changing-directory-in-google-colab-breaking-out-of-the-python-interpreter) # #%cd /content/gentle/ # #!/content/gentle/install.sh # + id="rgQoh0nwQy8j" colab_type="code" colab={} json_path = "/content/align.json" # + [markdown] id="6R1-d5TNP2Ud" colab_type="text" # ###Time to censor # # # 1. Get the list of profanity words from [here](https://raw.githubusercontent.com/PrashantDandriyal/Google-profanity-words/master/list.txt) # 2. Detect any such word # # # + id="Rahan50yQ-ma" colab_type="code" outputId="84f1cff5-a596-41ca-937b-eb767f83042b" colab={"base_uri": "https://localhost:8080/", "height": 257} # %cd /content/ # !wget "https://raw.githubusercontent.com/PrashantDandriyal/Google-profanity-words/master/list.txt" profane_text = "/content/list.txt" # + id="Ou4FwO8AYs6n" colab_type="code" colab={} #Make a list out of all the words in the profane_text txt file. #This is to avoid repetitive file searching with open(profane_text) as f: cuss_list = [i.strip() for i in f] f.close() #The word "F*Ck" has been recognised as "For", so censoring it cuss_list.append("for") # + id="ezvrN9BdZUwW" colab_type="code" colab={} #Parsing the json content to a easily-accesible dictionary import json import pandas as pd with open(json_path, 'r') as f: handle = json.load(f) df = pd.DataFrame(columns=['word', 'start', 'end']) rows_list = [] for i in handle['words']: #print(i) dict1 = {} if((i['word']).lower() in cuss_list): try: dict1.update({"word":i['word'], "start":i['start'], "end":i['end']}) rows_list.append(dict1) except KeyError: #Sometimes the word is not properly detected and the entry is "'case': 'not-found-in-audio'" pass df = pd.DataFrame(rows_list) #df.set_index("word", inplace=True) #print(df.head()) # + id="EotPSxYpUkpg" colab_type="code" colab={} #traverse the entire transcript(text converted from speech) and look for any of such word test_file = open(text_path,"r") dff = pd.DataFrame(columns=['swear', 'start', 'end']) swear_dict_list = [] with open(text_path, 'r') as f: for line in f: for word in line.split(): if(word.upper() in cuss_list): #Convert the word to Upper case d = {} d.update({"swear":word, "start":df.loc[word].start, "end":df.loc[word].end}) swear_dict_list.append(d) dff = pd.DataFrame(swear_dict_list) #df.set_index("word", inplace=True) # + [markdown] id="n8OtW0_2ic38" colab_type="text" # As we have obtained the durations of all the profane words in the speech, we will now suppress them by muting/fading the slice of audio. # + id="1TUWKqSbglav" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 90} outputId="f539ca6c-2f8e-47d6-b168-87d62607fe1a" # wav_path = "/opt/intel/openvino/deployment_tools/demo/how_are_you_doing.wav" #Format of SOX command to fade in. Refer to(https://stackoverflow.com/questions/20127095/using-sox-to-change-the-volume-level-of-a-range-of-time-in-an-audio-file) ''' fade [type] fade-in-length [stop-position(=) [fade-out-length]] sox -m -t wav "|sox -V1 inputfile.wav -t wav - fade t 0 2.2 0.4" -t wav "|sox -V1 inputfile.wav -t wav - trim 1.8 fade t 0.4 3.4 0.4 gain -6 pad 1.8" -t wav "|sox -V1 inputfile.wav -t wav - trim 4.8 fade t 0.4 0 0 pad 4.8" outputfile.wav gain 9.542 ''' for i in df.index: start = df['start'][i] end = df['end'][i] duration = end-start #The duration of transition period when a fades in and fades out trans = 0.3 fade_start = start-(trans/2) act_fade_start = start+(trans/2) #fade_start -> act_fade_start -> fade_end -> act_fade_end fade_end = end-(trans/2) act_fade_end = end+(trans/2) fade_duration = duration + trans #Note: Don't forget to add the $ before variable names print("For ",start,", ", end) # !sox -m -t wav "|sox -V1 $wav_path -t wav - fade t 0 $act_fade_start $trans" -t wav "|sox -V1 $wav_path -t wav - trim $fade_start fade t $trans $fade_duration $trans gain -40 pad $fade_start" -t wav "|sox -V1 $wav_path -t wav - trim $fade_end fade t $trans 0 0 pad $fade_end" outputfile.wav gain 9.542 #Replacing the input file with the outputfile # !rm -r "$wav_path" # !cp outputfile.wav "$wav_path" # + id="yi50k-7Vs2dA" colab_type="code" colab={} #Copy the final censored audio file to working directory # !cp "$wav_path" "/content/final_audio.wav" # + [markdown] id="txJdq6eL1MmD" colab_type="text" # # # # # --- # The above section marks an end to the audio censoring. To generated video outputs, get the link to the video file and proceed below. # # + [markdown] id="xec5EAF70nwi" colab_type="text" # Replace the audio of the video with the censored audio by using ffmpeg # + id="emjTmAW60vVm" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 239} outputId="2bdd1c4a-dd7e-4602-922e-44556df11952" ### TODO #Get the video file # !wget -P "/content/" "https://raw.githubusercontent.com/PrashantDandriyal/Speech-Censor-Bot/master/DocsResources/negan_clip_original.mp4" vid_path = "/content/negan_clip_original.mp4" # + id="dBsttbop5c-T" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="07cc7798-442c-4cd1-d9b6-c54e512e14ba" vid_path # + id="ooPj8YVf1yRX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 955} outputId="638f4b37-3906-426f-bee4-936594574601" # !ffmpeg -i "$vid_path" -i "$wav_path" -c:v copy -map 0:v:0 -map 1:a:0 censored_vid.mp4 # + id="StnAQtPE5hHA" colab_type="code" colab={}
Kaldi_OpenDevLibrary.ipynb
# + #@title Copyright 2021 The Earth Engine Community Authors { display-mode: "form" } # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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. # - # # Spectral transformations # # # There are several spectral transformation methods in Earth Engine. These include instance methods on images such as `normalizedDifference()`, `unmix()`, `rgbToHsv()` and `hsvToRgb()`. # # ## Setup # # ### Earth Engine setup import ee ee.Authenticate() ee.Initialize() # ### Folium setup (for interactive map display) # + import folium def add_ee_layer(self, ee_image_object, vis_params, name): map_id_dict = ee.Image(ee_image_object).getMapId(vis_params) folium.raster_layers.TileLayer( tiles=map_id_dict['tile_fetcher'].url_format, attr='Map Data &copy; <a href="https://earthengine.google.com/">Google Earth Engine</a>', name=name, overlay=True, control=True ).add_to(self) folium.Map.add_ee_layer = add_ee_layer # - # ## Pan sharpening # # Pan sharpening improves the resolution of a multiband image through enhancement provided by a corresponding panchromatic image with finer resolution. The `rgbToHsv()` and `hsvToRgb()` methods are useful for pan sharpening. # + # Load a Landsat 8 top-of-atmosphere reflectance image. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') # Convert the RGB bands to the HSV color space. hsv = image.select(['B4', 'B3', 'B2']).rgbToHsv() # Swap in the panchromatic band and convert back to RGB. sharpened = ee.Image.cat( [hsv.select('hue'), hsv.select('saturation'), image.select('B8')]).hsvToRgb() # Define a map centered on San Francisco, California. map_sharpened = folium.Map(location=[37.76664, -122.44829], zoom_start=13) # Add the image layers to the map and display it. map_sharpened.add_ee_layer(image, { 'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 0.25, 'gamma': [1.1, 1.1, 1] }, 'rgb') map_sharpened.add_ee_layer(sharpened, { 'min': 0, 'max': 0.25, 'gamma': [1.3, 1.3, 1.3] }, 'pan-sharpened') display(map_sharpened.add_child(folium.LayerControl())) # - # ## Spectral unmixing # # Spectral unmixing is implemented in Earth Engine as the `image.unmix()` method. (For more flexible methods, see the [Array Transformations page](https://developers.google.com/earth-engine/guides/arrays_transformations)). The following is an example of unmixing Landsat 5 with predetermined urban, vegetation and water endmembers: # + # Load a Landsat 5 image and select the bands we want to unmix. bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'] image = ee.Image('LANDSAT/LT05/C01/T1/LT05_044034_20080214').select(bands) # Define spectral endmembers. urban = [88, 42, 48, 38, 86, 115, 59] veg = [50, 21, 20, 35, 50, 110, 23] water = [51, 20, 14, 9, 7, 116, 4] # Unmix the image. fractions = image.unmix([urban, veg, water]) # Define a map centered on San Francisco Bay. map_fractions = folium.Map(location=[37.5010, -122.1899], zoom_start=10) # Add the image layers to the map and display it. map_fractions.add_ee_layer( image, {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 128}, 'image') map_fractions.add_ee_layer(fractions, None, 'unmixed') display(map_fractions.add_child(folium.LayerControl()))
guides/ipynb/image_transforms.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import os #Visualizations import matplotlib.pyplot as plt import random from datetime import datetime import itertools import swnHeatKernels as swnN from scipy import linalg import helperFunc as hf import swnMetrics as swn import centrality as ce import distributions as dstr # - # ## Functions def getDegreeDistributions(Adict): listKeys = list(Adict[1].keys()) DegDistDict = {} StrengthDistDict = {} for kTuple in listKeys: tempDeg = np.zeros(len(Adict.keys())*100) tempStrength = np.zeros(len(Adict.keys())*100) for rep in Adict: A = Adict[rep][kTuple][1] tempDeg[(rep-1)*100:rep*100] = np.sum(A > 0, axis=1, keepdims=False) tempStrength[(rep-1)*100:rep*100] = np.sum(A, axis=1, keepdims=False) DegDistDict[kTuple] = tempDeg StrengthDistDict[kTuple] = tempStrength return DegDistDict, StrengthDistDict # ## Get degree and strength outliers and save them # + #parameters tested factor=3 rewirings = 4000 pRand = [0, 0.2] taus = {} taus['normal'] = np.array([0,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3,3.2,3.4,3.6,3.8,4,4.2,4.4,4.6,4.8, 5,5.2,5.4,5.6,5.8,6,6.2,6.4,6.6,6.8,7,7.2,7.4,7.6,7.8,8]) taus['lognormal'] = taus['normal'] weightDist = ['normal','lognormal'] ###### Load Adjacency matrices directoryALoad ='data/ArandA/' # + ##THE OUTLIERS dictPrpOutliersDeg = {} dictPrpOutliersStrength = {} #the derivatives of the above dictDerivDeg = {} dictDerivStrength = {} for wD in weightDist: filePathLoad = directoryALoad + 'ArandA_'+wD+'_'+str(rewirings)+'.pckl' Adict = hf.loadVar(filePathLoad) dictPrpOutliersDeg[wD], dictPrpOutliersStrength[wD] = dstr.getPercOutliersAll(taus[wD], pRand, rewirings, Adict,factor) # - filePathSave = 'data/degreesStrengths/outliers.pckl' hf.saveVarSimple((dictPrpOutliersDeg, dictPrpOutliersStrength, pRand,taus,factor), filePathSave) # ## Get A, calculate degree and strength distributions, save them # # + rewirings = 4000 pRand = [0,0.2] weightDist = ['normal','lognormal'] ###### Load Adjacency matrices directoryALoad ='data/ArandA/1000iterations/QrandQtau/' # + p = 0.2 modTau = {}; modTau['normal'] = 3; modTau['lognormal'] = 4.5 centraTau = {}; centraTau['normal'] = 5; centraTau['lognormal'] = 7 strDict= {} degDict= {} degMod = {}; degCentra = {}; strMod = {}; strCentra = {} for wD in weightDist: #for modular filePathLoad = directoryALoad + 'ArandA_tauMod_'+wD+'_p'+str(p)+'_rewir'+str(rewirings)+'.pckl' Adict = hf.loadVar(filePathLoad) degDictMod,strDictMod = getDegreeDistributions(Adict) degMod[wD] = degDictMod[(p,modTau[wD],4000)] strMod[wD] = strDictMod[(p,modTau[wD],4000)] del Adict #for centralized filePathLoad = directoryALoad + 'ArandA_tauCentra_'+wD+'_p'+str(p)+'_rewir'+str(rewirings)+'.pckl' Adict = hf.loadVar(filePathLoad) degDictCentra,strDictCentra = getDegreeDistributions(Adict) degCentra[wD] = degDictCentra[(p,centraTau[wD],4000)] strCentra[wD] = strDictCentra[(p,centraTau[wD],4000)] del Adict filePathSave = 'data/degreesStrengths/histDegStr.pckl' hf.saveVarSimple((degCentra,strCentra,centraTau,degMod,strMod,modTau), filePathSave) # -
2GetSavePercOutliersDegreesStrengths.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Part 2 # *********** # # ![smitty](https://i.imgur.com/jNYC9op.gif "smitty") # # ### warning: suicide is mentioned multiple times throughout this presentation # ************** # # + # !pip install pandas numpy matplotlib # - import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib as mpl # + file = "https://raw.githubusercontent.com/BIOF309/group-project-hacking-pythonistas/master/notebooks/death.csv" df1 = pd.read_csv(file) # - # # Exploring the dataset # # -------------------------- # ### Viewing head, columns, shape, and info print(df1.head()) print(df1.columns) print(df1.shape) print(df1.info()) # ## Indexed by state and dropped an unneeded column # # ---------- death = pd.read_csv(file, index_col='State') death = death.drop("113 Cause Name", axis=1) print(death.head()) # # # Determining the causes of death in by state in 2016 # ------------------ # # ### Index by year and get rid of the redundant column # # ### Then slice the causes from 2016 using loc df_2016 = pd.read_csv(file, index_col='Year') df_2016 = df_2016.drop("113 Cause Name", axis=1) df_2016 = df_2016.iloc[:,0:3] df_2016 = df_2016.loc[2016] print(df_2016.head()) print(df_2016.tail()) # --------------------------- # # ### Sorting by cause to organize the data # # ### And removing "United States" from the data set # # --------------- # # df_2016 = df_2016.sort_values(by=['Cause Name']) df_2016 = df_2016.iloc[52:] df_2016 = df_2016.loc[df_2016['State'] != "United States"] # # Graphing causes of death in each state in 2016 # # ---------------- # # #### Moved legend outside of the graph because it took up too much space df_2016.pivot(index='State', columns='Cause Name', values='Deaths').plot(kind='bar', stacked=True, legend=False, figsize=(20,10)) plt.legend(loc='upper left', prop={'size':14}, bbox_to_anchor=(1,1)) plt.xticks(fontsize="16") # # Looking at suicides # # ## the raw numbers # ----------------- # ### using loc to obtain information for suicides only # + suicide = death.loc[death['Cause Name'] == "Suicide"] suicide = suicide.iloc[:,0:3] suicide = suicide.reset_index() print(suicide.head()) # - # # Comparing suicide data from 1999 and 2016 # ------------------------- # # # Slice and append! # # ![snap](https://media2.giphy.com/media/pKesvivyxwmJO/giphy.gif?cid=3640f6095c0855005a516c516f75201c.gif[snap]) # + #Slicing syear_1999 = suicide.loc[suicide["Year"] == 1999] syear_2016 = suicide.loc[suicide["Year"] == 2016] #Appending data from 1999 and 2016 s9916 = syear_1999.append(syear_2016) print(s9916.head()) print(s9916.tail()) s9916 = s9916.loc[s9916['State'] != "United States"] # - # # Plotting raw suicide data # # ----------------- # # ## Number of actual suicides by state in 1999 (darker bar) and 2016 (ligher bar) # # #### Note: These bars are on the same axis and do not represent part of a whole # + fig, ax = plt.subplots() s9916_p1 = s9916.groupby('Year').plot(x='State', y='Deaths', legend=False, kind="bar", alpha=0.5,ax=ax,figsize=(20,10)) plt.ylabel('Deaths by Suicide') plt.xticks(fontsize="16") # - # # A different representation of the same raw data # # ----------------- # # #### via pivoting! s9916_p2 = s9916.pivot(index='State', columns='Year', values='Deaths').plot(kind='bar', figsize=(20,10)) plt.ylabel('Deaths by Suicide') plt.xticks(fontsize="16") # ----------- # # # Moving from raw data to percentages # # ----------- # # ### Adding total deaths to dataframe # + syear_16_2 = syear_2016.set_index("State") syear_99_2 = syear_1999.set_index("State") #Total deaths total_all_years=death.sort_values(by=['Cause Name']) total_all_years=total_all_years.loc[total_all_years['Cause Name'] == "All causes"] #total deaths in 1999 total_1999 = total_all_years.loc[total_all_years['Year'] == 1999] total_1999 = total_1999.reset_index() total_1999 = total_1999.set_index("State") total_1999 = total_1999.sort_values(by=['State']) total_1999 = total_1999.iloc[:,0:3] #total deaths in 2016 total_2016 = total_all_years.loc[total_all_years['Year'] == 2016] total_2016 = total_2016.reset_index() total_2016 = total_2016.set_index("State") total_2016 = total_2016.sort_values(by=['State']) total_2016 = total_2016.iloc[:,0:3] #Adding total deaths to number of suicides syear_99_2['Total Deaths in 1999'] = total_1999['Deaths'].values syear_16_2['Total Deaths in 2016'] = total_2016['Deaths'].values print(syear_99_2.head()) print(syear_16_2.head()) # - # # ### Dividing suicides by deaths (x100) to get percentage of deaths that were suicides # ----------- # + syear_99_2[['Suicide (Percent)']] = syear_99_2[['Deaths']].div(syear_99_2['Total Deaths in 1999'].values,axis=0) syear_99_2.loc[:,'Suicide (Percent)'] *= 100 syear_16_2[['Suicide (Percent)']] = syear_16_2[['Deaths']].div(syear_16_2['Total Deaths in 2016'].values,axis=0) syear_16_2.loc[:,'Suicide (Percent)'] *= 100 print(syear_99_2.head()) print(syear_16_2.head()) # + #removing US syear_99_3 = syear_99_2.reset_index() syear_16_3 = syear_16_2.reset_index() syear_99_3 = syear_99_3.loc[syear_99_3['State'] != "United States"] syear_16_3 = syear_16_3.loc[syear_16_3['State'] != "United States"] # - # ------------------- # # # Change in Percent Suicides from 1999 to 2016 by State # # ------------------- syear_16_3["Change"] = syear_16_3['Suicide (Percent)'] - syear_99_3['Suicide (Percent)'] print(syear_16_3.head()) s_p_9916 = syear_99_3.append(syear_16_3, sort=False) syear_16_3.plot(kind='bar',x='State',y='Change', title="Change in Suicide Percentages from 1999 to 2016 by State", figsize=(25,15)) plt.grid(color='grey', linestyle='-', linewidth=.3, alpha=0.5) # ### Hawaii's rate is the only that has declined from 1999 to 2016! # ___________ # # # Considering state populations # # ___________ # # ## Importing and tweaking new data # # ----------- # + #importing and renaming columns pop = pd.read_csv("https://raw.githubusercontent.com/BIOF309/group-project-hacking-pythonistas/master/notebooks/uspop.csv", index_col="NAME") pop = pop.loc[:,"POPESTIMATE2010":"POPESTIMATE2016"] pop = pop.iloc[5:,:] pop.columns = ["2010", "2011", "2012", "2013", "2014", "2015", "2016"] pop.index.name = 'State' #getting rid of Puerto Rico pop = pop.drop("Puerto Rico") print(pop.tail()) # - # ---------- # # Examining 2016 Data # ----------- # ### Adding 2016 population data to deaths dataframe # --------- # + #Adding 2016 population to deaths data frame pop_16 = pop[["2016"]] pop_16 = pop_16.reset_index() pop_16 = pop_16.sort_values(by=['State']) syear_16_4 = syear_16_3.sort_values(by=['State']) pop_s_16 = pd.merge(syear_16_4, pop_16, on='State') print(pop_s_16.head(5)) # - # ----------- # ### Finding total deaths per population # _________ #Total deaths in 2016 divided by population of each state in 2016 pop_s_16[['Normalized Death']] = pop_s_16[['Total Deaths in 2016']].div(pop_s_16['2016'].values,axis=0) print(pop_s_16.head()) #Plotting normalized deaths fig, ax = plt.subplots() pop_deaths_16 = pop_s_16.groupby('Year').plot(x='State', y='Normalized Death', legend=False, kind="bar", alpha=0.75,ax=ax,figsize=(20,20)) plt.xlabel('State', fontsize=18) # ### Sorting the data would make it easier to read # --------------- # #### Sorted by normalized death rate # + #sorting data to show the deadliest state! pop_s_16_2 = pop_s_16.sort_values(by=['Normalized Death']) print(pop_s_16_2.head()) # - pop_s_16_2.plot(kind='bar',x='State',y='Normalized Death', title="Death Rate by State in 2016", figsize=(20,20), legend=False) # ### Wow West Virginia, you ok pal??? # ----------------- # # Looking at suicide rate within a population # # ------------------ # + # suicide rate pop_s_16[['Suicide Rate']] = pop_s_16[['Deaths']].div(pop_s_16['2016'].values,axis=0) pop_s_16_3 = pop_s_16.sort_values(by=['Suicide Rate']) print(pop_s_16_3.head()) # - pop_s_16_3.plot(kind='bar',x='State',y='Suicide Rate', title="Suicide Rate by State in 2016", figsize=(20,20), color="red") # ## Things are not looking good for the midwest...... # # ------- # # -------- # ------- # # ![suicideprev](https://tvlvmcjg4f-flywheel.netdna-ssl.com/wp-content/uploads/2016/08/NSPL_Logo.jpg "name")
notebooks/Sara_Death2!.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Python ? # # 1. Introducciรณn a Python para la ciencia de datos: # # # Python es un lenguaje de programaciรณn de propรณsito general que se estรก volviendo mรกs y mรกs popular para hacer ciencia de datos. # # # ## 1.1 Python Scientific Stack # # - NumPy # - Scipy # - Jupyter (Ipython) # - matplotlib # - pandas # # # 2. Preparaciรณn de datos (Extraer, importar y limpiar): # # - ยฟDรณnde estรกn los datos que necesitas? # - ยฟCรณmo prepararlos para usarlos en tu caso?. # - Fuentes de Datos, Scrapping, Limpieza de Datos y Almacenamiento # # # 3. Anรกlisis Exploratorio de Datos: # # Para conocer mejor la informaciรณn con la que estรกs tratando, es mejor explorarla. # Anรกlisis bรกsico de datos, ayudado con herramientas grรกficas. # Conceptos bรกsicos de Pandas # # # -------- # # Preparacioฬn de datos / Fuentes de datos # # # # ## ยฟDรณnde consigo los datos? # # ### Datasets publicos: # - http://archive.ics.uci.edu/ml/ # - http://www.kaggle.com # - https://www.quora.com/Where-can-I-find-large-datasets-open-to-the-public # # ### Datos en Mรฉxico # - http://datos.gob.mx # - http://data.mx.io # - http://www.inegi.org.mx/ # - http://inegifacil.com/ # - http://datos.imss.gob.mx/ # - https://datos.jalisco.gob.mx/ # - https://datosabiertos.unam.mx/ # # # # # ## Numpy (Numerical Python) # # http://www.numpy.org/ # # Las listas en python son muy poderosas y versรกtiles pero fallan en un aspecto importante para la ciencia de datos. # # NumPy agrega mayor soporte para arreglos y matrices, constituyendo una biblioteca de funciones matemรกticas de alto nivel para operar con esos vectores o matrices. # # # ### Arreglos # # $$ y = [0, 1, 2, 3, 4] $$ # + import numpy as np x = [0, 1, 2, 3, 4] y = np.array(x) y # - help(np.array) type(y) y * y np.ndim(y) y.size y.dtype np.identity(n = 5) np.ones(shape= [2,4]) np.zeros(shape= [2,4]) # + y = [0, 1, 2, 3, 4] y * y # - np.ndim(y) # ### Matrices (Arreglos de dos dimensiones) # # $$x = \begin{bmatrix} # 1 & 2 & 3 \\[0.3em] # 4 & 5 & 6 \\[0.3em] # 7 & 8 & 9 # \end{bmatrix}$$ x = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(x) x np.ndim(x) # ### Selecciรณn escalar x = np.array([[1.0,2,3],[4,5,6]]) x[1,2] # ### Array slicing # # - a[comienzo:fin] # elementos desde el รญndice del comienzo hasta el รญndice fin-1 # - a[comienzo:] # del nรบmero en comienzo hasta el fin # - a[:fin] # desde el principio hasta fin-1 # - a[:] # todo el arreglo # - a[comienzo:fin:paso] # elementos desde el รญndice del comienzo hasta el รญndice fin-1, por paso # ### Operaciones con arreglos y matrices # # # #### Reshaping x x.flatten() x.dtype x.T # # #### Operaciones # # La creaciรณn y manipulaciรณn de matrices es una buena herramienta, pero el verdadero poder de NumPy es la capacidad de realizar operaciones matemรกticas con muchos valores rรกpida y fรกcilmente. # x + 100 x * 2 x ** 2 x + x x * x np.mean(x) x.mean() np.mean(x, axis = 0) #Promedio por columna x.std() np.sum(x, axis=1) x.sum(axis=0) # # # Linear รกlgebra (numpy.linalg) # # - Productos entre vectores y matrices # - Descomposiciones # - Cรกlculo de eigenvalues # # Los arreglos de numpy funcionan muy bien para arreglos de n-dimensiones con valores numรฉricos, pero seamos realistas quedan muy atrรกs al momento de lidiar con datos heterogรฉneos. # # Para almacenar datos de una fuente externa, como un libro de Excel o base de datos, necesitamos una estructura de datos que pueda contener diferentes tipos de datos. # # Tambiรฉn es deseable poder hacer referencia a filas y columnas de los datos usando etiquetas en lugar de รญndices numerados. # -------- # ## Meet Pandas # ## Pandas y DataFrames http://pandas.pydata.org/ # # # <a href="http://pandas.pydata.org/"><img src="img/pandas-web.png" style="float:center;height:400px"/></a> # pandas: # # - Librerรญa Open Source para anรกlisis de datos # - Python # - Equivalente a data.frame y Dplyr de R-lang # # pandas is an open source Python library for data analysis. Python has always been great for prepping and munging data, but it's never been great for analysis - you'd usually end up using R or loading it into a database and using SQL (or worse, Excel). pandas makes Python great for analysis. # - pandas es un mรณdulo de alto rendimiento que ofrece un amplio conjunto de estructuras para trabajar con datos. # - pandas ayuda al manejo de datos estructurados que contienen muchas variables # - permite el manejo de "missing values" # - pandas tambiรฉn proporciona mรฉtodos robustos para la importaciรณn y exportaciรณn de una amplia gama de formatos. # ## `import pandas as pd` import pandas as pd # Series s = pd.Series([7, 'Heisenberg', 3.14, -1789710578, 'Happy Eating!']) s s = pd.Series([0.1, 1.2, 2.3, 3.4, 4.5]) s s = pd.Series([0.1, 1.2, 2.3, 3.4, 4.5], index = ['a','b','c','d','e']) s pd.DataFrame({ 'municipio': ['mty', 'spgg', 'sta_c', 'garcia'], 'temp_celcius_jueves': [35, 36, 37, 38], 'temp_celcius_viernes': [36, 37, 39, 38] }) # DataFrame data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012], 'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'], 'wins': [11, 8, 10, 15, 11, 6, 10, 4], 'losses': [5, 8, 6, 1, 5, 10, 6, 12]} football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses']) football # + mi_df = pd.DataFrame({ 'municipio': ['mty', 'spgg', 'sta_c', 'garcia'], 'temp_celcius_jueves': [35, 36, 37, 38], 'temp_celcius_viernes': [36, 37, 39, 38] }) mi_df[(mi_df['temp_celcius_jueves'] < 37) or (mi_df['temp_celcius_viernes'] < 40)] # - # El รญndice es parte de la "magia" de las estructuras de datos en pandas s[['a','c']] s[s>2] data.tail() data = pd.read_csv('train.csv') data.head() data.tail() data.pop() age = data['Age'] sum(age.isnull()) np.mean(age) age = data['Age'].fillna(29.69) sum(age.isnull()) pclass = data['Pclass'] pclass.unique() data.Pclass.head() data[['Age', 'Pclass']].head() # Podemos borrar columnas usando los comando del, pop(), drop() # - del modifica nuestro dataframe borrando la Serie seleccionada. # - pop() borra la Serie pero la regresa como un output # - drop() regresa un dataframe sin la Serie, pero no modifica el dataframe original del data['Ticket'] data.head() # ### Datos # # Los datos son caracterรญsticas cualitativas o cuantitativas pertenecientes a un objeto, o un conjunto de objetos # # # ### Datos en bruto # # "Raw data is a term for data collected on source which has not been subjected to processing or any other manipulation." # # - Los datos en bruto llegan directamente de la fuente y no tienen la estructura necesaria para realizar anรกlisis con ellos eficientemente. # # - Requieren pre-procesamiento para ser utilizados. # - Por lo general suelen verse de la siguiente manera: # # <img src="http://www.objectplanet.com/opinio/userguide/images/raw_data_export_example.jpg" /> # # Video, audio, pรกginas web, tambiรฉn son fuentes de datos # # # ### Datos ordenados (Tidy data) # # #### Notebook Tidy_data # # <img src="http://garrettgman.github.io/images/tidy-1.png" /> # # - Las variables deben de ser entendibles para el humano # # #### Codebook! # # Documento para poder entender la informaciรณn de la tabla. # # - Descripciรณn de las caracterรญsticas con sus unidades # - Instrucciones sobre las transformaciones que aplicamos a nuestros datos en bruto para trabajarlos # # ESTO ES MUY IMPORTANTE # # Existen historias de terror: # # http://www.cc.com/video-clips/dcyvro/the-colbert-report-austerity-s-spreadsheet-error # # <img src="http://image.slidesharecdn.com/documentation-metadata-denton-lake-150423121613-conversion-gate02/95/documentation-and-metdata-va-dm-bootcamp-27-638.jpg?cb=1429791459" /> # # ### ยฟDรณnde consigo los datos? # # ## Datasets publicos: # - http://archive.ics.uci.edu/ml/ # - http://www.kaggle.com # - https://www.quora.com/Where-can-I-find-large-datasets-open-to-the-public # # ## Datos en Mรฉxico # - http://datos.gob.mx # - http://data.mx.io # - http://www.inegi.org.mx/ # - http://inegifacil.com/ # - http://datos.imss.gob.mx/ # - https://datos.jalisco.gob.mx/ # - https://datosabiertos.unam.mx/ # ## Dataset para hoy - train.csv # # ### Predecir la supervivencia en el Titanic # # https://www.kaggle.com/c/titanic/data # # El hundimiento del Titanic es uno de los naufragios mรกs infames de la historia. El 15 de abril de 1912, durante su viaje inaugural, el Titanic se hundiรณ despuรฉs de chocar con un iceberg, matando de 1,502 a 2,224 pasajeros. # # Una de las razones por las cuales se perdieron tantas vidas fue que no habรญa suficientes botes salvavidas. Aunque hubo algรบn elemento de suerte involucrada en sobrevivir al hundimiento, algunos grupos de personas tenรญan mรกs probabilidades de sobrevivir que otros, como las mujeres, los niรฑos y personas de la clase alta. # # Para hoy usaremos el dataset `train.csv` y completarรกs el anรกlisis de quรฉ tipo de personas eran propensos a sobrevivir . En un futuro, te pedimos aplicar las herramientas de aprendizaje automรกtico para predecir que los pasajeros sobrevivieron a la tragedia. # # ### Matplotlib # # Las visualizaciones son una de las herramientas mรกs poderosas a su disposiciรณn para explorar los datos y comunicar tus ideas. La biblioteca pandas incluye capacidades bรกsicas para graficar con el paquete matplotlib. # import matplotlib # %matplotlib inline # #### Histogramas data.hist(bins = 20, column="Age", figsize=(8,8), color="blue") # #### Boxplot data.boxplot(column="Age", return_type='axes') data.boxplot(column="Age", by="Pclass", figsize= (8,8)) # + ### Scatterplots data.plot(kind="scatter", x="Age", y="Fare", figsize=(10,10)) # - # #### Barras tabla = pd.crosstab(index=data["Pclass"], columns=data["Survived"]) tabla tabla.plot(kind="bar", figsize=(8,8)) # # #### EJERCICIO # # Usando el dataframe anterior, crear un grรกfico de barra donde se vea la cantidad de sobrevivientes en proporciรณn al total de pasajeros por clase. # # # -------- # # # #### RESPUESTA data.boxplot(column='Age', return_type='axes') # + tabla = pd.crosstab(index=data["Pclass"], columns=data["Survived"], margins=True) #Agregando margins=True nos da los totales tabla # - #Obtenemos la proporciรณn dividiento entre el total por filas tabla = tabla.div(tabla["All"], axis=0) tabla tabla = tabla.drop(tabla.index[3])[1] tabla.plot(kind="bar", figsize=(8,8)) # ## Web Scrapping con PANDAS # + # Asignar el resultado del metodo read_html a densidad_paises # Parametro header=0 para establecer el header de la tabla # Consultar: http://pandas.pydata.org/pandas-docs/stable/gotchas.html#html-gotchas densidad_paises = pd.read_html('https://simple.wikipedia.org/wiki/List_of_countries_by_population_density', header=0) # Observar los primeros 10 registros densidad_paises[0][:10] # - # Que tipo de objeto tenemos? type(densidad_paises) # + # Como lo convertimos en un dataframe? densidad_paises_dataframe = pd.DataFrame(densidad_paises[0]) # Que tipo de objeto tenemos? type(densidad_paises_dataframe) densidad_paises_dataframe.head() densidad_paises_dataframe.keys() densidad_paises_clean = densidad_paises_dataframe.copy() # http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion densidad_paises_clean.pop('Unnamed: 1') # Verificar densidad_paises_clean densidad_paises_clean.pop('Area (mi2)') densidad_paises_clean.pop('Density (/mi2)') # for cycle column_list = [] for element in column_list: dataframe.pop(element) densidad_paises_clean.head() del densidad_paises_clean['Notes'] densidad_paises_clean.head() densidad_paises_clean.rename(columns={'Population': 'Pop'}, inplace=True) densidad_paises_clean.rename(columns={'Area (km2)': 'Area'}, inplace=True) densidad_paises_clean.rename(columns={'Density (/km2)': 'Density'}, inplace=True) # - # ### Exportar ? ๐Ÿ˜ฑ # # # ### APIs ? # Siguiente NB: Estadistica_24_Jun
Python_para_ciencia_de_datos/2da_clase/Sab_24_Jun.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Assessing and Building Intuition # Once you have your data loaded into dataframes, Pandas makes a quick investigation of the data really easy. Let's explore some helpful methods for assessing and building intuition about a dataset. We can use the cancer data from before to help us. # + import pandas as pd df = pd.read_csv('cancer_data.csv') df.head() # - # this returns a tuple of the dimensions of the dataframe df.shape # this returns the datatypes of the columns df.dtypes # although the datatype for diagnosis appears to be object, further # investigation shows it's a string type(df['diagnosis'][0]) # Pandas actually stores [pointers](https://en.wikipedia.org/wiki/Pointer_(computer_programming) to strings in dataframes and series, which is why `object` instead of `str` appears as the datatype. Understanding this is not essential for data analysis - just know that strings will appear as objects in Pandas. # this displays a concise summary of the dataframe, # including the number of non-null values in each column df.info() # this returns the number of unique values in each column df.nunique() # this returns useful descriptive statistics for each column of data df.describe() # this returns the first few lines in our dataframe # by default, it returns the first five df.head() # although, you can specify however many rows you'd like returned df.head(20) # same thing applies to `.tail()` which returns the last few rows df.tail(2) # ## Indexing and Selecting Data in Pandas # Let's separate this dataframe into three new dataframes - one for each metric (mean, standard error, and maximum). To get the data for each dataframe, we need to select the `id` and `diagnosis` columns, as well as the ten columns for that metric. # View the index number and label for each column for i, v in enumerate(df.columns): print(i, v) # We can select data using `loc` and `iloc`, which you can read more about [here](https://pandas.pydata.org/pandas-docs/stable/indexing.html). `loc` uses labels of rows or columns to select data, while `iloc` uses the index numbers. We'll use these to index the dataframe below. # select all the columns from 'id' to the last mean column df_means = df.loc[:,'id':'fractal_dimension_mean'] df_means.head() # repeat the step above using index numbers df_means = df.iloc[:,:11] df_means.head() # Let's save the dataframe of means for later. df_means.to_csv('cancer_data_means.csv', index=False) # ### Selecting Multiple Ranges in Pandas # Selecting the columns for the mean dataframe was pretty straightforward - the columns we needed to select were all together (`id`, `diagnosis`, and the mean columns). Now we run into a little issue when we try to do the same for the standard errors or maximum values. `id` and `diagnosis` are separated from the rest of the columns we need! We can't specify all of these in one range. # # First, try creating the standard error dataframe on your own to see why doing this with just `loc` and `iloc` is an issue. Then, use this [stackoverflow link](https://stackoverflow.com/questions/41256648/select-multiple-ranges-of-columns-in-pandas-dataframe) to learn how to select multiple ranges in Pandas and try it below. By the way, to figure this out myself, I just found this link by googling "how to select multiple ranges df.iloc" # # *Hint: You may have to import a new package!* # + # import import numpy as np # create the standard errors dataframe df_SE = df.iloc[:, np.r_[:2, 12:22]] # view the first few rows to confirm this was successful df_SE.head() # -
1. Data Analysis/Course Work/1. Intro to DA/assessing-solutions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [Root] # language: python # name: Python [Root] # --- # # Data analysis - <span style="color: blue">Optional extension work</span> import numpy as np # There is lots more that we can do with python to analyse and present data. The optional sections of the notebook below will introduce you to three more important aspects of data analysis: # * Reading more complex files, # * Hypothesis testing, # * Creating more complex plots. # ### Opening a file # The file we are going to work with first is `Data/test_data.txt`. Take a look at the contents by opening it up in a text editor such as Notepad - it just contains a small amount of toy data. The first thing we need to do is tell python where the file is and associate it with a file object: myFile = open('Data/test_data.txt', 'r') # The function <code>open()</code> returns a file object, which we here associate with the variable <code>myFile</code>. You can think of this variable as a label that we can use to access the file from now on. The <code>'r'</code> specifies that we are opening the file for the purposes of reading its contents rather than writing to it. We will look at writing files later. Notice that we did not need to import any new modules in order to open the file for reading: the function `open()` is part of core python. # ### Reading the data into an array # Now we need to read in the data from the file. We can read a single line from the file: myFile.readline() # `readline()` is a *method* of a *file* object. our variable `myFile` contains a file object, so when we apply the `readline()` method to it it returns a single line of the file. The structure here is: # # <object>.<method_to_do_something_to_object> # # Notice the addition of a newline character '\n' at the end of the line. Each time we read a line, Python moves through the file, so if we repeat the command: myFile.readline() # then we get the next line. To move back to the start of the file we can use: myFile.seek(0) # Now we can try reading the whole file at once: myFile.readlines() myFile.seek(0) myData = myFile.readlines() # Now the data is contained in the `myData` variable. We can then, for example, print out the second line (remember that Python indexes its arrays, lists, etc. from zero!) # Notice that the `readlines()` method of a file object returns a python *list* in which each line of the file is a member of the list (we could assign this list to a variable, if we wanted): print(myData[1]) # This element of the `myData` list is a *string*. We can thus split this line of text quite easily using the `split()` method of the string object: myData[1].split() # This returns another list object in which each member is one of the space-separated values in the line from our file. Note that <code>split()</code> can be given several optional parameters, one of which will split the line based on any delimiting character(s), such as a comma, that you specify. The default delimiter is one or more spaces. Use your favourite search engine to find out a bit more about the `split()` method and the various options that you can use. # Now let's do something a bit more useful and flexible: we'll read the contents of the file into a numpy array. We know the size of the array and the type of data it contains (floating point numbers) and we don't want to include the first line (the header) or first column (sample labels) in the array, so we can begin by defining an empty array: import numpy as np myDataArray = np.zeros([3,2], dtype=float) # Create a 3x2 array full of zeros (of floating point type) # Now, here I have explicitly told Python that my array will contain floating point numbers by specifying `dtype=float`. I don't need to to this, but it can save trouble and make the code more readable. # # Next I need to iterate through the file and read each line into the array: myFile.seek(0) # Go back to the beginning of the file! lineIndex = 0 # Keep track of which line we are reading myFile.readline() # Read the first (header) line and do nothing with it for line in myFile: theseData = line.split() # split the line and store the result in a list myDataArray[lineIndex,0] = float(theseData[1]) myDataArray[lineIndex,1] = float(theseData[2]) lineIndex = lineIndex + 1 # Increment the line counter so that we write to the next row of the array print(myDataArray) # Notice how flexible the `for` loop is in Python: it "knows" about the concept of "lines" in "files". # # Now let's close the file, to avoid any problems with file conflicts: myFile.close() # Always close files as soon as you are done with them. # ## Hypothesis testing # Let's load in the data for the pore sizes in a metal foam from the file `pores_unstrained.txt` that we worked with previously. import numpy as np sampleA = np.loadtxt('Data/pores_unstrained.txt', delimiter=',', usecols=(0,)) sampleB = np.loadtxt('Data/pores_unstrained.txt', delimiter=',', usecols=(1,)) # The two samples of pore sizes A and B have quite similar means but moderately large standard deviations, so it would be reasonable to conclude that these two samples come from similar populations (which is to say in our context that they come from equivalent materials). We can formally test this conclusion by using a *t-test* to test if we can reject our *null hypothesis* that "the two samples are from populations that have equivalent average pore sizes". We do this as follows: from scipy import stats testResults = stats.ttest_ind(sampleA,sampleB) print('The p-value is ' + str(testResults[1])) # This p-value is less than 5%, which suggests that we can reject our null hypothesis at the 95% level and conclude that the two materials that we have sampled are likely to have different pore size distributions. # ### <span style="color: red"> Optional task:</span> Carry out a hypothesis test on *paired* data # This is a particularly challenging task, so leave it until last and come back to it if you are interested. # # The file `pores_Strained.txt` in the `Data` folder contains measurements of the sizes of ten pores in a single sample of metal foam, before and after a strain is applied. # # <figure> # <img src="Figures/pores_strained.png" width='200'> # <figcaption></figcaption> # </figure> # # Note that in each line of the file the two columns contain the size of *the same pore* before and after straining. Hence this is what is known as *paired data*. Your task is to do the following: # * Calculate the basic statistics for the sample of pores before and after straining. # * Use an appropriate statistical test to determine if the straining of the sample has resulted in an increase in the mean pore size at the 95% confidence level. # ### <span style="color: blue"> Solution:</span> # ## A more complex plot - Texture analysis # In this section we will introduce you to a different kind of plot and use it to analyse some real experimental data. We'll also take a look at some of the ways that you can format plots in python and how to write your plots to a file (perhaps for use in a project report or dissertation). # ### A (very) brief introduction to pole figures # By now, you should have been introduced to the idea of material *microstructure* and know that most of the metals that we use are *polycrystalline*. This means that they are made up of multiple *grains* of crystal in which the arrangement of atoms has different orientations. # # <figure> # <img src="Figures/Polycrystal.jpg" width='200'> # <figcaption></figcaption> # </figure> # # The way that the orientations of these grains are distributed is known as the *texture* of the material. A *random texture* means that the distribution of orientation of the crystal lattice in the grains is random. If all of the grains have their crystal lattices oriented in (or close to) a subset of directions, then the material is said to have a *strong texture*. # # Here we will look at some data for the orientation of the grains in a sample of a zirconium alloy used in the fuel rods for fission nuclear reactors. This alloy is processed to give it a strong texture. The figure below shows an EBSD (electron back-scatter diffraction) map of the grain structure of a sample of Zr alloy: # # <figure> # <img src="Figures/ebsd_map.png" width='300'> # <figcaption></figcaption> # </figure> # # Here we can see the grains of the metal, coloured according to the orientation of the $[0001]$ crystallographic direction relative to the plane of the image (note that Zr has the hcp structure at normal temperature and pressure). One way that this sort of information about texture can be represented *quantitatively* is with a *pole figure* like the one below: # # <figure> # <img src="Figures/pole_figure.png" width='600'> # <figcaption></figcaption> # </figure> # # In this figure we are showing contour plots of the relative likelihood of finding a given crystallographic plane ($(10\overline{1}0)$, $(0001)$ and $(10\overline{1}2)$ as indicated in the labels of the subplots) orientated in a certain way relative to the sample ('RD' and 'ND' are the rolling and normal directions in the sample - actually the 'ND' is mislabelled here: it should be 'TD' for transverse direction). You'll get used to reading these types of figures over the next few years, but for now focus on the centre plot, for the $(0001)$ pole. # # # ### Reading in the data # We thought it might be instructive to work with some raw data taken straight from one of the lab-based xray instruments here at Manchester. This means the file structure is complicated and includes headers containing lots of information. The structure is shown schematically below: # # <figure> # <img src="Figures/FileFormat.jpg" width='500'> # <figcaption></figcaption> # </figure> # # We've provided the python code necessary to read in the file and load it into several numpy arrays. Have a careful look through the code and try to understand what it is doing (we've added some comments to help you). # + import numpy as np myFile = open('Data/Z4RX_3PEAKS.uxd', 'r') fileHeadSize = 31 # The number of lines in the main file header blockHeadSize = 30 # The number of lines in the header for each block section nPoles = 3 # The file contains data for three poles corresponding to the three subfigures above nTheta = 18 # There are 18 blocks. One for each different polar angle (0 to 85 degrees at 5 degree intervals) nPhi = 72 # There are 72 entries for different azimuthal angles at each polar angle (0 to 355 deg at 5 deg intervals) poleData = np.zeros((nPoles,nTheta,nPhi+1), dtype=float) thetaAngle = np.zeros(nTheta, dtype=float) phiAngle = np.zeros(nPhi+1, dtype=float) for i in range (fileHeadSize): myFile.readline() for i in range(nPoles): for j in range(nTheta): for l in range(blockHeadSize): thisLine = myFile.readline() if (i==0 and l==9): thetaAngle[j] = float(thisLine.split()[2])*np.pi/180.0 for k in range(nPhi): thisData = myFile.readline().split() if (i==0 and j==0): phiAngle[k] = float(thisData[0])*np.pi/180.0 poleData[i,j,k] = float(thisData[1]) for j in range(nTheta): poleData[i,j,nPhi] = poleData[i,j,0] phiAngle[nPhi] = 360.0*np.pi/180.0 myFile.close() # - # ### A basic plot # Let's begin by simply plotting out the data from the file in a polar plot - we won't bother with any formatting at this stage: import matplotlib.pyplot as plt # %matplotlib inline ax = plt.subplot(111, polar=True) cax = ax.contourf(phiAngle,np.sin(thetaAngle),poleData[1,:,:]/1625.0, cmap=plt.cm.get_cmap('Blues'), vmax=5.0) plt.show() # ### Formatting a figure # Now let's try something a bit more fancy - we'll format up the plot in a way suitable for publication. Have a look at the code below and use the Python documentation and internet search results to understand what each line is doing; # + import matplotlib.pyplot as plt import pylab fig = plt.figure(figsize=(15,7)) ax1 = plt.subplot(131, polar=True) cax1 = ax1.contourf(phiAngle,np.sin(thetaAngle),poleData[0,:,:]/500.0, cmap=plt.cm.get_cmap('Blues'), vmax=5.0) ax1.set_xticklabels(['RD', '', 'TD', '', '', '', '', '']) ax1.set_yticklabels([]) ax1.set_title("$(10\overline{1}0)$", va='bottom') ax2 = plt.subplot(132, polar=True) cax2 = ax2.contourf(phiAngle,np.sin(thetaAngle),poleData[1,:,:]/1625.0, cmap=plt.cm.get_cmap('Blues'), vmax=5.0) ax2.set_xticklabels(['RD', '', 'TD', '', '', '', '', '']) ax2.set_yticklabels([]) ax2.set_title("$(0001)$", va='bottom') ax3 = plt.subplot(133, polar=True) cax3 = ax3.contourf(phiAngle,np.sin(thetaAngle),poleData[2,:,:]/450.0, cmap=plt.cm.get_cmap('Blues'), vmax=5.0) ax3.set_xticklabels(['RD', '', 'TD', '', '', '', '', '']) ax3.set_yticklabels([]) ax3.set_title("$(10\overline{1}2)$", va='bottom') cbar_ax = fig.add_axes([0.95, 0.3, 0.02, 0.4]) fig.colorbar(cax, cax=cbar_ax) ax.grid(True) pylab.savefig('Output/PoleFigure.pdf', bbox_inches='tight') plt.show() # - # Note that the last two lines use functionality from the pylab module (which we need to import, of course) to save the figure in a file. Here we have chosen pdf format as this is ideal for inclusion in written work. You can also output e.g. png or jpg formats for use on webpages. Find the file in the Outputs directory and open it with a pdf viewer to check that everything has worked as expected. # ### <span style="color: red"> Optional task:</span> An alternative plot # Produce a plot of just the right-most pole figure ($(10\bar{1}2)$ pole), with a colour key and using a colour map of the colours of the visible spectrum. Save this figure as a png graphic. # ### <span style="color: blue"> Solution:</span>
6-Extension_material/Data_Analysis_Extension_Material/Data_analysis_extension.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="BkGsYcWbTZvv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 306} outputId="9b23eb64-2161-48a5-f215-59f8ae71dae7" executionInfo={"status": "ok", "timestamp": 1583795946712, "user_tz": -60, "elapsed": 9003, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} # !pip install --upgrade tables # !pip install eli5 # !pip install xgboost # + id="O54gfGjMT4gR" colab_type="code" colab={} import pandas as pd import numpy as np from sklearn.dummy import DummyRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor import xgboost as xgb from sklearn.metrics import mean_absolute_error as mae from sklearn.model_selection import cross_val_score, KFold import eli5 from eli5.sklearn import PermutationImportance # + id="Wj31n2HpUk0c" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0a730396-f0d2-4458-adc9-2e19608ba652" executionInfo={"status": "ok", "timestamp": 1583795961297, "user_tz": -60, "elapsed": 591, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} # cd "/content/drive/My Drive/Colab Notebooks/matrix/matrix_two/dw_matrix_car" # + id="MmOgg3tnUnu-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="04e6bf32-d6ca-464a-b00a-c091132d681f" executionInfo={"status": "ok", "timestamp": 1583795967180, "user_tz": -60, "elapsed": 2272, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} df = pd.read_hdf('data/car.h5') df.shape # + id="n7hQQ-M4UvJC" colab_type="code" colab={} # + [markdown] id="G2ls0b5rUzMG" colab_type="text" # Feature Engineering # + id="FrWB3apvU3Yt" colab_type="code" colab={} SUFFIX_CAT = '__cat' for feat in df.columns: if isinstance(df[feat][0],list): continue factorized_values = df[feat].factorize()[0] if SUFFIX_CAT in feat: df[feat] = factorized_values else: df[feat + SUFFIX_CAT] = factorized_values # + id="faZr_U3OVBNQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="9bbcc2d2-404f-4575-f9b6-8e890d1eaabc" executionInfo={"status": "ok", "timestamp": 1583795972847, "user_tz": -60, "elapsed": 553, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} cat_feats = [x for x in df.columns if SUFFIX_CAT in x] cat_feats = [x for x in cat_feats if 'price' not in x] len(cat_feats) # + id="OS0OaecGVJnr" colab_type="code" colab={} def run_model(model, feats): X = df[feats].values y = df['price_value'].values scores = cross_val_score(model, X, y, cv =3, scoring='neg_mean_absolute_error') return np.mean(scores), np.std(scores) # + [markdown] id="Ga_3VA9AWQOp" colab_type="text" # Decision Tree # + id="50UhCFlnVZJO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ec090bc4-768e-43d3-9035-d999b661141d" executionInfo={"status": "ok", "timestamp": 1583796050735, "user_tz": -60, "elapsed": 4635, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} run_model(DecisionTreeRegressor(max_depth=5), cat_feats) # + [markdown] id="ipzLjx7OWZkt" colab_type="text" # Random Forest # + id="LhIv-TkPWFM8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="500b4cea-9792-4eab-d685-0427a27cf084" executionInfo={"status": "ok", "timestamp": 1583796282811, "user_tz": -60, "elapsed": 117620, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} model = RandomForestRegressor(max_depth=5, n_estimators=50,random_state=0) run_model(model, cat_feats) # + [markdown] id="3Snrt0V_XAUf" colab_type="text" # XGBoost # + id="oLGUELUXmw9S" colab_type="code" colab={} xgb_params = { 'max_depth' : 5, 'n_estimators' : 50, 'leraning rate' : 0.1, 'seed' : 0 } # + id="UKsWOPQzW6P3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="51af9512-bf9f-4923-8e85-d36a9e3d3447" executionInfo={"status": "ok", "timestamp": 1583792368327, "user_tz": -60, "elapsed": 60111, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} model = xgb.XGBRegressor(**xgb_params) run_model(model, cat_feats) # + id="5Yd9rkPPYhwR" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 408} outputId="6aa14570-09de-4615-c345-38146ea967da" executionInfo={"status": "ok", "timestamp": 1583792875429, "user_tz": -60, "elapsed": 367189, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} m = xgb.XGBRegressor(max_depth=5, n_estimators=50, leraning_rate = 0.1, seed = 0 ) m.fit(X,y) imp = PermutationImportance(m, random_state=0).fit(X,y) eli5.show_weights(imp,feature_names = cat_feats) # + id="jWmfWqUNY8zE" colab_type="code" colab={} feats= ['param_napฤ™d__cat', 'param_rok-produkcji__cat', 'param_stan__cat', 'param_skrzynia-biegรณw__cat', 'param_faktura-vat__cat', 'param_moc__cat', 'param_marka-pojazdu__cat', 'feature_kamera-cofania__cat', 'param_typ__cat', 'param_pojemnoล›ฤ‡-skokowa__cat', 'seller_name__cat','feature_wspomaganie-kierownicy__cat', 'param_model-pojazdu__cat', 'param_wersja__cat', 'param_kod-silnika__cat','feature_system-start-stop__cat', 'feature_asystent-pasa-ruchu__cat', 'feature_czujniki-parkowania-przednie__cat', 'feature_ล‚opatki-zmiany-biegรณw__cat', 'feature_regulowane-zawieszenie__cat'] # + id="Od7UPa3ZcuTv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 357} outputId="49932ea6-a2ef-4f92-e6fe-21124f8b8adf" executionInfo={"status": "ok", "timestamp": 1583796425681, "user_tz": -60, "elapsed": 370, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} feats # + id="e5xEeTSYc51k" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="0bf1aa2c-9784-4dbe-8b12-c147a5f3d554" executionInfo={"status": "ok", "timestamp": 1583796446642, "user_tz": -60, "elapsed": 13737, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} xgb_params = { 'max_depth' : 5, 'n_estimators' : 50, 'leraning rate' : 0.1, 'seed' : 0 } model = xgb.XGBRegressor(**xgb_params) run_model(model, feats) # + id="STK0S4_sgPTa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 187} outputId="cde09a74-dc46-46e4-ba97-b8c8a8d15601" executionInfo={"status": "ok", "timestamp": 1583796453533, "user_tz": -60, "elapsed": 575, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} df['param_rok-produkcji'].unique() # + id="B_e9OAH5f_oY" colab_type="code" colab={} df['param_rok-produkcji'] = df['param_rok-produkcji'].map(lambda x: -1 if str(x) == 'None' else int(x)) # + id="r3XvPVShgig0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 136} outputId="e70db6b3-d0e8-4f51-970e-79c62ca4f7cb" executionInfo={"status": "ok", "timestamp": 1583796457268, "user_tz": -60, "elapsed": 649, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} df['param_rok-produkcji'].unique() # + id="G_l83VetdHRj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="0ea3254b-eae2-4eb8-e3fd-381e5adee1f1" executionInfo={"status": "ok", "timestamp": 1583796472537, "user_tz": -60, "elapsed": 14057, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} feats = ['param_napฤ™d__cat', 'param_rok-produkcji', 'param_stan__cat', 'param_skrzynia-biegรณw__cat', 'param_faktura-vat__cat', 'param_moc__cat', 'param_marka-pojazdu__cat', 'feature_kamera-cofania__cat', 'param_typ__cat', 'param_pojemnoล›ฤ‡-skokowa__cat', 'seller_name__cat','feature_wspomaganie-kierownicy__cat', 'param_model-pojazdu__cat', 'param_wersja__cat', 'param_kod-silnika__cat','feature_system-start-stop__cat', 'feature_asystent-pasa-ruchu__cat', 'feature_czujniki-parkowania-przednie__cat', 'feature_ล‚opatki-zmiany-biegรณw__cat', 'feature_regulowane-zawieszenie__cat'] run_model(xgb.XGBRegressor(**xgb_params), feats) # + id="obKbs2c7eDvc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="316955a3-7cd1-4e6b-fecc-9db8a264a599" executionInfo={"status": "ok", "timestamp": 1583796491018, "user_tz": -60, "elapsed": 13998, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} df['param_moc'] = df['param_moc'].map(lambda x: -1 if str(x) == 'None' else int(x.split(' ')[0] )) feats = ['param_napฤ™d__cat', 'param_rok-produkcji', 'param_stan__cat', 'param_skrzynia-biegรณw__cat', 'param_faktura-vat__cat', 'param_moc', 'param_marka-pojazdu__cat', 'feature_kamera-cofania__cat', 'param_typ__cat', 'param_pojemnoล›ฤ‡-skokowa__cat', 'seller_name__cat','feature_wspomaganie-kierownicy__cat', 'param_model-pojazdu__cat', 'param_wersja__cat', 'param_kod-silnika__cat','feature_system-start-stop__cat', 'feature_asystent-pasa-ruchu__cat', 'feature_czujniki-parkowania-przednie__cat', 'feature_ล‚opatki-zmiany-biegรณw__cat', 'feature_regulowane-zawieszenie__cat'] run_model(xgb.XGBRegressor(**xgb_params), feats) # + id="_KZ46C2ueNdS" colab_type="code" colab={} df['param_pojemnoล›ฤ‡-skokowa'] = df['param_pojemnoล›ฤ‡-skokowa'].map(lambda x: -1 if str(x) == 'None' else int(x.split('cm')[0].replace(' ','') )) # + id="VOMKC-ezkqZw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="ade09400-30f1-466d-cb5a-efc8730490f8" executionInfo={"status": "ok", "timestamp": 1583796511536, "user_tz": -60, "elapsed": 13867, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17746203315080825597"}} feats = ['param_napฤ™d__cat', 'param_rok-produkcji', 'param_stan__cat', 'param_skrzynia-biegรณw__cat', 'param_faktura-vat__cat', 'param_moc', 'param_marka-pojazdu__cat', 'feature_kamera-cofania__cat', 'param_typ__cat', 'param_pojemnoล›ฤ‡-skokowa', 'seller_name__cat','feature_wspomaganie-kierownicy__cat', 'param_model-pojazdu__cat', 'param_wersja__cat', 'param_kod-silnika__cat','feature_system-start-stop__cat', 'feature_asystent-pasa-ruchu__cat', 'feature_czujniki-parkowania-przednie__cat', 'feature_ล‚opatki-zmiany-biegรณw__cat', 'feature_regulowane-zawieszenie__cat'] run_model(xgb.XGBRegressor(**xgb_params), feats) # + id="0uO9aKp-oT-z" colab_type="code" colab={} # !git
day4.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .cs // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: C# // language: csharp // name: csharp // --- // ![QuantConnect Logo](https://cdn.quantconnect.com/web/i/icon.png) // <hr> // ### Kalman Filters and Pairs Trading // // There are a few Python packages out there for Kalman filters, but we're adapting this example and the Kalman filter class code from [this article](https://www.quantstart.com/articles/kalman-filter-based-pairs-trading-strategy-in-qstrader) and demonstrating how you can implement similar ideas using QuantConnect!, // // Briefly, a Kalman filter is a [state-space model](https://en.wikipedia.org/wiki/State-space_representation) applicable to linear dynamic systems -- systems whose state is time-dependent and state variations are represented linearly. The model is used to estimate unknown states of a variable based on a series of past values. The procedure is two-fold: a prediction (estimate) is made by the filter of the current state of a variable and the uncertainty of the estimate itself. When new data is available, these estimates are updated. There is a lot of information available about Kalman filters, and the variety of their applications is pretty astounding, but for now, we're going to use a Kalman filter to estimate the hedge ratio between a pair of equities. // // The idea behind the strategy is pretty straightforward: take two equities that are cointegrated and create a long-short portfolio. The premise of this is that the spread between the value of our two positions should be mean-reverting. Anytime the spread deviates from its expected value, one of the assets moved in an unexpected direction and is due to revert back. When the spread diverges, you can take advantage of this by going long or short on the spread. // // To illustrate, imagine you have a long position in AAPL worth \\\\$2000 and a short position in IBM worth \\\\$2000. This gives you a net spread of \\\\$0. Since you expected AAPL and IBM to move together, then if the spread increases significantly above \\\\$0, you would short the spread in the expectation that it will return to \\\\$0, it's natural equilibrium. Similarly, if the value drops significantly below \\\\$0, you would long the spread and capture the profits as its value returns to \\\\$0. In our application, the Kalman filter will be used to track the hedging ratio between our equities to ensure that the portfolio value is stationary, which means it will continue to exhibit mean-reversion behavior. // QuantBook C# Research Environment // For more information see https://www.quantconnect.com/docs/research/overview #load "../QuantConnect.csx" var qb = new QuantBook(); var via = qb.AddEquity("VIA", Resolution.Daily).Symbol; var viab = qb.AddEquity("VIAB", Resolution.Daily).Symbol; // + public class KalmanFilter { private decimal delta = 0.0001M; private decimal[,] wt = new decimal[,] {{0.0001M / (1 - 0.0001M), 0}, {0 , 0.0001M / (1 - 0.0001M)}}; private decimal vt = 0.001M; private decimal[] theta = new decimal[2] {0, 0}; private decimal[,] P = new decimal[,] {{0, 0}, {0, 0}}; private decimal[,] R = null; private decimal qty = 2000; private decimal[,] C = new decimal[2,2]; public List<decimal> Update(decimal priceOne, decimal priceTwo) { // Create the observation matrix of the latest prices // of TLT and the intercept value (1.0) decimal[] F = new decimal[2] {priceOne, 1.0M}; decimal y = priceTwo; // The prior value of the states \theta_t is // distributed as a multivariate Gaussian with // mean a_t and variance-covariance R_t if(R == null){ R = new decimal[,] {{0, 0}, {0, 0}}; }else{ for(int k = 0; k <= 1; k++){ for(int j = 0; j <= 1; j++){ R[k,j] = C[k,j] + wt[k,j]; } } } // Calculate the Kalman Filter update // ---------------------------------- // Calculate prediction of new observation // as well as forecast error of that prediction decimal yhat = F[0] * theta[0] + F[1] * theta[1]; decimal et = y - yhat; // Q_t is the variance of the prediction of // observations and hence \sqrt{Q_t} is the // standard deviation of the predictions decimal[] FR = new decimal[2]; FR[0] = F[0] * R[0,0] + F[0] * R[0,1]; FR[1] = F[1] * R[1,0] + F[1] * R[1,1]; decimal Qt = FR[0] * F[0] + FR[1] * F[1] + vt; decimal sqrtQt = (decimal)Math.Sqrt(Convert.ToDouble(Qt)); // The posterior value of the states \theta_t is // distributed as a multivariate Gaussian with mean // m_t and variance-covariance C_t decimal[] At = new decimal[2] {FR[0] / Qt, FR[1] / Qt}; theta[0] = theta[0] + At[0] * et; theta[1] = theta[1] + At[1] * et; C[0,0] = R[0,0] - At[0] * FR[0]; C[0,1] = R[0,1] - At[0] * FR[1]; C[1,0] = R[1,0] - At[1] * FR[0]; C[1,1] = R[1,1] - At[1] * FR[1]; decimal hedgeQuantity = Math.Floor(qty * theta[0]); return new List<decimal>() {et, sqrtQt, hedgeQuantity}; } } // - // Now, we initialize the Kalman Filter, grab our data, and then run the Kalman Filter update process over the data. // // In an algorithm, the kf.qty variable is the number of shares to invested in VIAB, and hedge_quantity is the amount to trade in the opposite direction for VIA // + var kf = new KalmanFilter(); var history = qb.History(qb.Securities.Keys, new DateTime(2019, 1, 1), new DateTime(2019, 1, 11), Resolution.Daily); var prices = new Dictionary<Symbol, List<decimal>>(); foreach(var slice in history){ foreach(var symbol in slice.Keys){ if(!prices.ContainsKey(symbol)){ prices.Add(symbol, new List<decimal>()); } prices[symbol].Add(slice.Bars[symbol].Close); } } for(var k=0; k < prices[via].Count(); k++){ var via_price = prices[via][k]; var viab_price = prices[viab][k]; var result = kf.Update(via_price, viab_price); Console.WriteLine(result[0] + " : " + result[1] + " : " + result[2]); }
Research2Production/CSharp/04 Kalman Filters and Pairs Trading CSharp.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + id="I6xBUMdozpip" outputId="34a4aef2-d451-4ffb-e46d-b1f572290ad1" colab={"base_uri": "https://localhost:8080/", "height": 110} # IMPORT LIBRARIES import os import sys import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from pandas import set_option import matplotlib import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import seaborn as sns # %matplotlib inline # from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler # import performance metrics/measures from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report # from imblearn.under_sampling import KMeansSMOTE from imblearn.over_sampling import SMOTE from imblearn.pipeline import make_pipeline # + id="0ukT_B-Ozpiv" # VARIABLES # created a .csv version of the original dataset (.xls) INPUT_PATH = "https://raw.githubusercontent.com/robertofranceschi/default-credit-card-prediction/master/dataset/default%20of%20credit%20card%20clients.csv" # SCALER = 'std' # else 'minmax' SHOW_FIGURE = False # preprocessing FEATURE_SELECTION = False # if 'True' Feature Selection will be applied (i.e. 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6' will be removed) APPLY_PCA = False # if 'True' Principal Component Analysis will be applied APPLY_OVERSAMPLING = False # if 'True' SMOTE Oversampling will be applied RANDOM_STATE = 42 # fixed in order to have comparable results # Pandas options set_option('display.max_colwidth', None) set_option('precision', 2) # + id="BxnRfbe3zpi1" outputId="4f47f59c-6556-452c-e23a-613abf599d3b" colab={"base_uri": "https://localhost:8080/", "height": 217} # read input data = pd.read_csv(INPUT_PATH) data.head() # + id="605gSlh9zpj9" # Dataset balanced? if SHOW_FIGURE : font = FontProperties() font.set_family(['Times New Roman', 'serif']) font.set_size(14) plt.figure(figsize = (6,6)) sns.countplot('default.payment.next.month', data=data, palette=['steelblue','crimson']) # plt.title('Class Distribution Histogram', fontsize=14) plt.xticks([0,1],['Not default','Default'],fontproperties=font) plt.ylabel('# of samples', fontproperties=font) plt.xlabel('') # plt.show() plt.savefig('Fig - Class Distribution Histogram.png') # + id="YcYnM4BmKGyV" outputId="b00535c3-3f5a-48c6-d6ed-2788b5ac9111" colab={"base_uri": "https://localhost:8080/", "height": 488} # Check data types data.dtypes # + id="76PPKPHOzpjK" outputId="07b850de-f33f-461b-e7bd-8f940c819511" colab={"base_uri": "https://localhost:8080/", "height": 35} # Check missing values: no as can be also seen with data.info() data.isnull().values.any() # + id="br3RuO_7XtTu" outputId="c2307afe-c209-4d81-8988-74fbe027fbff" colab={"base_uri": "https://localhost:8080/", "height": 307} # Summary Statistics data.describe() # + id="7-YxsZlYFXwE" # rename variable 'PAY_0' to 'PAY_1' data.rename(columns={"PAY_0": "PAY_1"}, inplace=True) # rename target variable: 'default.payment.next.month' to 'Default' data.rename(columns={"default.payment.next.month": "Default"}, inplace=True) # drop first attribute "ID" data.drop('ID', axis = 1, inplace =True) # Class label to category data["Default"] = data["Default"].astype('category') # + id="hCkD_8s6zpjT" outputId="66f50f9c-3e01-4954-887a-6e55f0318e76" colab={"base_uri": "https://localhost:8080/", "height": 108} data['MARRIAGE'].value_counts() # + id="TilhkI5czpjZ" outputId="7afaed4f-c5bc-4ba3-b7cb-9245ab07a49d" colab={"base_uri": "https://localhost:8080/", "height": 162} data['EDUCATION'].value_counts() # + id="zMal2aDOzpje" # category '0' undocumented is deleted data = data.drop(data[data['MARRIAGE']==0].index) # we could also group the 0 category with 3:others # data['MARRIAGE']=np.where(data['MARRIAGE'] == 0, 3, data['MARRIAGE']) # categories 0, 5 and 6 are unknown and are deleted data = data.drop(data[data['EDUCATION']==0].index) data = data.drop(data[data['EDUCATION']==5].index) data = data.drop(data[data['EDUCATION']==6].index) # we could also group the categories together # data['EDUCATION']=np.where(data['EDUCATION'] == 5, 4, data['EDUCATION']) # data['EDUCATION']=np.where(data['EDUCATION'] == 6, 4, data['EDUCATION']) # data['EDUCATION']=np.where(data['EDUCATION'] == 0, 4, data['EDUCATION']) # + id="pjDVytB_zpjl" if SHOW_FIGURE : # 1=graduate school, 2=university, 3=high school 4=others data['EDUCATION'].value_counts().plot(kind='bar', figsize=(10,6)) # plt.title("Number of cars by make") plt.xticks([0,1,2,3],['University','Graduate\nSchool', 'High\nSchool', 'Others'],fontproperties=font,rotation=0) # plt.xlabel('Education level', fontproperties=font) plt.ylabel('# of clients', fontproperties=font) # plt.show() plt.savefig('Fig - Education Level barplot.png') # + id="UCbizDuhzpjr" if SHOW_FIGURE : # 1=married, 2=single, 3=others data['MARRIAGE'].value_counts().plot(kind='bar', figsize=(10,6)) # plt.title("Number of cars by make") plt.xticks([0,1,2],['Single','Married', 'Others'],fontproperties=font,rotation=0) # plt.xlabel('Marital Status', fontproperties=font) plt.ylabel('# of clients', fontproperties=font) # plt.show() plt.savefig('Fig - Marital Status.png') # + id="6psCg6Y2zpkS" outputId="0734172e-976d-4aa2-b46f-4a515e7714ac" colab={"base_uri": "https://localhost:8080/", "height": 287} # Payment delay description data[['PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']].describe() # + id="bXiM4RtkS1FP" # REPAYMENT STATUS = -1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above # for att in ['PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']: # print(f"# {att} -------") # print(data[att].value_counts()) # + id="JfjguM7bhC6C" # since PAY_n can take as values only -1,1,2,3,4,5,6,7,8,9 for att in ['PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']: # categories -2,-1 are grouped into a single class -1: pay duty filter = (data[att] == -2) | (data[att] == -1) data.loc[filter, att] = -1 # print(data[att].unique()) # moreover the category 0 is undocumented # so each category >= 0 has been updated by adding 1 data[att] = data[att].astype('int64') filter = (data[att] >= 0) data.loc[filter, att] = data.loc[filter, att] + 1 # print(data[att].unique()) # print("##############################################") # + id="bvyrQ1-tUEtm" outputId="fb766079-05ca-4f4f-b659-93227284d6ee" colab={"base_uri": "https://localhost:8080/", "height": 287} # Payment delay description data[['PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']].describe() # + id="lkazd9Z_UEts" # # REPAYMENT STATUS = -1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above # for att in ['PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']: # print(f"# {att} -------") # print(data[att].value_counts()) # + id="EeGQR6ZoYhvT" if SHOW_FIGURE : # Creating a new dataframe with categorical variables subset = data[['SEX', 'EDUCATION', 'MARRIAGE', 'PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6', 'Default']] f, axes = plt.subplots(3, 3, figsize=(20, 15), facecolor='white') f.suptitle('FREQUENCY OF CATEGORICAL VARIABLES (BY TARGET)') ax1 = sns.countplot(x="SEX", hue="Default", data=subset, palette="Blues", ax=axes[0,0]) ax2 = sns.countplot(x="EDUCATION", hue="Default", data=subset, palette="Blues",ax=axes[0,1]) ax3 = sns.countplot(x="MARRIAGE", hue="Default", data=subset, palette="Blues",ax=axes[0,2]) ax4 = sns.countplot(x="PAY_1", hue="Default", data=subset, palette="Blues", ax=axes[1,0]) ax5 = sns.countplot(x="PAY_2", hue="Default", data=subset, palette="Blues", ax=axes[1,1]) ax6 = sns.countplot(x="PAY_3", hue="Default", data=subset, palette="Blues", ax=axes[1,2]) ax7 = sns.countplot(x="PAY_4", hue="Default", data=subset, palette="Blues", ax=axes[2,0]) ax8 = sns.countplot(x="PAY_5", hue="Default", data=subset, palette="Blues", ax=axes[2,1]) ax9 = sns.countplot(x="PAY_6", hue="Default", data=subset, palette="Blues", ax=axes[2,2]); # + id="pqulwUJ2zpkc" outputId="13460ca4-eabe-49ce-989e-6b0d8bfa2ebc" colab={"base_uri": "https://localhost:8080/", "height": 287} # Bill Statement description data[['BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6']].describe() # + id="cdUD5NUszpki" outputId="e63384d9-bf05-4f74-a6c5-e18dbfedbb1d" colab={"base_uri": "https://localhost:8080/", "height": 287} # Previous Payment Description data[['PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6']].describe() # + id="hwvSfKKIzpko" outputId="e9ffd365-f5d1-4f88-e575-ab450ca27e7a" colab={"base_uri": "https://localhost:8080/", "height": 180} data.LIMIT_BAL.describe() # + id="2_Ez3QFEq0ZP" # plt.figure(figsize = (14,6)) # plt.title('Amount of credit limit - Density Plot') # sns.set_color_codes("pastel") # sns.distplot(data['LIMIT_BAL'],kde=True,bins=200, color="blue") # plt.show() # + id="b_M3fZ8BrBff" # data['LIMIT_BAL'].value_counts().head(10) # + id="vUv4pbElzpkt" # x1 = list(data[data['Default'] == 1]['LIMIT_BAL']) # x2 = list(data[data['Default'] == 0]['LIMIT_BAL']) # plt.figure(figsize=(12,4)) # sns.set_context('notebook', font_scale=1.2) # #sns.set_color_codes("pastel") # plt.hist([x1, x2], bins = 40, color=['steelblue', 'lightblue']) # # plt.xlim([0,600000]) # plt.legend(['Yes', 'No'], title = 'Default', loc='upper right', facecolor='white') # plt.xlabel('Limit Balance (NT dollar)') # plt.ylabel('Frequency') # plt.title('LIMIT BALANCE HISTOGRAM BY TYPE OF CREDIT CARD', SIZE=15) # plt.box(False) # plt.savefig('ImageName', format='png', dpi=200, transparent=True); # + id="79i_3RaksjAi" # class_1 = data.loc[data['Default'] == 1]["LIMIT_BAL"] # class_0 = data.loc[data['Default'] == 0]["LIMIT_BAL"] # plt.figure(figsize = (14,6)) # # plt.title('Default amount of credit limit - grouped by Payment Next Month (Density Plot)') # sns.set_color_codes("pastel") # sns.distplot(class_1,kde=True,bins=200, color="red") # sns.distplot(class_0,kde=True,bins=200, color="green") # plt.savefig('Fig - Density plot LIMIT_BAL grouped by label.png') # + id="GhUymmg5UEuV" if SHOW_FIGURE : # HISTOGRAMS PLOTS FOR FEATURES IMPORTANCE fig, axes= plt.subplots(6,4, figsize=(12,12)) non_def = data[data.Default==0] default = data[data.Default==1] ax = axes.ravel() for i,label in enumerate(data.columns[:-1]): _,bins = np.histogram(data[label],bins=100) ax[i].hist(non_def[label],bins=bins,color='r',alpha=.5)# red color for malignant class ax[i].hist(default[label],bins=bins,color='g',alpha=0.3)# alpha is for transparency in the overlapped region ax[i].set_title(data.columns[i],fontsize=9) ax[i].axes.get_xaxis().set_visible(True) # the x-axis co-ordinates are not so useful, as we just want to look how well separated the histograms are ax[i].set_yticks(()) ax[0].legend(['Non Default','Default'],loc='best',fontsize=8) plt.tight_layout() # let's make good plots #plt.show() # + id="pwg8bhsAzpk_" outputId="1bf176bf-e86d-4e7b-c562-0c5ccff0076d" colab={"base_uri": "https://localhost:8080/", "height": 806} # Correlation matrix sns.set(style="white", font_scale=1) numeric = ['LIMIT_BAL','AGE','BILL_AMT1','BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'] corr = data[numeric].corr() # .corr is used to find corelation mask = np.triu(np.ones_like(corr, dtype=np.bool)) f, ax = plt.subplots(figsize=(20, 13)) cmap = sns.diverging_palette(220, 10, as_cmap=True) ax=sns.heatmap(corr, mask=mask, vmax=1, vmin=-1, center=0, square=True, linewidths=.5, cmap=cmap, cbar_kws={"shrink": .5}, annot=True, annot_kws={"size": 10}) cbar=ax.collections[0].colorbar cbar.set_ticks([-1, -0.50, 0, 0.50, 1]) # plt.xticks(fontsize=6) # plt.yticks(fontsize=10) # plt.show() plt.savefig('Fig - Correlation matrix by means of the Pearsonโ€™s coefficient for all feature pairs.png') # + id="xXyRXb8IUEug" outputId="70ba73d6-4d58-43a2-b38f-a09607a5383d" colab={"base_uri": "https://localhost:8080/", "height": 436} #distribution correlated features -- scatter interaction import matplotlib.patches as mpatches data_np=data.to_numpy() target=data.Default # variables to BILL_AMT1 = data['BILL_AMT1'].to_numpy() BILL_AMT2 = data['BILL_AMT2'].to_numpy() BILL_AMT3 = data['BILL_AMT3'].to_numpy() BILL_AMT4 = data['BILL_AMT4'].to_numpy() BILL_AMT5 = data['BILL_AMT5'].to_numpy() BILL_AMT6 = data['BILL_AMT6'].to_numpy() AGE = data['AGE'].to_numpy() LIMIT_BAL = data['LIMIT_BAL'].to_numpy() PAY_AMT1 = data['PAY_AMT1'].to_numpy() fig, ax = plt.subplots(1,3, figsize= (15,6)) labels=["Non Default","Default"] pop_a = mpatches.Patch(color='steelblue', label='Non Default') pop_b = mpatches.Patch(color='crimson', label='Default') colors=['crimson', 'steelblue'] ax[0].scatter(BILL_AMT1, BILL_AMT2, c=target, cmap=matplotlib.colors.ListedColormap(colors), label=labels, alpha=0.5) ax[0].grid() ax[0].set_xlabel('BILL_AMT1') ax[0].set_ylabel('BILL_AMT2') ax[0].legend(handles= [pop_a,pop_b]) ax[1].scatter(BILL_AMT2, BILL_AMT3, c=target, cmap=matplotlib.colors.ListedColormap(colors), alpha=0.5) ax[1].grid() ax[1].set_xlabel('BILL_AMT2') ax[1].set_ylabel('BILL_AMT3') ax[1].legend(handles= [pop_a,pop_b]) ax[2].scatter(BILL_AMT4,BILL_AMT5, c=target, cmap=matplotlib.colors.ListedColormap(colors), alpha=0.5) ax[2].grid() ax[2].set_xlabel('BILL_AMT4') ax[2].set_ylabel('BILL_AMT5') ax[2].legend(handles= [pop_a,pop_b]) plt.tight_layout()# let's make good plots plt.show() # + id="nk3cBZ7GUEuk" outputId="3009a473-68aa-491e-bb3a-57b29091369c" colab={"base_uri": "https://localhost:8080/", "height": 436} #distribution un-correlated features -- scatter interaction fig, ax = plt.subplots(1,3, figsize= (15,6)) labels=["Non Default","Default"] pop_a = mpatches.Patch(color='steelblue', label='Non Default') pop_b = mpatches.Patch(color='crimson', label='Default') colors=['crimson', 'steelblue'] ax[0].scatter(AGE, LIMIT_BAL, c=target, cmap=matplotlib.colors.ListedColormap(colors), label=labels, alpha=0.5) ax[0].grid() ax[0].set_xlabel('AGE') ax[0].set_ylabel('LIMIT_BAL') ax[0].legend(handles= [pop_a,pop_b]) ax[1].scatter(AGE, BILL_AMT1, c=target, cmap=matplotlib.colors.ListedColormap(colors), alpha=0.5) ax[1].grid() ax[1].set_xlabel('AGE') ax[1].set_ylabel('BILL_AMT1') ax[1].legend(handles= [pop_a,pop_b]) ax[2].scatter(PAY_AMT1,BILL_AMT1, c=target, cmap=matplotlib.colors.ListedColormap(colors), alpha=0.5) ax[2].grid() ax[2].set_xlabel('PAY_AMT1') ax[2].set_ylabel('BILL_AMT1') ax[2].legend(handles= [pop_a,pop_b]) plt.tight_layout()# let's make good plots plt.show() # + id="R_AK9qe4UEuo" outputId="b4909fb3-deae-4e4c-847f-572071bdbb97" colab={"base_uri": "https://localhost:8080/", "height": 913} scaler = MinMaxScaler() data['LIMIT_BAL'] = scaler.fit_transform(data['LIMIT_BAL'].values.reshape(-1, 1)) data['AGE'] = scaler.fit_transform(data['AGE'].values.reshape(-1, 1)) for i in range(1,7): scaler = MinMaxScaler() data['PAY_' + str(i)] = scaler.fit_transform(data['PAY_' + str(i)].values.reshape(-1, 1)) for i in range(1,7): scaler = MinMaxScaler() data['BILL_AMT' + str(i)] = scaler.fit_transform(data['BILL_AMT' + str(i)].values.reshape(-1, 1)) for i in range(1,7): scaler = MinMaxScaler() data['PAY_AMT' + str(i)] = scaler.fit_transform(data['PAY_AMT' + str(i)].values.reshape(-1, 1)) # BOXPLOT cols = ['LIMIT_BAL','AGE','BILL_AMT1','BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'] fig=plt.figure(1, figsize=(25,15)) ax=fig.add_subplot(111) sns.boxplot(data=data[cols]) plt.xticks(np.arange(0,14), labels=cols, rotation=25, fontsize=18) plt.yticks(fontsize=18) # plt.title('Boxplot', fontsize= 35) plt.savefig('Fig - Boxplot') # + [markdown] id="YsCj4PstUEux" # #### Standardization # # Another possible scaling technique is referred to as **standardization**, which transforms each value $x$ of feature $X$ as follows, independently for each column: # # \begin{equation} # x^{\prime} =\frac{x-\mu _{X}}{\sigma _{X}} # \end{equation} # # where $\mu_{X}$ is the sample mean and $\sigma_{X}$ is the sample standard deviation of feature $X$. This way, we force each attribute to have a new empirical mean value of 0 and variance 1. # # + id="FafXsX07UEuy" outputId="1c49e672-b63d-4d84-8121-33ecaf597333" colab={"base_uri": "https://localhost:8080/", "height": 913} # Standard Scaler from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaled_data = scaler.fit_transform(data) # BOXPLOT cols = ['LIMIT_BAL','AGE','BILL_AMT1','BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'] fig=plt.figure(1, figsize=(25,15)) ax=fig.add_subplot(111) sns.boxplot(data=scaled_data[:,:-10]) plt.xticks(np.arange(0,14), labels=cols, rotation=25, fontsize=18) plt.yticks(fontsize=18) # plt.title('Boxplot', fontsize= 35) plt.savefig('Fig - Boxplot Std Scaler') # + [markdown] id="L0jdlMRazplY" # ## 3. Data Preprocessing # + id="v66pw7H9qxYH" outputId="5a77cd6e-b9eb-4fa3-99a8-60be80eb5d05" colab={"base_uri": "https://localhost:8080/", "height": 217} # Set 'category' type to categorical attributes for att in ['SEX', 'EDUCATION', 'MARRIAGE']: data[att] = data[att].astype('category') # one-hot encoding data=pd.concat([pd.get_dummies(data['SEX'], prefix='SEX'), pd.get_dummies(data['EDUCATION'], prefix='EDUCATION'), pd.get_dummies(data['MARRIAGE'], prefix='MARRIAGE'), data],axis=1) # drop original columns data.drop(['EDUCATION'],axis=1, inplace=True) data.drop(['SEX'],axis=1, inplace=True) data.drop(['MARRIAGE'],axis=1, inplace=True) # print samples data.head() # + id="32BQbKfAUEvB" # Separating features and target y = data.Default # target default=1 or non-default=0 X = data.drop('Default', axis = 1, inplace = False) # + id="EpoqlyxKUEvG" outputId="1e1ea2fa-f4f7-4bdc-be53-eead7c6aae0e" colab={"base_uri": "https://localhost:8080/", "height": 72} # Check data set dimension print(X.shape) print("Number of samples:", X.shape[0]) print("Number of attributes:", X.shape[1]) # + id="hD6YDubaqxpU" from sklearn.model_selection import train_test_split X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=0.25, random_state=RANDOM_STATE, stratify=y) # + id="Au4tzO-zqxa5" outputId="31fa60ae-24f1-46bf-a1cf-0ca959426194" colab={"base_uri": "https://localhost:8080/", "height": 162} # Check dimensions print(np.shape(X_train_val)) print(np.shape(X_test)) print("Training set:") print(f" + Non-defaulters (y=0): {len(y_train_val[y_train_val==0])}") print(f" + Defaulters (y=1):\t {len(y_train_val[y_train_val==1])}") print("Test set:") print(f" + Non-defaulters (y=0): {len(y_test[y_test==0])}") print(f" + Defaulters (y=1):\t {len(y_test[y_test==1])}") # + id="FB5AUHsQUEvS" if FEATURE_SELECTION : # remove features with correlation coefficent >= 0.93 upper = corr.where(np.triu(np.ones(corr.shape), k=1).astype(np.bool)) to_drop = [column for column in upper.columns if any(upper[column] >= 0.92)] print(to_drop) #['BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6'] data= data.drop(data[to_drop], axis = 1) # + id="A_u9zFxDUEvZ" outputId="5c004529-fb63-4cd7-d760-db235417dd9e" colab={"base_uri": "https://localhost:8080/", "height": 357} from sklearn.decomposition import PCA print(f"Actual number of components: {len(X_train_val.columns.values)}") n_pc = len(X_train_val.columns.values) # with n_components = 11 -> 0.98693009 variance explained pca = PCA(n_components=n_pc) pca.fit(X_train_val) # print(np.cumsum(pca.explained_variance_ratio_)) # print(pca.explained_variance_ratio_) fig=plt.figure(1, figsize=(10,5)) plt.grid(b=True, which='major', axis='both') plt.plot(pca.explained_variance_ratio_, marker='o', color='#20c8b8') plt.plot(np.cumsum(pca.explained_variance_ratio_), marker='o', color='#e8a000') # plt.xticks([n for n in range(0,n_pc)], [ "PC"+str(n) for n in range(1,n_pc+1)]) plt.legend(["Variance explained by a single component", "Cumulative variance explained"]) plt.xlabel('Number of principal components') plt.ylabel('Variance Explained') plt.savefig("PCA"); # + id="aZ1rRp8VUEvc" outputId="dce3efab-8822-4a9b-fd2f-bc00791f5eb6" colab={"base_uri": "https://localhost:8080/", "height": 197} n_pc = 12 pca = PCA(n_components=n_pc) pca.fit(X_train_val) # X_train_val.index = pd.RangeIndex(start=0, stop=len(X_train_val), step=1) X_12d_train_val = pd.DataFrame(pca.transform(X_train_val)) X_12d_test = pd.DataFrame(pca.transform(X_test)) X_12d_train_val.columns = ['PC' + str(i) for i in range(1, n_pc+1) ] X_12d_test.columns = ['PC' + str(i) for i in range(1, n_pc+1) ] X_12d_train_val.head() # + id="3R3nEJcZUEvg" outputId="cdfc502d-1f27-4c6d-eca0-3f460c26aa2c" colab={"base_uri": "https://localhost:8080/", "height": 108} APPLY_PCA = False if APPLY_PCA: X_train_val = X_12d_train_val X_test = X_12d_test print(X_12d_train_val.shape) print(X_12d_test.shape) print(f"PCA APPLIED: {APPLY_PCA}") print(X_train_val.shape) print(X_test.shape) # + id="ytPQp9rtUEvp" import imblearn from imblearn.over_sampling import SMOTE from imblearn.under_sampling import ClusterCentroids from imblearn.pipeline import make_pipeline import sklearn.ensemble from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC, LinearSVC from sklearn.metrics import f1_score, make_scorer, precision_score, recall_score, accuracy_score, plot_confusion_matrix from sklearn.svm import LinearSVC, SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression # PARAMETER CLASSIFICATION ALGORITHM = 'LogisticRegression' # 'RandomForest', 'LogisticRegression', 'LDA', 'KNN' APPLY_OVERSAMPLING = False APPLY_UNDERSAMPLING = True if APPLY_OVERSAMPLING: APPLY_UNDERSAMPLING = False if APPLY_UNDERSAMPLING: APPLY_OVERSAMPLING = False # + id="IQrMhPttUEvr" outputId="5dcff8b3-d064-43d8-c048-5f4affa9ff6a" colab={"base_uri": "https://localhost:8080/", "height": 689} # TRAIN AND VALIDATION # Stratified K-Fold Cross Validation # Pipeline if ALGORITHM == 'SVM' : # Support Vector Machine (SVM) classifier # best config found {'C': 1, 'gamma': 0.01, 'kernel': 'poly'} # 0.7963817277250114 parameter_grid = { 'C': [100, 0.1, 1, 10], 'kernel': ['rbf', 'poly'], 'gamma': [0.0001, 0.001, 0.01] } clf_name = 'svc__' classifier = SVC() # or SVC elif ALGORITHM == 'RandomForest': # Random Forest classifier # {'randomforestclassifier__criterion': 'entropy', 'randomforestclassifier__max_features': 'sqrt', 'randomforestclassifier__n_estimators': 100, 'randomforestclassifier__oob_score': True} parameter_grid = { "criterion":["gini", "entropy"], "max_features":[None, "sqrt"], "oob_score":[True], "n_estimators":[10, 50, 100, 200] } clf_name = 'randomforestclassifier__' classifier = RandomForestClassifier() elif ALGORITHM == 'LogisticRegression': # Logistic Regression classifier parameter_grid = { "C":[0.0001, 0.001, 0.01, 0.1, 1, 10] } clf_name = 'logisticregression__' classifier = LogisticRegression() elif ALGORITHM == 'KNN': # K-Nearest Neighbors classifier parameter_grid = { "n_neighbors":[500, 800, 1500, 2500, 3500, 4500] } clf_name = 'kneighborsclassifier__' classifier = KNeighborsClassifier() else : raise RuntimeError("Choose a correct classifier."); new_params = {clf_name + key: parameter_grid[key] for key in parameter_grid} kf = StratifiedKFold(n_splits=5, random_state=RANDOM_STATE) if APPLY_OVERSAMPLING: # apply oversampling on training dataset imba_pipeline = make_pipeline(SMOTE(random_state=RANDOM_STATE), classifier) elif APPLY_UNDERSAMPLING: # TO DO imba_pipeline = make_pipeline(ClusterCentroids(random_state=RANDOM_STATE), classifier) else : # DO NOT apply oversampling on training dataset, just the classifier imba_pipeline = make_pipeline(classifier) SCORE = 'precision' # 'accuracy', 'precision', 'recall', 'f1' grid_imba = GridSearchCV(imba_pipeline, param_grid=new_params, cv=kf, scoring=SCORE, return_train_score=True) grid_imba.fit(X_train_val, y_train_val) print(f"Best configuration found for {classifier}:") print(grid_imba.best_params_) print(f"Val {SCORE}: {grid_imba.best_score_}") # + id="Z_yTXCrrUEvv" # TEST # evaluation on test data with bestparams # Oversampling smote = SMOTE() X_train_val, y_train_val = smote.fit_resample(X_train_val, y_train_val) # retrain with best params clf = classifier clf.fit(X_train_val, y_train_val) y_pred = clf.predict(X_test) accuracy=accuracy_score(y_test, y_pred) f1=f1_score(y_test, y_pred) precision=precision_score(y_test, y_pred) recall=recall_score(y_test, y_pred) print(accuracy, f1, precision, recall) print(f"") # print(classification_report()) disp = plot_confusion_matrix(clf, X_test, y_test, #display_labels=class_names, cmap=plt.cm.Blues, #display_labels=data.target_names, normalize='true') disp.ax_.set_title(f'normalized confusion matrix {clf_name}')
code.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: conda_python3 # language: python # name: conda_python3 # --- # # A/B Testing with Amazon SageMaker # # In production ML workflows, data scientists and data engineers frequently try to improve their models in various ways, such as by performing [Perform Automatic Model Tuning](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning.html), training on additional or more-recent data, and improving feature selection. Performing A/B testing between a new model and an old model with production traffic can be an effective final step in the validation process for a new model. In A/B testing, you test different variants of your models and compare how each variant performs relative to each other. You then choose the best-performing model to replace a previously-existing model new version delivers better performance than the previously-existing version. # # Amazon SageMaker enables you to test multiple models or model versions behind the same endpoint using production variants. Each production variant identifies a machine learning (ML) model and the resources deployed for hosting the model. You can distribute endpoint invocation requests across multiple production variants by providing the traffic distribution for each variant, or you can invoke a specific variant directly for each request. # # In this notebook we'll: # * Evaluate models by invoking specific variants # * Gradually release a new model by specifying traffic distribution # ### Prerrequisites # # First we ensure we have an updated version of boto3, which includes the latest SageMaker features: # !pip install -qU awscli # !pip install -qU pandas from IPython.core.display import HTML HTML("<script>Jupyter.notebook.kernel.restart()</script>") # ## Configuration # Let's set up some required imports and basic initial variables: # + isConfigCell=true # %%time # %matplotlib inline from datetime import datetime, timedelta import time import os import boto3 import re import json from sagemaker import get_execution_role, session from sagemaker.s3 import S3Downloader, S3Uploader region= boto3.Session().region_name role = get_execution_role() sm_session = session.Session(boto3.Session()) sm = boto3.Session().client("sagemaker") sm_runtime = boto3.Session().client("sagemaker-runtime") # You can use a different bucket, but make sure the role you chose for this notebook # has the s3:PutObject permissions. This is the bucket into which the model artifacts will be uploaded bucket = sm_session.default_bucket() prefix = 'sagemaker/DEMO-VariantTargeting' # - # ## Step 1: Create and deploy the models # # ### First, we upload our pre-trained models to Amazon S3 # This code uploads two pre-trained XGBoost models that are ready for you to deploy. These models were trained using the XGB Churn Prediction Notebook in SageMaker. You can also use your own pre-trained models in this step. If you already have a pretrained model in Amazon S3, you can add it by specifying the s3_key. # # The models in this example are used to predict the probability of a mobile customer leaving their current mobile operator. The dataset we use is publicly available and was mentioned in the book [Discovering Knowledge in Data](https://www.amazon.com/dp/0470908742/) by <NAME>. It is attributed by the author to the University of California Irvine Repository of Machine Learning Datasets. model_url = S3Uploader.upload(local_path="model/xgb-churn-prediction-model.tar.gz", desired_s3_uri=f"s3://{bucket}/{prefix}") model_url2 = S3Uploader.upload(local_path="model/xgb-churn-prediction-model2.tar.gz", desired_s3_uri=f"s3://{bucket}/{prefix}") model_url, model_url2 # ### Next, we create our model definitions # Start with deploying the pre-trained churn prediction models. Here, you create the model objects with the image and model data. # + from sagemaker.amazon.amazon_estimator import get_image_uri model_name = f"DEMO-xgb-churn-pred-{datetime.now():%Y-%m-%d-%H-%M-%S}" model_name2 = f"DEMO-xgb-churn-pred2-{datetime.now():%Y-%m-%d-%H-%M-%S}" image_uri = get_image_uri(boto3.Session().region_name, 'xgboost', '0.90-1') image_uri2 = get_image_uri(boto3.Session().region_name, 'xgboost', '0.90-2') sm_session.create_model(name=model_name, role=role, container_defs={ 'Image': image_uri, 'ModelDataUrl': model_url }) sm_session.create_model(name=model_name2, role=role, container_defs={ 'Image': image_uri2, 'ModelDataUrl': model_url2 }) # - # ### Create variants # # We now create two variants, each with its own different model (these could also have different instance types and counts). # # We set an initial_weight of โ€œ1โ€ for both variants: this means 50% of our requests go to Variant1, and the remaining 50% of all requests to Variant2. (The sum of weights across both variants is 2 and each variant has weight assignment of 1. This implies each variant receives 1/2, or 50%, of the total traffic.) # + from sagemaker.session import production_variant variant1 = production_variant(model_name=model_name, instance_type="ml.m5.xlarge", initial_instance_count=1, variant_name='Variant1', initial_weight=1) variant2 = production_variant(model_name=model_name2, instance_type="ml.m5.xlarge", initial_instance_count=1, variant_name='Variant2', initial_weight=1) (variant1, variant2) # - # ### Deploy # # Let's go ahead and deploy our two variants to a SageMaker endpoint: # + endpoint_name = f"DEMO-xgb-churn-pred-{datetime.now():%Y-%m-%d-%H-%M-%S}" print(f"EndpointName={endpoint_name}") sm_session.endpoint_from_production_variants( name=endpoint_name, production_variants=[variant1, variant2] ) # - # ## Step 2: Invoke the deployed models # # You can now send data to this endpoint to get inferences in real time. # # This step invokes the endpoint with included sample data for about 2 minutes. # + # get a subset of test data for a quick test # !tail -120 test_data/test-dataset-input-cols.csv > test_data/test_sample_tail_input_cols.csv print(f"Sending test traffic to the endpoint {endpoint_name}. \nPlease wait...") with open('test_data/test_sample_tail_input_cols.csv', 'r') as f: for row in f: print(".", end="", flush=True) payload = row.rstrip('\n') sm_runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType="text/csv", Body=payload) time.sleep(0.5) print("Done!") # - # ### Invocations per variant # # Amazon SageMaker emits metrics such as Latency and Invocations (full list of metrics [here](https://alpha-docs-aws.amazon.com/sagemaker/latest/dg/monitoring-cloudwatch.html)) for each variant in Amazon CloudWatch. Letโ€™s query CloudWatch to get number of Invocations per variant, to show how invocations are split across variants: # + import pandas as pd cw = boto3.Session().client("cloudwatch") def get_invocation_metrics_for_endpoint_variant(endpoint_name, variant_name, start_time, end_time): metrics = cw.get_metric_statistics( Namespace="AWS/SageMaker", MetricName="Invocations", StartTime=start_time, EndTime=end_time, Period=60, Statistics=["Sum"], Dimensions=[ { "Name": "EndpointName", "Value": endpoint_name }, { "Name": "VariantName", "Value": variant_name } ] ) return pd.DataFrame(metrics["Datapoints"])\ .sort_values("Timestamp")\ .set_index("Timestamp")\ .drop("Unit", axis=1)\ .rename(columns={"Sum": variant_name}) def plot_endpoint_metrics(start_time=None): start_time = start_time or datetime.now() - timedelta(minutes=60) end_time = datetime.now() metrics_variant1 = get_invocation_metrics_for_endpoint_variant(endpoint_name, variant1["VariantName"], start_time, end_time) metrics_variant2 = get_invocation_metrics_for_endpoint_variant(endpoint_name, variant2["VariantName"], start_time, end_time) metrics_variants = metrics_variant1.join(metrics_variant2, how="outer") metrics_variants.plot() return metrics_variants # - # ### Run Sample Invocations # + import numpy as np predictions = '' print(f"Sending test traffic to the endpoint {endpoint_name}. \nPlease wait...") with open('test_data/test_sample_tail_input_cols.csv', 'r') as f: for row in f: print(".", end="", flush=True) payload = row.rstrip('\n') response = sm_runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType="text/csv", Body=payload) #print(response) predictions = ','.join([predictions, response['Body'].read().decode('utf-8')]) time.sleep(0.5) #print('Predictions: ' +predictions) #print(predictions) # Convert our predictions to a numpy array pred_np = np.fromstring(predictions[1:], sep=',') # Convert the prediction probabilities to binary predictions of either 1 or 0 threshold = 0.5 preds = np.where(pred_np > threshold, 1, 0) print("Done!") print(preds) # - print("Waiting a minute for initial metric creation...") time.sleep(60) plot_endpoint_metrics() # ### Invoke a specific variant # # Now, letโ€™s use the new feature that was released today to invoke a specific variant. For this, we simply use the new parameter to define which specific ProductionVariant we want to invoke. Let us use this to invoke Variant1 for all requests. # + import numpy as np predictions = '' print(f"Sending test traffic to the endpoint {endpoint_name}. \nPlease wait...") with open('test_data/test_sample_tail_input_cols.csv', 'r') as f: for row in f: print(".", end="", flush=True) payload = row.rstrip('\n') response = sm_runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType="text/csv", Body=payload, TargetVariant=variant1["VariantName"]) predictions = ','.join([predictions, response['Body'].read().decode('utf-8')]) time.sleep(0.5) # Convert our predictions to a numpy array pred_np = np.fromstring(predictions[1:], sep=',') # Convert the prediction probabilities to binary predictions of either 1 or 0 threshold = 0.5 preds = np.where(pred_np > threshold, 1, 0) print("Done!") # - # When we again check the traffic per variant, this time we see that the number of invocations only incremented for Variant1, because all invocations were targeted at that variant: time.sleep(20) #let metrics catch up plot_endpoint_metrics() # ## Step 3: Evaluate variant performance # # ### Evaluating Variant 1 # # Using the new targeting feature, let us evaluate the accuracy, precision, recall, F1 score, and ROC/AUC for Variant1: # + import matplotlib.pyplot as plt import pandas as pd from sklearn import metrics from sklearn.metrics import roc_auc_score # Let's get the labels of our test set; we will use these to evaluate our predictions # !tail -121 test_data/test-dataset.csv > test_data/test_dataset_sample_tail.csv df_with_labels = pd.read_csv('test_data/test_dataset_sample_tail.csv') test_labels = df_with_labels.iloc[:, 0] labels = test_labels.to_numpy() # Calculate accuracy accuracy = sum(preds == labels) / len(labels) print(f'Accuracy: {accuracy}') # Calculate precision precision = sum(preds[preds == 1] == labels[preds == 1]) / len(preds[preds == 1]) print(f'Precision: {precision}') # Calculate recall recall = sum(preds[preds == 1] == labels[preds == 1]) / len(labels[labels == 1]) print(f'Recall: {recall}') # Calculate F1 score f1_score = 2 * (precision * recall) / (precision + recall) print(f'F1 Score: {f1_score}') # Calculate AUC auc = round(roc_auc_score(labels, preds), 4) print('AUC is ' + repr(auc)) fpr, tpr, _ = metrics.roc_curve(labels, preds) plt.title('ROC Curve') plt.plot(fpr, tpr, 'b', label='AUC = %0.2f'% auc) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'r--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() # - # ### Next, we collect data for Variant2 # + predictions2 = '' print(f"Sending test traffic to the endpoint {endpoint_name}. \nPlease wait...") with open('test_data/test_sample_tail_input_cols.csv', 'r') as f: for row in f: print(".", end="", flush=True) payload = row.rstrip('\n') response = sm_runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType="text/csv", Body=payload, TargetVariant=variant2["VariantName"]) predictions2 = ','.join([predictions2, response['Body'].read().decode('utf-8')]) time.sleep(0.5) # Convert to numpy array pred_np2 = np.fromstring(predictions2[1:], sep=',') # Convert to binary predictions thresh = 0.5 preds2 = np.where(pred_np2 > threshold, 1, 0) print("Done!") # - # When we again check the traffic per variant, this time we see that the number of invocations only incremented for Variant2, because all invocations were targeted at that variant: time.sleep(60) # give metrics time to catch up plot_endpoint_metrics() # ### Evaluating Variant2 # + # Calculate accuracy accuracy2 = sum(preds2 == labels) / len(labels) print(f'Accuracy: {accuracy2}') # Calculate precision precision2 = sum(preds2[preds2 == 1] == labels[preds2 == 1]) / len(preds2[preds2 == 1]) print(f'Precision: {precision2}') # Calculate recall recall2 = sum(preds2[preds2 == 1] == labels[preds2 == 1]) / len(labels[labels == 1]) print(f'Recall: {recall2}') # Calculate F1 score f1_score2 = 2 * (precision2 * recall2) / (precision2 + recall2) print(f'F1 Score: {f1_score2}') auc2 = round(roc_auc_score(labels, preds2), 4) print('AUC is ' + repr(auc2)) fpr2, tpr2, _ = metrics.roc_curve(labels, preds2) plt.title('ROC Curve') plt.plot(fpr2, tpr2, 'b', label='AUC = %0.2f'% auc2) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'r--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() # - # We see that Variant2 is performing better for most of our defined metrics, so this is the one weโ€™re likely to choose to dial up in production. # ## Step 4: Dialing up our chosen variant in production # # Now that we have determined Variant2 to be better as compared to Variant1, we will shift more traffic to it. # # We can continue to use TargetVariant to continue invoking a chosen variant. A simpler approach is to update the weights assigned to each variant using UpdateEndpointWeightsAndCapacities. This changes the traffic distribution to your production variants without requiring updates to your endpoint. # # Recall our variant weights are as follows: { variant["VariantName"]: variant["CurrentWeight"] for variant in sm.describe_endpoint(EndpointName=endpoint_name)["ProductionVariants"] } # We'll first write a method to easily invoke our endpoint (a copy of what we had been previously doing): def invoke_endpoint_for_two_minutes(): with open('test_data/test-dataset-input-cols.csv', 'r') as f: for row in f: print(".", end="", flush=True) payload = row.rstrip('\n') response = sm_runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType='text/csv', Body=payload) response['Body'].read() time.sleep(1) # We invoke our endpoint for a bit, to show the even split in invocations: invocation_start_time = datetime.now() invoke_endpoint_for_two_minutes() time.sleep(20) # give metrics time to catch up plot_endpoint_metrics(invocation_start_time) # Now let us shift 75% of the traffic to Variant2 by assigning new weights to each variant using UpdateEndpointWeightsAndCapacities. Amazon SageMaker will now send 75% of the inference requests to Variant2 and remaining 25% of requests to Variant1. sm.update_endpoint_weights_and_capacities( EndpointName=endpoint_name, DesiredWeightsAndCapacities=[ { "DesiredWeight": 25, "VariantName": variant1["VariantName"] }, { "DesiredWeight": 75, "VariantName": variant2["VariantName"] } ] ) # + print("Waiting for update to complete") while True: status = sm.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"] if status in ["InService", "Failed"]: print("Done") break print(".", end="", flush=True) time.sleep(1) { variant["VariantName"]: variant["CurrentWeight"] for variant in sm.describe_endpoint(EndpointName=endpoint_name)["ProductionVariants"] } # - # Now let's check how that has impacted invocation metrics: invoke_endpoint_for_two_minutes() time.sleep(20) # give metrics time to catch up plot_endpoint_metrics(invocation_start_time) # We can continue to monitor our metrics and when we're satisfied with a variant's performance, we can route 100% of the traffic over the variant. We used UpdateEndpointWeightsAndCapacities to update the traffic assignments for the variants. The weight for Variant1 is set to 0 and the weight for Variant2 is set to 1. Therefore, Amazon SageMaker will send 100% of all inference requests to Variant2. # + sm.update_endpoint_weights_and_capacities( EndpointName=endpoint_name, DesiredWeightsAndCapacities=[ { "DesiredWeight": 0, "VariantName": variant1["VariantName"] }, { "DesiredWeight": 1, "VariantName": variant2["VariantName"] } ] ) print("Waiting for update to complete") while True: status = sm.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"] if status in ["InService", "Failed"]: print("Done") break print(".", end="", flush=True) time.sleep(1) { variant["VariantName"]: variant["CurrentWeight"] for variant in sm.describe_endpoint(EndpointName=endpoint_name)["ProductionVariants"] } # - invoke_endpoint_for_two_minutes() time.sleep(20) # give metrics time to catch up plot_endpoint_metrics(invocation_start_time) # The Amazon CloudWatch metrics for the total invocations for each variant below shows us that all inference requests are being processed by Variant2 and there are no inference requests processed by Variant1. # # You can now safely update your endpoint and delete Variant1 from your endpoint. You can also continue testing new models in production by adding new variants to your endpoint and following steps 2 - 4. # ## Delete the endpoint # # If you do not plan to use this endpoint further, you should delete the endpoint to avoid incurring additional charges. # + #sm_session.delete_endpoint(endpoint_name)
09_deploy/wip/model-ab-blog/a_b_testing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] papermill={} tags=[] # <img width="10%" alt="Naas" src="https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160"/> # + [markdown] papermill={} tags=[] # # Github - Download file from url # <a href="https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/Github/Github_Download_file_from_url.ipynb" target="_parent"><img src="https://img.shields.io/badge/-Open%20in%20Naas-success?labelColor=000000&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTAyNHB4IiBoZWlnaHQ9IjEwMjRweCIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIj4KIDwhLS0gR2VuZXJhdGVkIGJ5IFBpeGVsbWF0b3IgUHJvIDIuMC41IC0tPgogPGRlZnM+CiAgPHRleHQgaWQ<KEY>> # + [markdown] papermill={} tags=[] # **Tags:** #github #productivity #code # + [markdown] papermill={} tags=[] # ## Input # + [markdown] papermill={} tags=[] # ### Import needed library # + papermill={} tags=[] import requests import naas import uuid # + [markdown] papermill={} tags=[] # ## Model # + [markdown] papermill={} tags=[] # ### Default Github file for testing purpose # + papermill={} tags=["parameters"] target = "https://github.com/jupyter-naas/awesome-notebooks/blob/master/Plotly/Create%20Candlestick%20chart.ipynb" # + [markdown] papermill={} tags=[] # ### Convert url to downloadable one # + papermill={} tags=[] # https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/Dataviz/Plotly/Create%20Candlestick%20chart.ipynb raw_target = target.replace("https://github.com/", "https://raw.githubusercontent.com/") raw_target = raw_target.replace("/blob/", "/") print(raw_target) # + [markdown] papermill={} tags=[] # ## Output # + [markdown] papermill={} tags=[] # ### Dowload file locally # + papermill={} tags=[] import urllib.parse r = requests.get(raw_target) uid = uuid.uuid4().hex file_name = raw_target.split('/')[-1] file_name = urllib.parse.unquote(file_name) with open(file_name, 'wb') as f: f.write(r.content)
Github/Github_Download_file_from_url.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # The Home Advantage: An investigation into the extent of crowd support on Premier league results. # It is widely accepted in the sporting world that the home team tends to benefit from certain advantages. Generally, these factors include crowd support, travel fatigue, tactics, venue familiarity, referee bias and psychological factors. (Fothergill et al. 2012 & Pollard, 1986). Under normal conditions, it is difficult to quantify the impact of each of these variables as many of them interact with each other and typically controlling for them in an authentic environment is not possible (Leite, 2017). The 2019/2020 football season is one of the few exceptions. Due to COVID pandemic, the season was first suspended and then resumed under preconditions with one of the biggest changes being that all games were played behind closed doors without a crowd. # # There is a consensus in previous studies on the home advantage in football that crowd support is a contributing factor (Reade, 2009; Pollard, 2008; Fothergill et all, 2012; Leite, 2017; Boyko, 2007). Whilst there seems to be a consensus that the crowd is a contributing factor on teams having an advantage playing at home the specific reason for this phenomenon is unclear (Leite, 2017; Pollard, 2008). However, one area with a body of work with statistically significant results is the impact of bias crowd support on referring decisions (Pollard, 2008; Fothergill et al., 2012, Boyko, 2007). Pollard (2008) went as far to state that, "There is now overwhelming evidence that referee decisions favour the home team. . . The reason for apparent referee bias is thought to be a consequence of crowd support". Whilst it is clear that the academia agrees that crowd support has a wider impact on the home advantage the only area there is considerable proof of the matter is the impact of crowd bias on referring decisions. # # Furthermore, another consideration that needs to be considered is the psychological impact of the idea of home advantage on teams. Fothergill et al. (2012) comment on a study on focus groups of players, referees and fans perceived as the significant factors contributing to the home advantage in which the three groups believed that the most significant of these was crowd support and familiarity to the environment. This suggests that even if statistically speaking there is no indication that these factors do have a significant impact on home advantage, there could be psychological factors impacting on a teamโ€™s home advantage due to the perception that factors such as crowd support are influencing the game. # # The consensus of previous studies is that apart from the impact of crowd support of referee bias there is a common belief that crowd support does influence the home advantage but a lack of consensus on the mechanisms crowd support influences (i.e., players performance) and how much of an influence crowd support has on games generally. # # This investigation will therefore use the unique opportunity of being able to analyse a body of games without crowds to try and provide further insight into if and how much crowds impact games. The hypothesis is that based on current understanding a key component to a teamโ€™s home advantage is the home team having the support of the majority of the fans. If this is the case, when fans are not present then there should be some kind of quantifiable decrease in that advantage. Therefore, the average point total for teams playing at home should drop whilst the average point total for the away team should increase. # # The main variables that will be considered in this investigation are points gained at home compared with points gained playing away. This metric of measurement was chosen over comparing home wins against away wins as this approach does not include draws. The methodology for this investigation is to first to analyse the results from 14 seasons of the Premier league from 2006/07 to 2019/2020 and establish the average baseline of points gained at home and away. Then I will investigate the 2019/2020 season in further depth and control for the games that were played with and without a crowd to try and understand if there is a statistically significant variation in the games played without a crowd. # # ## Premier League Data # My original plan was to scrape the fixture results from the official premier league website. Whilst this method would have been a completely valid route for my data collection, after doing some further research I discovered there was already an abundance of CSV sources readily available to download that contained the data I required in an ideal format for dealing with quantitative values. # # At the stage of collecting my data, I knew at a minimum I needed the data to included, at the minimum at least a decade worth of data which included identifiers for the season, home goals scored, and away goals scored. Furthermore, I required the 2019/2020 season to show the dates when the games were played so I could differentiate between the games that were played pre- and post-lockdown. # # In the end, I settled on three separate data files from open sources. The first having a breakdown of each season from 2006/2007 - 2017/18 sourced from https://www.kaggle.com/zaeemnalla/premier-league, the second covering the season 2018/2019 and the final data set covering the season 2019/2020 with those data files sourced from https://fixturedownload.com/sport/football. The data was cross-checked with the data provided by the official premier league website https://www.premierleague.com/results. Whilst there was more comprehensive data available which included far more variables on each Premier League season as the focus of my research was focusing on the home advantage the main data requirements needed was a data set that contained the results for each fixture whilst indicating what result belonged to the home and away team. The data sets I opted for provides this information in a format that can be manipulated to derive further information if required. # # To streamline my work later on I decided the first task required was to merge all the data into a single DataFrame. However, before I carried the task out, I need to clean the data and ensure that all the CSV files were consistently formatted. # # # + import pandas as pd #imported the csv files that I have uploaded to Jupyter Notebooks df1 = pd.read_csv('epl_res_06-18.csv') df2 = pd.read_csv('epl_19.csv') data_19_20 = pd.read_csv('epl_res_19:20.csv') # + # I decided that I would more than likely would want to alter how many columns or rows were visible at any time pd.set_option('display.max_rows', 2000) # can increase/decrease the max visible rows outputted pd.set_option('display.max_columns', 1000) # can increase/decrease the max visible rows outputted # + # I then checked how the data looked in the output. #df1 #df2 #data_19_20 # - # When I initially looked at my data, I noticed that 2 of the DataFrames (df2 and data_19_20) had the same variable names for the home and away team column so, I changed the corresponding variable names in df1 to match. I also decided on setting my index to the season column. # + # Changes the names of two columns so they match the corresponding varaible name in the other dataframe. df1.rename(columns={'home_team': 'Home Team', 'away_team': 'Away Team'}, inplace=True) # Sets the index as the season column df1.set_index('season', inplace=True) # + # Checked the output of the df1 DataFrame #df1 # - # Once the df1 DataFrame was formatted, I began manipulating the df2 DataFrame to mirror the formatting of df1. # + # Splits the result column into home goals and away goals df2[['home_goals','Null','away_goals']] = df2.Result.str.split(expand=True) # Removes the columns that are no longer required df2.drop(['Round Number', 'Location','Null', 'Result', 'Date'], axis=1, inplace=True) #creates a new colum and assigns values to that column df2.loc[:, 'Season'] = '2018-2019' #Sets the index as the season column df2.set_index('Season', inplace=True) #creates a new column with the function defining the result based on goals scored def fun(result): if result['home_goals']>result['away_goals']: return 'H' elif result['home_goals']<result['away_goals']: return 'A' else : return 'D' df2['result'] = df2.apply(fun, axis=1) # + # Checked the output of the df2 DataFrame # df2 # - # With the data_19_20 DataFrame, I realised that I needed to ensure that the season column captured the pre lockdown and post lockdown games. As the season was suspended on the 12th of March any game after that will be split into the post lockdown group. I implemented the following code which replaced to located and replace games played pre and post lockdown with identifiable names. # + data_19_20.loc[0:288, 'Date'] = "2019 - 2020 P1" # Updates the values of the data column to show all games pre-lockdown data_19_20.loc[288:, 'Date'] = "2019 - 2020 P2" # Updates the values of the data column to show all games post-lockdown data_19_20.rename(columns={'Date': 'season'}, inplace=True) # Renames the 'Date' column as season # - # I then applied similiar methods to this DataFrame to the methods used on the df2 DataFrame. # + # Splits the result column into home goals and away goals data_19_20[['home_goals','Null','away_goals']] = data_19_20.Result.str.split(expand=True) # Removes the columns that are no longer required data_19_20.drop(['Round Number', 'Location','Null', 'Result'], axis=1, inplace=True) #Sets the index as the season column data_19_20.set_index('season', inplace=True) #creates a new column with the functioning defining the result based on goals scored def fun(result): if result['home_goals']>result['away_goals']: return 'H' elif result['home_goals']<result['away_goals']: return 'A' else : return 'D' data_19_20['result'] = data_19_20.apply(fun, axis=1) # - # Checked the output of the df3 DataFrame data_19_20 # Now that all the DataFrames have been formatted I concatenated them into a single DataFrame 'data_master'. # Concatenates the three dataframes into a single dataframe with the variable name data_master data_master = pd.concat([df1,df2,data_19_20], axis=0) # The below functions are implemented to create two new columns that contain the home points and away points gained in each match. # + # Functions populate two new columns with points earned at home and points earned away def fun(homepoints): if homepoints['home_goals']>homepoints['away_goals']: return 3 elif homepoints['home_goals']<homepoints['away_goals']: return 0 else : return 1 data_master['home_points'] = data_master.apply(fun, axis=1) # Applys function to DataFrame in a new column def fun(awaypoints): if awaypoints['home_goals']>awaypoints['away_goals']: return 0 elif awaypoints['home_goals']<awaypoints['away_goals']: return 3 else : return 1 data_master['away_points'] = data_master.apply(fun, axis=1) # Applys function to DataFrame in a new column # - # Checked the output of the data_master DataFrame data_master # Although I need the data_19_20 DataFrame to differentiate between the pre and post lockdown games for the 2019/20 season, this is not required for the data_master dataframe and would in fact create make the seasononal data analysis more complicated. # + data_master.reset_index(inplace=True) data_master['index'] = data_master['index'].replace(["2019 - 2020 P1","2019 - 2020 P2"], "2019-2020") #Sets the index as the season column data_master.set_index('index', inplace=True) # - # After checking the data types of the columns using the .dtypes method, i noticed that the 'home_goals and 'away_goals' were objects. As I would like to carry out some quantatitive analysis on this data further down the line I altered the data type of this columns so that they became integers. # + data_master['home_goals'] = data_master['home_goals'].astype(int) #Changes datatype from object to integer data_master['away_goals'] = data_master['away_goals'].astype(int) #Changes datatype from object to integer data_master.dtypes # Checks the data types within the dataframe # - # So that I am able to conduct my analysis on points gained at home compard to points gained away from home, I applied the homepoints and awaypoints function to the data_19_20_master DataFrame. # + data_19_20_master = data_19_20 def fun(homepoints): if homepoints['home_goals']>homepoints['away_goals']: return 3 elif homepoints['home_goals']<homepoints['away_goals']: return 0 else : return 1 data_19_20_master['home_points'] = data_19_20_master.apply(fun, axis=1) # Applys function to DataFrame in a new column def fun(awaypoints): if awaypoints['home_goals']>awaypoints['away_goals']: return 0 elif awaypoints['home_goals']<awaypoints['away_goals']: return 3 else : return 1 data_19_20_master['away_points'] = data_19_20_master.apply(fun, axis=1) # Applys function to DataFrame in a new column # + # Checked the output of the data_19_20_master DataFrame #data_19_20_master # - # ## Analysis # Now that the initial datasets have been wrangled into the format required it is ready to be analysed. I wanted to get an overview of the totals for each of the variables by season. I decided that the best way to approach this was to create a new DataFrame from the data_master DataFrame that totalled the variables by season. # + # Creates a table that summarises the column values by season #Creates new variables that totals the information points_by_season = data_master.groupby(level=[0]).agg({'home_points': 'sum', 'away_points': 'sum'}) season_count = data_master.groupby(level=[0]).result.count().rename('Matches Played').to_frame() goals_by_season = data_master.groupby(level=[0]).agg({'home_goals': 'sum', 'away_goals': 'sum'}) season_results = pd.crosstab(data_master.index, data_master.result).rename( columns={'H': 'Home Wins', 'D': 'Draws', 'A': 'Away Wins'}) season_results.index.name = None # Creates a new DataFrame with the aggregated totals seas_tot_df = pd.concat([season_count, season_results, points_by_season, goals_by_season], axis=1) \ .rename(columns={'home_points': 'Home Points', 'away_points': 'Away Points', 'home_goals': 'Home Goals', 'away_goals': 'Away Goals',}) # - # Checks the output of the agg_df DataFrame seas_tot_df # Now that seas_tot_df DataFrame contained the summed totals for each varaible by season, I created two new varaibles which summed the total points and total goals by season. # Creates a total points and total goals by season column seas_tot_df['Total Points'] = seas_tot_df['Home Points']+seas_tot_df['Away Points'] seas_tot_df['Total Goals'] = seas_tot_df['Home Goals']+seas_tot_df['Away Goals'] # I then created percentage variables for each season using the necessary data from the seas_tot_df dataframe. # Creates percentage columns for wins and points seas_tot_df['Home Win %'] = round((seas_tot_df['Home Wins']/seas_tot_df['Matches Played']*100),3,) seas_tot_df['Away Win %'] = round((seas_tot_df['Away Wins']/seas_tot_df['Matches Played']*100),3,) seas_tot_df['Home Points %'] = round((seas_tot_df['Home Points']/seas_tot_df['Total Points']*100),3,) seas_tot_df['Away Points %'] = round((seas_tot_df['Away Points']/seas_tot_df['Total Points']*100),3,) seas_tot_df['Home Goals %'] = round((seas_tot_df['Home Goals']/seas_tot_df['Total Goals']*100),3,) seas_tot_df['Away Goals %'] = round((seas_tot_df['Away Goals']/seas_tot_df['Total Goals']*100),3,) # Checks the output of the agg_df DataFrame seas_tot_df # To get a broad statistical overview I applied the .describe method. This method will output useful statistics such as the mean and deviation for each of my variables. seas_tot_df.describe() # As expected, the analysis shows that the home team enjoys a significant advantage over the way team with an average margin of 19%. However, the initial analysis of the data shows that statistically speaking, the 2019/2020 season as a whole does not show a marginal difference in the points gained at home or away. Whilst the accumulated home point percentage of 58.015% is slightly below the average of 59.529% is well within the deviation of 59.529%ยฑ2.386%. The difference in away points accumulated similar when compared to the average with the 19/20 season totalling 41.985% and the average with deviation totalling 40.471%ยฑ2.386%. When you compare the 19/20 season to the preceding 18/19 season there is less home advantage in that season. To further reinforce this point the 19/20 season is near identical in the percentage of points gained in home and away games as the 11/12, 13,14 and 14/15 seasons. The graph below shows home points and away points by season with lines that average of those variables across all 14 seasons. # + from matplotlib import pyplot as plt import numpy as np #print(plt.style.available) # Shows available visualisation styles you can use plt.style.use("fivethirtyeight") # Selects the style # Creates a bar chart with the columns Home Points and Away Points chart_1 = seas_tot_df[['Home Points %','Away Points %']].plot(kind='bar', title =" Home Points v Away Points", figsize=(13, 10), legend=True, fontsize=12) # Sets the x-axis label and the y-axis label chart_1.set_xlabel("Season", fontsize=14) chart_1.set_ylabel("Percentage of Points", fontsize=14) # Adds line for the Home and Away mean chart_1.axhline(np.mean(seas_tot_df["Away Points %"]), color="yellow", linewidth= 2, label='Away Average (mean)') chart_1.axhline(np.mean(seas_tot_df["Home Points %"]), color="magenta", linewidth= 2, label='Home Average (mean)') #Adds labels to the legend and augments its fontsize plt.legend(fontsize=10) plt.grid(True) # Adds a grid plt.tight_layout() plt.show() # Outputs the graph # - # Whilst it may be the case that there seems to be no home advantage when looking at the 19/20 season as a whole, further analysis of the 19/10 may suggest otherwise. As 74% of the games in the 19/20 season was played under 'normal conditions' in that there was crowd support, looking at the season as a whole may skew the analysis. The next step creates a data frame that summarises the same variables as the data_master data frame but for the data_19_20_master that contains the data for the 19/20 season. # + # Creates a table that summarises the column values by season data_19_20_master['home_goals'] = data_19_20_master['home_goals'].astype(int) #Changes datatype from object to integer data_19_20_master['away_goals'] = data_19_20_master['away_goals'].astype(int) #Changes datatype from object to integer #Creates new variables that totals the information points_by_season = data_19_20_master.groupby(level=[0]).agg({'home_points': 'sum', 'away_points': 'sum'}) season_count =data_19_20_master.groupby(level=[0]).result.count().rename('Matches Played').to_frame() goals_by_season = data_19_20_master.groupby(level=[0]).agg({'home_goals': 'sum', 'away_goals': 'sum'}) season_results = pd.crosstab(data_19_20_master.index, data_19_20_master.result).rename( columns={'H': 'Home Wins', 'D': 'Draws', 'A': 'Away Wins'}) season_results.index.name = None # Creates a new DataFrame with the aggregated totals season_19_20_agg = pd.concat([season_count, season_results, points_by_season, goals_by_season], axis=1) \ .rename(columns={'home_points': 'Home Points', 'away_points': 'Away Points', 'home_goals': 'Home Goals', 'away_goals': 'Away Goals'}) # Creates a total points and total goals by season column season_19_20_agg['Total Points'] = season_19_20_agg['Home Points']+season_19_20_agg['Away Points'] season_19_20_agg['Total Goals'] = season_19_20_agg['Home Goals']+season_19_20_agg['Away Goals'] # Creates percentage columns for wins and points to 3 decimal places season_19_20_agg['Home Win %'] = round((season_19_20_agg['Home Wins']/season_19_20_agg['Matches Played']*100),3,) season_19_20_agg['Away Win %'] = round((season_19_20_agg['Away Wins']/season_19_20_agg['Matches Played']*100),3,) season_19_20_agg['Home Points %'] = round((season_19_20_agg['Home Points']/season_19_20_agg['Total Points']*100),3,) season_19_20_agg['Away Points %'] = round((season_19_20_agg['Away Points']/season_19_20_agg['Total Points']*100),3,) season_19_20_agg['Home Goals %'] = round((season_19_20_agg['Home Goals']/season_19_20_agg['Total Goals']*100),3,) season_19_20_agg['Away Goals %'] = round((season_19_20_agg['Away Goals']/season_19_20_agg['Total Goals']*100),3,) # - # Checks the output of the season_19_20_agg DataFrame season_19_20_agg season_19_20_agg.describe() # The chart below visualises the home and away points gained in the pre-lockdown part of the season with those gained in the post-lockdown part of the season. It also highlights the averages for both those variables for the seasons in the other data set. # + plt.style.use("fivethirtyeight") # Selects the style # Creates a bar chart with the columns Home Points and Away Points chart_2 = season_19_20_agg[['Home Points %','Away Points %']].plot(kind='bar', title ="With Crowd v Without Crowd", figsize=(10, 8), legend=True, fontsize=12) # Sets the x-axis label and the y-axis label chart_2.set_xlabel("Season", fontsize=14) chart_2.set_ylabel("Percentage of Points", fontsize=14) # Adds line for the Home and Away mean chart_2.axhline(np.mean(season_19_20_agg["Away Points %"]), color="yellow", linewidth= 2, label='Away Average (mean)') chart_2.axhline(np.mean(season_19_20_agg["Home Points %"]), color="magenta", linewidth= 2, label='Home Average (mean)') #Adds labels to the legend and augments its fontsize plt.legend(fontsize=10) plt.grid(True) # Adds a grid plt.tight_layout() plt.show() # Outputs the graph # - # ## Discussion # Further analysis of 2019-2020 season indicates that no statistically significant difference existed between home and away points gained when crowds were present compared to when they were not. Analysis of the seasons from 2006 โ€“ 2019 found, that the average home points were 59.529%ยฑ2.386% and the average away points 40.471%ยฑ2.386%. Both averages of 2019-2020 when controlled for crowd support are not significantly different from those averages. The average home points for home teams playing with a crowd in 2019 โ€“ 2020 was 57.955% and the average home points gained without a crowd was 58.203%. Furthermore, a similar inference can be made regarding the away points. The average away points for away teams playing with a crowd in 2019 โ€“ 2020 was 42.045% and the average away points gained without a crowd was 41.797%. The data and the analysis done in this study contradict the original hypothesis. The hypothesis stated that a key component to a teamโ€™s home advantage is the home team having the support of the majority of the fans. However, the statistical analysis suggests that this may not be the case as there is no significant differenct in points gained # by home teams when fans are present compared to when they are not. # # Apart from the COVID pandemic, the 2019 โ€“ 2020 season had another significant difference to the preceding seasons in the data set, the introduction of the virtual assistant referee (VAR). The introduction of VAR was to ensure that any clear and obvious errors by the officials such as red cards, penalties, and disallowed goals were reviewed to ensure the correct decision had been made. As a wealth of previous studies (Pollard, 2008; Fothergill et al., 2012, Boyko, 2007 suggest one of the measurable effects of crowd support has on the home advantage is its effect on referees. As the major decisions listed above are now reviewed by VAR it is plausible that this in itself has already impacted on the advantage (if any) of crowd bias. # # Another caveat in this approach is that it is not specifically controlled for team strength. Whilst over the course of a full season this is not as big of an issue as team strength will balance out it may skew the figures when comparing to parts of season especially as the two sections of the 19/20 season are skewed heavily in favour in the games that were played with crowds (74% with crowds and 26% without). Whilst there may not be a significant change in the results if team strength was controlled for it is worth noting that it is possible. # # A potential issue in this analysis is the relatively small dataset used for the control variable of the crowd. As there were only 92 games without a crowd in the 2019/2020 season there is a possibility the result of this statistical analysis will differ if the data set included a larger number of games in the controlled environment. However, A study looking to find if the absence of crowds had any effect on performance and referring decisions in the 2019/2020 season concurs with these findings concluding "that the absence of a partisan home crowd has no effect on the final match scoreline." (Bryson et al.) This study was broader in its scope, looking at games across 17 different countries with 1,498 of the games studied did not have any crowd. This suggests that the dataset used may not be that much of an issue in this approach. # ## Conclusion # A general assumption from a literary of previous studies assumed that a significant factor contributing to a team enjoying a home advantage is the contribution of a biased crowd (Reade, 2009; Pollard, 2008; Fothergill et all, 2012; Leite, 2017; Boyko, 2007). However, in these studies, much of the evidence to support that this was the case was essentially presumptuous due to lack of available data that controlled for crowd bias. This study has shown that there is not a statistically significant difference in results when teams play with a crowd or when they play without. This suggests that whilst crowd support may contribute to the home advantage when in combination with other factors, crowd support as a sole factor does not. # # As previously discussed, the results from this study concur with the results of Brysonโ€™s recent study across leagues in 17 countries. They found that there was no statistical evidence to suggest that the lack of crowd support had any negative impact on the home teamโ€™s points percentage and no positive impact on the away teams point percentage. Both this study and Brysonโ€™s concur that crowd support might not be as significant as once thought in given teams an advantage when playing at home. # # Whilst this could be the case, possible caveats in this approach such as the quantity of data available, the introduction of VAR and controlling for team strength. As these factors themselves have the potential to have an impact on the home advantage they may have weakened the reliability of the conclusions from the analysis. # ## Further Work # There is a myriad of different ways that further work could be conducted in this topic area. As mentioned previously the number of games played without a crowd used in this study is 92. A good next step would be to incorporate data from the 20/21 premier league season as a vast majority of the games played are being played without a crowd. With a larger dataset available more reliable statistical inferences would be possible. # # Also, in further studies, I would develop stronger methods to control for other possible factors such as team strength. By implementing a method that controls for team strength, the results from any further work should have a higher level of accuracy. Any further work that I conducted would include a model for controlling team strength that, if successful, would nullify one major caveat to the results. # # The study by Bryson showed that across the leagues their study looked at that they found that there was a one-third reduction in the away teamโ€™s yellow cards when they were playing without a crowd. One interesting route to explore would be to study referee actions in games played in front of a crowd compared to when they play without a crowd and see if there is a significant difference in actions taken that would favour the home team. As VAR has now been introduced decisions for such actions as offsides would be irrelevant but the number of freekicks and yellow cards could be variables of interest. This route could be further explored by not just trying to infer the impact of crowd support on referee bias but on other factors that possibly contribute to the home advantage. # ## Bibliography # In addition to the below references I have also utilised the supporting documentation for various packages. # # <NAME>., <NAME>. and <NAME>., 2007. Referee bias contributes to home advantage in English Premiership football.ย Journal of Sports Sciences, 25(11), pp.1185-1194. # # <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>., 2020. Experimental effects of an absent crowd on performances and refereeing decisions during Covid-19.ย SSRN Electronic Journal,. # # <NAME>., <NAME>., <NAME>. and <NAME>., 2012. Perspectives on the home advantage: A comparison of football players, fans and referees. Psychology of Sport and Exercise, [online] 13(3), pp.311-316. Available at: <https://www.researchgate.net/publication/257591792_Perspectives_on_the_home_advantage_A_comparison_of_football_players_fans_and_referees> [Accessed 1 January 2021]. # # <NAME>., 2017. Home Advantage: Comparison between the Major European Football Leagues. Athens Journal of Sports, 4(1), pp.65-74. # # # <NAME>., 1986. Home advantage in soccer: A retrospective analysis. Journal of Sports Sciences, [online] 4(3), pp.237-248. Available at: <https://www.researchgate.net/publication/20272586_Home_advantage_in_soccer_A_retrospective_analysis> [Accessed 1 January 2021]. # # <NAME>., 2008. Home Advantage in Football: A Current Review of an Unsolved Puzzle.ย The Open Sports Sciences Journal, [online] 1(1), pp.12-14. Available at: <https://www.researchgate.net/publication/228632270_Home_Advantage_in_Football_A_Current_Review_of_an_Unsolved_Puzzle> # # Aljazeera.com. 2021. English Premier League Set To Return After Coronavirus Break. [online] Available at: <https://www.aljazeera.com/sports/2020/6/17/english-premier-league-set-to-return-after-coronavirus-break> [Accessed 2 January 2021]. # # Fixturedownload.com. 2019. English Premier League 2018/19 Download Football/Soccer Fixtures, Schedules And Results As CSV, XLSX And ICS | Fixture Download. [online] Available at: <https://fixturedownload.com/sport/football> [Accessed 2 January 2021]. # # Fixturedownload.com. 2020. English Premier League 2019/20 Download Football/Soccer Fixtures, Schedules And Results As CSV, XLSX And ICS | Fixture Download. [online] Available at: <https://fixturedownload.com/sport/football> [Accessed 2 January 2021]. # # Kaggle.com. 2021. Premier League. [online] Available at: <https://www.kaggle.com/zaeemnalla/premier-league> [Accessed 2 January 2021]. # # Premierleague.com. 2021. Premier League Football Scores, Results & Season Archives. [online] Available at: <https://www.premierleague.com/results> [Accessed 3 January 2021]. # # Stack Overflow. 2021. User Sj293. [online] Available at: <https://stackoverflow.com/users/14860604/sj293> [Accessed 10 January 2021].
Premier_League_Home_Advantage.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import nltk import re # from nltk.tokenize import word_tokenize # from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords import spacy # from spacy.lang.fr.stop_words import STOP_WORDS nlp = spacy.load('fr_core_news_md') # nltk.download('wordnet') # nltk.download('punkt') # + stopwords = stopwords.words('french') stopwords.extend(['avoir', 'pouvoir', 'devoir']) def deEmojify(text): regrex_pattern = re.compile(pattern = "[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" u"\U00002500-\U00002BEF" u"\U00002702-\U000027B0" u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" u"\U0001f926-\U0001f937" u"\U00010000-\U0010ffff" u"\u2640-\u2642" u"\u2600-\u2B55" u"\u200d" u"\u23cf" u"\u23e9" u"\u231a" u"\ufe0f" u"\u3030" "]+", flags = re.UNICODE) return regrex_pattern.sub(r'', text) def preprocessing_final(tweet): # nlp = spacy.load('fr_core_news_md') # To lowercase punctuation = '!"$%&\'()*+,-./:;<=>?[\\]^_`{|}~โ€ข@' """function that also performs tokenization, lemmatization and removal of stopwords""" tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at tweet = re.sub(r'http\S+', '', tweet) # remove http links tweet = re.sub(r'bit.ly/\S+', '', tweet) # remove bitly links tweet = tweet.strip('[link]') # remove [links] tweet = re.sub(r'pic.twitter\S+','', tweet) tweet = re.sub('(#[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove hash tags tweet = tweet.lower() # lower case tweet = re.sub('[' + punctuation + ']+', ' ', tweet) # strip punctuation tweet = re.sub('\s+', ' ', tweet) # remove double spacing tweet = re.sub('([0-9]+)', '', tweet) # remove numbers tweet=deEmojify(tweet) # Creating a doc with spaCy doc = nlp(tweet) lemmas = [] for token in doc: if token.pos_ != "VERB": lemmas.append(token.lemma_) return " ".join([str(x) for x in lemmas if x.isalpha() and x not in stopwords]) # + # punctuation = '!"$%&\'()*+,-./:;<=>?[\\]^_`{|}~โ€ข@' # # stopwords= set(stopwords.words('french')) # def basic_clean(tweet): # """function to clean tweets only without tokenization or removal of stopwords""" # tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet # tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at # tweet = re.sub(r'http\S+', '', tweet) # remove http links # tweet = re.sub(r'bit.ly/\S+', '', tweet) # remove bitly links # tweet = tweet.strip('[link]') # remove [links] # tweet = re.sub(r'pic.twitter\S+','', tweet) # tweet = re.sub('(#[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove hash tags # tweet = tweet.lower() # lower case # tweet = re.sub('[' + punctuation + ']+', ' ', tweet) # strip punctuation # tweet = re.sub('\s+', ' ', tweet) # remove double spacing # tweet = re.sub('([0-9]+)', '', tweet) # remove numbers # tweet= deEmojify(tweet) # return tweet # def preprocess_tweet(tweet): # punctuation = '!"$%&\'()*+,-./:;<=>?[\\]^_`{|}~โ€ข@' # stopwords = stopwords.words('french') # """function that also performs tokenization, lemmatization and removal of stopwords""" # tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet # tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at # tweet = re.sub(r'http\S+', '', tweet) # remove http links # tweet = re.sub(r'bit.ly/\S+', '', tweet) # remove bitly links # tweet = tweet.strip('[link]') # remove [links] # tweet = re.sub(r'pic.twitter\S+','', tweet) # tweet = re.sub('(#[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove hash tags # tweet = tweet.lower() # lower case # tweet = re.sub('[' + punctuation + ']+', ' ', tweet) # strip punctuation # tweet = re.sub('\s+', ' ', tweet) # remove double spacing # tweet = re.sub('([0-9]+)', '', tweet) # remove numbers # tweet=deEmojify(tweet) # words = nltk.word_tokenize(tweet) # lemmatized = ' '.join([WordNetLemmatizer().lemmatize(w) for w in words if w not in stopwords]) # return lemmatized # + # def preprocessing_europresse(text): # stop_words = set(stopwords.words("french")) # sentences = nltk.sent_tokenize(text) # gives us a list of sentences # tokens=[] # for sentence in sentences: # loop over each sentence and tokenize it separately # words = nltk.word_tokenize(sentence) #gives a list of words per sentence # for word in words: # if word not in stop_words: # tokens.append(word.lower()) #append lowercase words if they are not stopwords # return " ".join([x for x in tokens if x.isalpha()]) #returns alphabetic characters, excluding stopwords, joined together # - # def preprocessing_tweet(tweet): # tokens=[] # words = nltk.word_tokenize(tweet) #givets a list of words per sentence # for word in words: # WordNetLemmatizer().lemmatize(word) # if word not in stop_words: # tokens.append(word.lower()) #append lowercase words if they are not stopwords # return " ".join([x for x in tokens if x.isalpha()]) #returns alphabetic characters, excluding stopwords, joined together # + # def preprocessing_spacy(tweet): # # To lowercase # tweet = tweet.lower() # # Creating a doc with spaCy # doc = nlp(tweet) # lemmas = [] # tokens = [] # for token in doc: # lemmas.append(token.lemma_) # for lemma in lemmas: # if lemma not in stopwords: # tokens.append(lemma) # return " ".join([str(x) for x in tokens if x.isalpha()]) # def preprocessing_spacy_stopwords(tweet): # # nlp = spacy.load('fr_core_news_md') # tweet= tweet.lower() # doc= nlp (tweet) # doc = [token.lemma_ for token in doc if token.lemma_ != '-PRON-'] # doc = [token.text for token in doc if token.is_stop == False and token.is_punct != True] # return " ".join([x for x in doc if x.isalpha()]) # + # from nltk.corpus import stopwords # punctuation = '!"$%&\'()*+,-./:;<=>?[\\]^_`{|}~โ€ข@' # stop_words = stopwords.words('french') # stop_words.extend(['demain', 'soir']) # def preprocess_tweet_extended_stopwords(tweet): # """function that also performs tokenization, lemmatization and removal of stopwords""" # tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet # tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at # tweet = re.sub(r'http\S+', '', tweet) # remove http links # tweet = re.sub(r'bit.ly/\S+', '', tweet) # remove bitly links # tweet = tweet.strip('[link]') # remove [links] # tweet = re.sub(r'pic.twitter\S+','', tweet) # tweet = re.sub('(#[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove hash tags # tweet = tweet.lower() # lower case # tweet = re.sub('[' + punctuation + ']+', ' ', tweet) # strip punctuation # tweet = re.sub('\s+', ' ', tweet) # remove double spacing # tweet = re.sub('([0-9]+)', '', tweet) # remove numbers # tweet=deEmojify(tweet) # words = nltk.word_tokenize(tweet) # lemmatized = ' '.join([WordNetLemmatizer().lemmatize(str(w)) for w in words if w not in stop_words]) # return lemmatized # -
preprocessing/preprocessing_tweets.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys sys.path.append('/home/cham/data/ToolFun/python/') from astropy.table import Table from spectrum import lamost_filepath,measure_line_index_null_result,measure_line_index from IPython.parallel import require catalogpath = '/pool/LAMOST/DR2/calalog/dr2_original/dr2c.fits' catalog = Table.read(catalogpath) filepath = [] for i in xrange(len(catalog)): filepath.append(lamost_filepath(\ catalog['planid'][i],\ catalog['mjd'][i],\ catalog['spid'][i],\ catalog['fiberid'][i])) from IPython.parallel import parallel,Client rc = Client() dview = rc[:] @dview.remote(block=True) def measure_line_index_loopfun_start(): import sys sys.path.append('/home/cham/data/ToolFun/python/') #from spectrum import measure_line_index_loopfun return sys.path #@require('measure_line_index') def measure_line_index_loopfun(filepath): num_refit = 100 line_info_dib5780 = {\ # 'line_center':5780,\ 'line_range':(5775,5785),\ 'line_shoulder_left':(5755,5775),\ 'line_shoulder_right':(5805,5825)} line_info_dib5797 = {\ # 'line_center':5797,\ 'line_range':(5792,5802),\ 'line_shoulder_left':(5755,5775),\ 'line_shoulder_right':(5805,5825)} line_info_dib6284 = {\ # 'line_center':6285,\ 'line_range':(6280,6290),\ 'line_shoulder_left':(6260,6280),\ 'line_shoulder_right':(6310,6330)} # try: # read spectrum +++++++++++++++++++++++++++++++++++++++++++++++++++ spec = read_spectrum(filepath,'lamost_dr2') # measure DIBs ++++++++++++++++++++++++++++++++++++++++++++++++++++ # DIB5780 line_indx_dib5780 = measure_line_index(\ wave=spec['wave'],\ flux=spec['flux'],\ flux_err=spec['flux_err'],\ mask=spec['and_mask'],\ line_info=line_info_dib5780,\ num_refit=num_refit,z=0,\ ) # DIB5797 line_indx_dib5797 = measure_line_index(\ wave=spec['wave'],\ flux=spec['flux'],\ flux_err=spec['flux_err'],\ mask=spec['and_mask'],\ line_info=line_info_dib5797,\ num_refit=num_refit,z=0,\ ) # DIB6284 line_indx_dib6284 = measure_line_index(\ wave=spec['wave'],\ flux=spec['flux'],\ flux_err=spec['flux_err'],\ mask=spec['and_mask'],\ line_info=line_info_dib6284,\ num_refit=num_refit,z=0,\ ) return line_indx_dib5780,line_indx_dib5797,line_indx_dib6284 dview['filepath[0]'] dview.scatter('filepath',filepath) results_async = dview.map_async(measure_line_index_loopfun,filepath[0:10]) results_async.get() # + dview.execute('sys.path.append(\'/home/cham/data/ToolFun/python\')').get() dview.execute('sys.path').get() results_async = dview.map_async(measure_line_index_loopfun,filepath[0]) results = results_async.get() # - results_async = dview.map_async(measure_line_index_loopfun,filepath[0]) results = results_async.get()
tutorial/test_measure_line_index.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Algoritmizace a programovรกnรญ 2 # ## Cv.9. Gitops # # * lorem # * lorem # * lorem # * lorem # ### 9.1 Lorem # ### 9.2 Lorem # ### 9.3 Lorem # ### 9.4 Lorem # ### Domรกcรญ cviฤenรญ # #### DCv.1 - Lorem # #### DCv.2 - Lorem # #### DCv.3 - Lorem # #### DCv.4 - Lorem # #### DCv.5 - Lorem
9_gitops.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Brain Tissue Classification # # ## Learning Objective # # The goal of this project is to demonstate that jupyter notebooks # is a powerful tool for quickly prototyping ideas. Jupyter notebooks allow for quick visualization # of both data and results in real time. The effects of preprocessubg # the data and tuning algorithm parameters can easily be observed. # # This notebook demonstrates the notebook features by segmenting brain regions # using machine learning on multi modal brain MRI images. However, the # the applications our endless. The focus should not be on machine learning, # but rather what jupyter notebooks are capable of doing. # # # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython # %load_ext autoreload # %autoreload 2 # + # Import Modules import itk itk.force_load() #Load everything at once, slow but maximizes introspection import glob import os import numpy as np import pandas as pd #pip install pandas from sklearn.naive_bayes import GaussianNB #pip install sklearn from sklearn.neighbors import KNeighborsClassifier from sklearn import svm from sklearn import tree #from sklearn.model_selection.cross_validation import cross_val_predict from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from matplotlib import pyplot as plt from matplotlib.ticker import NullFormatter from matplotlib import gridspec from itkwidgets import view from ipywidgets import interact, fixed from ipywidgets import interactive import ipywidgets as widgets # - # # Read Images # + # Image Filenames t1_fn = "t1_average_BRAINSABC.nii.gz" t2_fn = "t2_average_BRAINSABC.nii.gz" lbl_fn = "labels.nii.gz" # Read images t1_img = itk.imread(t1_fn) t2_img = itk.imread(t2_fn) lbl_img = itk.imread(lbl_fn) # Define labels LABELS = dict() LABELS["WM"] = [1] LABELS["GM"] = [2] LABELS["CSF"] = [4] # - # # Data Preprocessing # # It is almost always necessary to perform preprocessing on the data before using it. Here we will focus on two preprocessing methods. # # First, we will use smoothing filtes to reduce noise in the image. It is critical to find a good scale that balances the tradeoff between smoothing noise and loosing information. The notebook makes it easy to see the effects of different smoothing levels. # # Second, we will pick a sub sample of the image pixels to use for training a model. To do this we will erode the label map. The notebook allows us to see what radius to use for the erosion kernel, we don't want to completely erode a label! from medianhelper import MedianFilter ## See content from file medianhelper # Median widget helper median_instance = MedianFilter(t1_img) widgets.VBox([median_instance.viewer, median_instance.slider]) # + #help(itk.BinaryErodeImageFilter.New(lbl_img)) from erodehelper import ErodeLabels label_map = {'WM' : [1], 'GM' : [2], 'CSF' : [4], 'All' : [1,2,4]} # Erosion widget erode_instance = ErodeLabels(lbl_img) widgets.VBox([erode_instance.viewer, erode_instance.slider]) # - from plothelper import PlotClassDistribution LABELSDICT = {'WM': 1, 'GM':2, 'CSF':4} # 2D histogram widget plotter = PlotClassDistribution(t1_img, t2_img, lbl_img, LABELSDICT) interact(plotter.display, erode_radius=(erode_instance.min_radius, erode_instance.max_radius), median_radius=(median_instance.min_radius, median_instance.max_radius) ) # Based on the what your observations from the above widgets, preprocess the data to obtain a dataset that will be used to train a model for brain tissue classification. # + ############################ ####### FILL IN ############ ############################ # smooth image t1_img_smooth = t1_img t2_img_smooth = t2_img # erode label map lbl_img_erode = lbl_img ############################ # - # # Machine Learning from mlhelper import niave_gaussian_probabilities , knn_probabilities, dt_probabilities, plot_decision_boundary # ## Get Features Vectors from mlhelper import get_random_sample, get_accuracy # + from utilityfunctions import flatten_image # Flatten images to 1D numpy array t1_np1d = flatten_image(t1_img_smooth) t2_np1d = flatten_image(t2_img_smooth) lbl_np1d = flatten_image(lbl_img_erode) lbl_np1d_orig = flatten_image(lbl_img) # Take equal subsample from each class for training num=97 #NOTE: 97 is a relatively small number of samples choosen for speed. Try other values (i.e. 300, 4000, 100000) train, train_labels = get_random_sample(t1_np1d, t2_np1d, lbl_np1d,LABELSDICT,num) # Use entire image for testing test = np.column_stack((t1_np1d,t2_np1d)) # - # In the plots that follow, the blue regions indicate the high probability for that class, and the red regions indicate low probability for that class. # + def model_callback(model, models): """Plots the decision boundary for different classifiers Args: model : Key of dictionary corresponding to a model models (dict): dictionary of trained models class_labels (dict): a dictionary mapping class_labels to numerical values. """ plot_decision_boundary(models[model],train[:,0], train[:,1], train_labels, LABELSDICT) dt_probs, dt_model = dt_probabilities(test, train, train_labels) knn_probs, knn_model = knn_probabilities(test,train, train_labels, 5) nb_probs, nb_model = niave_gaussian_probabilities(test, train, train_labels) model_dict = {'knn':knn_model, 'naive_bayes':nb_model, 'decision_tree':dt_model} print("HERE: {0}".format(LABELSDICT)) interact(model_callback, model=['naive_bayes','decision_tree','knn'], models = fixed(model_dict)) # + # Predict using Decision Tree model dt_predict_train = dt_model.predict(train) dt_predict_test = dt_model.predict(test) dt_train_acc = get_accuracy(dt_predict_train, train_labels) dt_test_acc = get_accuracy(dt_predict_test, lbl_np1d_orig) # Predict using kNN model knn_predict_train = knn_model.predict(train) knn_predict_test = knn_model.predict(test) knn_train_acc = get_accuracy(knn_predict_train, train_labels) knn_test_acc = get_accuracy(knn_predict_test, lbl_np1d_orig) # Predict using Naive Bayes model nb_predict_train = nb_model.predict(train) nb_predict_test = nb_model.predict(test) nb_train_acc_train = get_accuracy(nb_predict_train, train_labels) nb_test_acc = get_accuracy(nb_predict_test, lbl_np1d_orig) # + # Plot results df = pd.DataFrame([[dt_train_acc,dt_test_acc], [knn_train_acc,knn_test_acc], [nb_train_acc_train, nb_test_acc]], index = ['dt','knn', 'nb'], columns = ['train','test']) df.plot(kind='bar',figsize=(8,5), fontsize=14) plt.ylabel("accuracy",fontsize=20) plt.xticks(rotation=45) plt.ylim([0.80,1.01]) plt.title("Accuracy for different Classification Models",fontsize=20) # + def knn_callback(k=1): """Plots the decision boundary for kNN classifer for different k Args: k (int): Number of neighbors for kNN classifer """ if k not in knn_pred_cache: all_probs, y_pred = knn_probabilities(test, train, train_labels, k) knn_pred_cache[k] = y_pred Z = knn_pred_cache[k] plot_decision_boundary(Z,train[:,0], train[:,1], train_labels, LABELSDICT) print('k = ' + str(k)) knn_pred_cache = dict() interact(knn_callback, k = (1,9,2)) # + def dt_callback(d=1): """Plots the decision boundary for kNN classifer for different k Args: k (int): Number of neighbors for kNN classifer """ if d not in dt_pred_cache: all_probs, y_pred = dt_probabilities(test, train, train_labels, d) dt_pred_cache[d] = y_pred Z = dt_pred_cache[d] plot_decision_boundary(Z,train[:,0], train[:,1], train_labels, LABELSDICT) print('d = ' + str(d)) dt_pred_cache = dict() interact(dt_callback, d = (1,9)) # - # Get accuracies for different k knn_accuracies = [] for k in range(1,10,2): if k not in knn_pred_cache: all_probs, model = knn_probabilities(test, train, train_labels, k) knn_pred_cache[k] = model pred = knn_pred_cache[k].predict(test) pred_train = knn_pred_cache[k].predict(train) accuracy = get_accuracy(pred, lbl_np1d_orig) accuracy_train = get_accuracy(pred_train, train_labels) knn_accuracies.append([accuracy_train,accuracy]) # Plot results knn_df = pd.DataFrame(knn_accuracies, index=['k=1','k=3','k=5','k=7','k=9'], columns = ['train','test']) knn_df.plot(kind='bar', figsize=(8,5), fontsize=14) #knn_df.plot(figsize=(8,5), fontsize=14) plt.ylim([0.80,1.01]) plt.ylabel("accuracy", fontsize=20) plt.xticks(rotation=45) plt.title("kNN Accuracy for different k",fontsize=20) # Get accuracies for different max tree depth dt_accuracies = [] for d in range(1,10): if d not in dt_pred_cache: all_probs, model = dt_probabilities(test, train, train_labels, d) dt_pred_cache[d] = model pred = dt_pred_cache[d].predict(test) pred_train = dt_pred_cache[d].predict(train) acc = get_accuracy(pred, lbl_np1d_orig) acc_train = get_accuracy(pred_train, train_labels) dt_accuracies.append([acc_train,acc]) # Plot results dt_df = pd.DataFrame(dt_accuracies,columns=['train','test'], index =range(1,10) ) dt_df.plot(figsize=(8,5), fontsize=14) plt.ylim([0.5,0.95]) plt.xlabel("tree depth", fontsize=20) plt.ylabel("accuracy",fontsize=20) plt.title("Accuracy for different tree depth",fontsize=20) # + #choose a model, train and predict all_probs, model = niave_gaussian_probabilities(test, train, train_labels) pred_test_np1d = model.predict(test) pred_train_np1d = model.predict(train) # set background prediction to zero pred_test_np1d[lbl_np1d_orig==0]=0 # - imsize=lbl_img.GetLargestPossibleRegion().GetSize() pred = pred_test_np1d.reshape((imsize[2], imsize[1], imsize[0])).astype(np.float32) pred_img = itk.GetImageFromArray(pred) pred_img.CopyInformation(lbl_img) pred_np1d = flatten_image(pred_img) cif = itk.CastImageFilter[pred_img, itk.Image[itk.UC,3]].New(Input=pred_img) pred_img= cif.GetOutput() # + # Calculate the accuracy of your model accuracy_test = get_accuracy(pred_test_np1d, lbl_np1d_orig) accuracy_train = get_accuracy(pred_train_np1d, train_labels) print(accuracy_test) print(accuracy_train) # + from scipy.stats import ttest_ind ttest_ind(pred_train_np1d, train_labels) # + #confusion matrix def show_confusion_matrix(prediction_np1d, labels_np1d): """Calculates confusion matrix for the trained classifier Args: prediction_np1d (np.array) : model prediction labels_np1d (np.array) : ground truth labels """ m = confusion_matrix(labels_np1d, prediction_np1d) # normalize each row m = m.astype('float')/m.sum(axis=1)[:,np.newaxis] # remove background labels m = m[1:,:] m = m[:,1:] fig = plt.figure() plt.imshow(m, interpolation='nearest', cmap = plt.cm.Reds) plt.colorbar() tick_marks = np.arange(3) plt.xticks(tick_marks, ['WM','GM','CSF'], rotation=45) plt.yticks(tick_marks, ['WM','GM','CSF']) plt.xlabel('Predicted Label') plt.ylabel('True Label') plt.show() show_confusion_matrix(pred_test_np1d, lbl_np1d_orig) # - # which model and why # any preprocessing? # training and testing accuracies #
hw/hw08-abpwrs/MIATT_INCLASS.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.5 64-bit (''sc_workshops'': conda)' # metadata: # interpreter: # hash: 787ea478c22349cf73d867deb0a19fc58e75e9742a9aed6f48d06cc412ad6e3b # name: python3 # --- # # Noise Field # # In this workshop, we will learn about creation of noise field, based on a set of noise sources. # ## 0. Initialization # # ### 0.1. Load required libraries import os import topogenesis as tg import pyvista as pv import trimesh as tm import numpy as np import scipy as sp # ### 0.2. Load the envelope lattice as the avialbility lattice # loading the lattice from csv lattice_path = os.path.relpath('../data/voxelized_envelope.csv') avail_lattice = tg.lattice_from_csv(lattice_path) init_avail_lattice = tg.to_lattice(np.copy(avail_lattice), avail_lattice) # ### 0.3. Load noise sources # loading program (agents information) from CSV noise_source_path = os.path.relpath('../data/noise_points.csv') noise_sources = np.genfromtxt(noise_source_path, delimiter=',') noise_sources # ### 0.4. Visualize noise source points # + p = pv.Plotter(notebook=True) # adding the avilability lattice init_avail_lattice.fast_vis(p) # adding axes p.add_axes() p.add_mesh(noise_sources, point_size=10) p.show(use_ipyvtk=True) # - # ## 1. Creation of Noise Field # # ### 1.1. Computing noise lattices # + tags=[] # create full lattice full_lattice = avail_lattice * 0 + 1 # extract the coordiantes of the centroid of all voxel vox_centroids = full_lattice.centroids # extract voxel indices of all voxels vox_indices = np.array(np.where(full_lattice==1)).T # setting the noise base pressure level noise_base = 75.0 # initializing the sum lattice of noise sum_noise_lats = avail_lattice * 0.0 # for each source of noise for noise_src in noise_sources: # initialize the occupation lattice dist_latice = avail_lattice * 0.0 for cen, ind in zip(vox_centroids, vox_indices): # compute the euclidian distance dist_latice[tuple(ind)] = sp.spatial.distance.euclidean(cen, noise_src) # computing the noise lattice from dist lattice noise_latice = noise_base - 20 * np.log10(dist_latice) - 8 # summing sum_noise_lats += np.power(10, noise_latice / 10.0) # computing the final aggregation agg_noise_lats = 10 * np.log10(sum_noise_lats) # - # ### 1.2. Visualizing the noise lattices # + # initiating the plotter p = pv.Plotter(notebook=True) vis_lattice = agg_noise_lats # Create the spatial reference grid = pv.UniformGrid() # Set the grid dimensions: shape because we want to inject our values grid.dimensions = vis_lattice.shape # The bottom left corner of the data set grid.origin = vis_lattice.minbound # These are the cell sizes along each axis grid.spacing = vis_lattice.unit # Add the data values to the cell data grid.point_arrays["Noise"] = vis_lattice.flatten(order="F") # Flatten the Lattice # adding the volume opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5 p.add_volume(grid, cmap="coolwarm" ,opacity=opacity, shade=True) # plotting p.show(use_ipyvtk=True) # - # ### Credits __author__ = "<NAME>" __license__ = "MIT" __version__ = "1.0" __url__ = "https://github.com/shervinazadi/spatial_computing_workshops" __summary__ = "Spatial Computing Design Studio Workshop on Noise Fields"
notebooks/w+6_noise_field.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Vacinaรงรฃo para a Covid-19 no Rio Grande do Norte # # ## Essa primeira seรงรฃo contรฉm somente uma rรกpida exploraรงรฃo dos dados baixados no site do ministรฉrio da saรบde # # # # Anรกlise dos dados para a vacinaรงรฃo da Covid-19 no estado do Rio Grande do Norte. O intuito de analisar este dataset foi procurar responder as seguintes perguntas: # # Quantas pessoas jรก estรฃo vacinadas com pelo menos 1 dose (D1)? # # Quantas pessoas jรก estรฃo completamente vacinadas (D1+D2)? # # O gรชneros (homem/mulher) que foram mais cobertos com a vacinaรงรฃo? # # A idade mรฉdia das pesoas que estรก completamente imunizada? # # Qual รฉ o perfil dos vacinados quanto a raรงa? # # Qual foi a vacina mais aplicada por fabricante? # # # # Link do arquivo csv: data do acesso: 12/08/2021 [Opendatasus](https://opendatasus.saude.gov.br/dataset/covid-19-vacinacao/resource/ef3bd0b8-b605-474b-9ae5-c97390c197a8) # + # # !pip install plotly --upgrade # + import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import plotly.express as px # - # ## Explorando os dados superficialmente # Carregando os dados do arquivo csv sobre a vacinaรงรฃo no Rio Grande do Norte data_vac = pd.read_csv('vacina_RN.csv', sep=';') # + # Vamos ver quantas linhas e colunas tem o nosso dataset data_vac.shape # - # As 5 primeiras linhas do arquivo data_vac.head() # Uma primeira dos dados acima mostra que: # # 1 - categorias entre 101 e 111 e de comorbidades # # 2 - categorias entre 201 e 205 foram a faixa etaria de pessoas de 80 anos ou mais # # 3- 301 e de Pessoas de 60 nos ou mais Institucionalizadas # # 4 - 401 ate 403 e forcas armadas # # 5 - 501 ate 207 sao os agentes de seguranca (bombeiros, guardas civil/militar, policia rodovi. ) # # 6 - 601 sao quilombolas # # 7 - 701 sao povos indigenas # # 8 - 801 e 802 ensino basico e ensino superior # # 9 - Trabalhadores da saude 901 ate 929 # 901: Auxiliar de Veterinรกrio # 902: Biรณlogo # 903: Biomรฉdico # 904: Cozinheiros e auxiliares # 905: cuidados de idoso # 906: doula/parteira # 907: enfermeiros # 908: Farmacรชutico # 909: Fisioterapeutas # 910: Fonoaudiรณlogo # 911: Funcionรกrio do Sistema Funerรกrio c/ cadรกveres # 912: Mรฉdico # 913: Mรฉdico Veterinรกrio # 914: Motorista de Ambulรขncia # 915: Nutricionista # 916: Odontologista # 917: Pessoal da Limpeza # 918: Profissionais de Educaรงรฃo Fรญsica # # 10 - 930 931 e 932 nao estao especificados # # 11 - 1001 ate 1006 sao trabalhadores de transportes # # 12 1101 e 1102 sao PCD # # 13 - 1201 Pessoas em Situaรงรฃo de Rua # # 14 - 1301 Trabalhadores Portuรกrios # # 15 - 1401 funcionarios do sistema prisional # # 16 - 1501 populacao carceraria # # Sao apenas algumas das categorias identificadas # Exibindo as cinco ultimas linhas do arquivo data_vac.tail(5) # + # Quantas pessoas acima de 60 anos foram vacinadas? 881000 data_vac[data_vac['paciente_idade'] >= 60] # - # Quantas pessoas com 40 anos ou menos foram vacinadas? data_vac[data_vac['paciente_idade'] <= 40] # 1283760 pessoas com 40 anos ou menos foram vacinadas. #quantas pessoas desse total nรฃo tem endereรงo no RN? data_vac[data_vac['paciente_endereco_uf'] != 'RN' ] # 125155 cujo endereรงo nรฃo รฉ do RN, se vacinaram aqui. Porรฉm, nรฃo temos como saber se de fato elas residem # no RN, ou estavam sรณ de passagem. Mas vamos assumir que elas moram aqui. # # Visualizando os dados # ### Analisando os dados quanto ao sexo. data_vac[data_vac['paciente_enumsexobiologico'] == 'I' ] data_vac[data_vac['paciente_enumsexobiologico'] == 'F' ] data_vac[data_vac['paciente_enumsexobiologico'] == 'M' ] # Podemos observar que apenas 7 linhas estรฃo especificadas como I que, de acordo com o dicionรกrio, nรฃo รฉ nem feminino e masculino. Podemos ainda assumir que elas sรฃo de alguns dos sexo F/M ou excluรญlas da anรกlise final, jรก que seu numero รฉ baixรญssimo se comparado a quantidade de dados no restante das linhas que somam mais de 2 mi. # # Alรฉm disso, 1817096 mulheres foram vacinadas e 1472439 homens foram vacinados, como indica o grรกfico abaixo. sns.countplot(x = data_vac['paciente_enumsexobiologico']); # Jรก podemos responder a umas das perguntas levantas **quanto ao gรชnero (homem/mulher) que foi mais cobertos com a vacinaรงรฃo?** A anรกlise preliminar mostra que mais mulheres foram vacinadas em comparaรงรฃo ao quantitativo de homens. # ### Podemos analisar o perfil quanto a raรงa dos vacinados # O dicionรกrio dos dados fornece: # # 1 - branca # # 2 - preta # # 3 - parda # # 4- amarela # # 5 - indigena # # 99- sem informaรงรฃo # + # contando os valores รบnicos que existem na coluna 'raรงa' # Esse grafico de contagem pode tanto ser feito a partir da coluna paciente_racacor_valor # quanto paciente_racacor_codigo np.unique(data_vac['paciente_racacor_codigo'], return_counts=True) # - plt.figure(figsize=(12, 8)) sns.countplot(x = data_vac['paciente_racacor_valor']); # A contagem mostra que, quanto a raรงa as pessoas se identificam em: # # 1 - brancos - 701542 pessoas vacinadas. # # 2 - preta - 95222 pessoas vacinadas. # # 3 - parda - 696203 pessoas vacinadas. # # 4 - amarela - 489281 pessoas vacinadas. # # 5 - indigena - 1015 vacinados # # 99 - sem informaรงรฃo - 385703 vacinados # # apenas um dado รฉ inconsistente. # # E com isso respondemos a mais uma pergunta sobre qual รฉ o **perfil dos vacinados quanto a raรงa**. # ### Nรบmeros quanto ao nรบmero de doses aplicadas # para responder as perguntas: # # Quantas pessoas jรก estรฃo vacinadas com pelo menos uma dose (D1)? temos que 1706098 tomaram pelo menos uma dose # # Quantas pessoas jรก estรฃo completamente vacinadas (D1+D2) ou dose รบnica? 609797 + 50966 + 2106 = 662869 estรฃo completamente imunizadas com duas doses ou uma doze รบnica # # O grรกfico abaixo nos mostra que o maior nรบmero de pessoas tomou apenas a primeira dose da vacina # + # As linhas abaixo sรฃo referentes a mesma vacina Vacina covid-19 - Ad26.COV2.S - Janssen-Cilag print(data_vac[data_vac['vacina_descricao_dose'] == 'Dose\xa0'].shape) print(data_vac[data_vac['vacina_descricao_dose'] == 'รšnica\xa0'].shape) # num dataframe transformado elas poderiam ser mescladas # - # contando os valores รบnicos que existem na coluna 'vacina_descricao_dose np.unique(data_vac['vacina_descricao_dose'], return_counts=True) sns.countplot(x = data_vac['vacina_descricao_dose']); # ### Quanto ao fabricante da vacina - Qual foi a vacina mais aplicada por fabricante? # # O dicionรกrio informa os seguintes cรณdigos # # 85 - Vacina covid-19 covishield - Astra/Zeneca - 1127963 doses # # 86 - Coronavac - Sinovac/Butantan - 846328 doses # # 87 - Vacina covid-19 BNT 162b2 - BioNthech/Pfizer - 846328 doses # # 88 - Vacina covid-19 - Ad26.COV2.S - Janssen-Cilag - 53988 doses # + # data_vac[data_vac['vacina_descricao_dose'] == 'Dose\xa0'][:2] # data_vac[data_vac['vacina_descricao_dose'] == 'รšnica\xa0'][:2] # - #quanto ao fabricante np.unique(data_vac['vacina_codigo'], return_counts=True) sns.countplot(x = data_vac['vacina_codigo']); # ## Tratando os valores inconsistentes #removendo colunas que nao sao de interesse #primeiro identificamos todas as colunas do nosso dataframe data_vac.columns # + # Apagando colunas que nao sao de interesse com o .drop # document_id, pacient_id, paciente_datanascimento, paciente (de todos os registros da base de dados) base_vacina2 = data_vac.drop(['document_id', 'paciente_id', 'paciente_datanascimento', 'paciente_racacor_valor', 'paciente_endereco_coibgemunicipio', 'paciente_endereco_copais', 'paciente_endereco_uf', 'paciente_endereco_nmpais', 'paciente_endereco_cep', 'paciente_nacionalidade_enumnacionalidade', 'estabelecimento_valor', 'estabelecimento_razaosocial', 'estalecimento_nofantasia', 'estabelecimento_municipio_codigo', 'estabelecimento_municipio_nome', 'estabelecimento_uf', 'vacina_grupoatendimento_codigo', 'vacina_grupoatendimento_nome', 'vacina_categoria_codigo', 'vacina_categoria_nome', 'vacina_lote', 'vacina_fabricante_nome', 'vacina_fabricante_referencia', 'vacina_dataaplicacao', 'vacina_nome', 'sistema_origem', 'data_importacao_rnds', 'id_sistema_origem' ], axis=1) # - base_vacina2 # + pd.options.display.float_format = '{:.2f}'.format base_vacina2.describe() # - # verificando valores onde se encontram dados nao-nulos #Contagem de dados nรฃo-nulos de todas as colunas com o .count base_vacina2.count() == 3289543 # Note que temos as colunas: # paciente_idade # paciente_enumsexobiologico # paciente_racacor_codigo # paciente_endereco_nmmunicipio # # com menos dados que o total # Descobrindo a quantidade de valores inconsistentes ou faltantes print(base_vacina2.paciente_idade.count()) print(base_vacina2.paciente_enumsexobiologico.count()) print(base_vacina2.paciente_racacor_codigo.count()) print(base_vacina2.paciente_endereco_nmmunicipio.count()) # A maior quantidade de dados faltantes estรก em no municรญpio com 7614 entradas nรฃo preenchidas! # ### 1 - Corrigindo a idade base_vacina2.loc[base_vacina2['paciente_idade'] == 0 ] base_vacina2.loc[pd.isnull(base_vacina2['paciente_idade'])] # Temos 6 linhas com idades nรฃo vรกlidas sendo 5 com idade 0 e 1 com valor faltante. # Podemos preencher com a mรฉdia # # base_vacina2.loc[base_vacina2['paciente_idade'] == 0, 'paciente_idade' ] = base_vacina2['paciente_idade'].mean() base_vacina2.loc[pd.isnull(base_vacina2['paciente_idade']), 'paciente_idade'] = base_vacina2['paciente_idade'].mean() base_vacina2.loc[base_vacina2['paciente_idade'] == 0 ] base_vacina2.loc[pd.isnull(base_vacina2['paciente_idade'])] # ### 2 - Corrigindo o paciente_enumsexobiologico base_vacina2.loc[base_vacina2['paciente_enumsexobiologico'] == ' ' ] base_vacina2.loc[base_vacina2['paciente_enumsexobiologico'] == 'I' ] base_vacina2.loc[pd.isnull(base_vacina2['paciente_enumsexobiologico'])] base_vacina3 = base_vacina2.drop(base_vacina2.loc[base_vacina2['paciente_enumsexobiologico'] == 'I' ].index) base_vacina3.loc[pd.isnull(base_vacina3['paciente_enumsexobiologico'])] base_vacina3 = base_vacina3.drop(base_vacina3.loc[pd.isnull(base_vacina3['paciente_enumsexobiologico'])].index) # ### 3 -corrigindo paciente_racacor_codigo base_vacina3.loc[base_vacina3['paciente_racacor_codigo'] == 0 ] base_vacina3.loc[pd.isnull(base_vacina3['paciente_racacor_codigo'])] # Por se tratar de somente uma linha e ser um atributo categรณrico podemos excluir esse dado ou substituir pelo que aparece mais vezes. base_vacina3 = base_vacina3.drop(384) base_vacina3 base_vacina3.count() == 3289534 # Note que agora, somente a coluna endereco_nmmunicipio contรฉm dados faltantes # ### 4 -corrigindo paciente_endereco_nmmunicipio # # # testando para ver se tem algum resultado nan base_vacina3.loc[pd.isnull(base_vacina3['paciente_endereco_nmmunicipio'])] df = base_vacina3.drop(base_vacina3.loc[pd.isnull(base_vacina3['paciente_endereco_nmmunicipio'])].index) df df.count() == 3279024 df.loc[pd.isnull(base_vacina3['vacina_descricao_dose'])] # ### 5 -corrigindo vacina_descricao_dose # Vamos substituit a descriรงรฃo 'dose' por 'unica' # + # print(data_vac[data_vac['vacina_descricao_dose'] == 'Dose\xa0'].shape) # print(data_vac[data_vac['vacina_descricao_dose'] == 'รšnica\xa0'].shape) df.loc[df['vacina_descricao_dose'] == 'Dose\xa0', 'vacina_descricao_dose' ] = 'รšnica\xa0' # - df.loc[df['vacina_descricao_dose']== 'Dose\xa0'] print(df[df['vacina_descricao_dose'] == 'Dose\xa0'].shape) print(df[df['vacina_descricao_dose'] == 'รšnica\xa0'].shape) df.count() # # Salvand novo Dataframe com os dados tratados df.to_csv('dados_vacina_RN_clean.csv') #contando os valores รบnicos que existem na coluna 'sexo' np.unique(df['paciente_enumsexobiologico'], return_counts=True) sns.countplot(x = df['paciente_enumsexobiologico']); plt.xlabel('Sexo', size=14) plt.show() #quanto ao fabricante np.unique(df['vacina_codigo'], return_counts=True) sns.countplot(x = df['vacina_codigo']); plt.xticks(size=12) plt.show() # + # os numeros por idade plt.figure(figsize=(15, 8)) sns.histplot(x = df['paciente_idade'], bins=40, kde=True, stat="density", color='#512DA8') plt.xticks(size =18) plt.yticks(size = 18) plt.xlabel('idade', size =25) plt.ylabel('density ', size =25) plt.show() # - sns.countplot(x = df['vacina_descricao_dose']); plt.xticks(size=12) plt.show()
Vacinacao_RN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt import talib as ta import bt volumes = pd.read_csv('Data/stock_volumes.csv', index_col = 'date', parse_dates = True) prices = pd.read_csv('Data/stock_prices.csv', index_col = 'date', parse_dates = True) info = pd.read_csv('Data/stock_info.csv') sp_listings = pd.read_csv('Data/sp500_listings.csv') # + stocks = ['AAPL', 'AMZN', 'NFLX'] info[info["MNEM"].str.contains('|'.join(stocks), na= False)] # - aapl_df = pd.DataFrame(prices['992816']).loc['2012-05-1':'2021-05-31'] amzn_df = pd.DataFrame(prices['891399']).loc['2012-05-1':'2021-05-31'] nflx_df = pd.DataFrame(prices['15303X']).loc['2012-05-1':'2021-05-31'] aapl_df['AMZN'] = amzn_df aapl_df['NFLX'] = nflx_df full_df = aapl_df.rename(columns={"992816": "AAPL"}) full_df df = full_df['AMZN'] # + # calculate daily returns of stocks returns_daily = full_df.pct_change() # resample the full dataframe to monthly timeframe monthly_df = full_df.resample('BMS').first() # calculate monthly returns of the stocks returns_monthly = monthly_df.pct_change().dropna() print(returns_monthly.tail()) # - df = pd.DataFrame(df) df['EMA_14'] = ta.EMA(df['AMZN'], timeperiod=14) df['EMA_50'] = ta.EMA(df['AMZN'], timeperiod=50) df['SMA_14'] = ta.SMA(df['AMZN'], timeperiod=14) df['SMA_50'] = ta.SMA(df['AMZN'], timeperiod=50) df['RSI'] = ta.RSI(df['AMZN'], timeperiod=14) df['Momentum'] = ta.MOM(df['AMZN'],timeperiod=10) df # + # def generate_features(df): # for col in df.columns: # df['EMA_14'] = ta.EMA(df[col], timeperiod=14) # df['EMA_50'] = ta.EMA(df[col], timeperiod=50) # df['SMA_14'] = ta.SMA(df[col], timeperiod=14) # df['SMA_50'] = ta.SMA(df[col], timeperiod=50) # df['RSI'] = ta.RSI(df[col], timeperiod=14) # print(df) # -
feature-engineering/Feature Engineering v0.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import torch import torchvision import torch2trt model = torchvision.models.segmentation.deeplabv3_resnet101(pretrained=True) model = model.cuda().eval().half() class ModelWrapper(torch.nn.Module): def __init__(self, model): super(ModelWrapper, self).__init__() self.model = model def forward(self, x): return self.model(x)['out'] model_w = ModelWrapper(model).half() data = torch.ones((1, 3, 224, 224)).cuda().half() model_trt = torch2trt.torch2trt(model_w, [data], fp16_mode=True) # # Live demo # + # from jetcam.csi_camera import CSICamera from jetcam.usb_camera import USBCamera # camera = CSICamera(width=224, height=224) camera = USBCamera(width=224, height=224) camera.running = True # + from jetcam.utils import bgr8_to_jpeg import traitlets import ipywidgets image_w = ipywidgets.Image() traitlets.dlink((camera, 'value'), (image_w, 'value'), transform=bgr8_to_jpeg) display(image_w) # + import cv2 import numpy as np import torchvision device = torch.device('cuda') mean = 255.0 * np.array([0.485, 0.456, 0.406]) stdev = 255.0 * np.array([0.229, 0.224, 0.225]) normalize = torchvision.transforms.Normalize(mean, stdev) def preprocess(camera_value): global device, normalize x = camera_value x = cv2.cvtColor(x, cv2.COLOR_BGR2RGB) x = x.transpose((2, 0, 1)) x = torch.from_numpy(x).float() x = normalize(x) x = x.to(device) x = x[None, ...] return x # + seg_image = ipywidgets.Image() display(seg_image) # + def execute(change): image = change['new'] output = model_trt(preprocess(camera.value).half())[0].detach().cpu().float().numpy() mask = 1.0 * (output.argmax(0) == 15) seg_image.value = bgr8_to_jpeg(mask[:, :, None] * image) mask = execute({'new': camera.value}) # camera.observe(execute, names='value') # - camera.observe(execute, names='value') camera.unobserve(execute, names='value') # + import time torch.cuda.current_stream().synchronize() t0 = time.time() for i in range(100): output = model_w(preprocess(camera.value).half()) torch.cuda.current_stream().synchronize() t1 = time.time() print(100.0 / (t1 - t0))
notebooks/image_segmentation/conversion.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # ## <center><font color='blue'>IICR functions for the n-island model</font></center> # This is a test notebook for the Python package <em>nisland</em>. # # For an n-island model with $n$ islands, $T_{k,\sigma}^{(K),n,M}$ denotes the $k$-th coalescence time where $K$ is the initial number of genes, $M$ the constant migration rate and $\sigma$ the initial state, i.e. an initial repartition of the $K$ genes in the $n$ islands. # # Denoting by $F(t)$ the cumulative distribution function $F(t) = \mbox{P}_\sigma ( T_{k,\sigma}^{(K),n,M} \leq t )$, the IICR is defined by # $$ # \lambda_{k,\sigma}^{(K),n,M}(t) = \frac{k(k-1)}{2} \; \frac{1 - F(t)}{F'(t)}. # $$ # ##### <font color='blue'> Importing some packages</font> import numpy as np from nisland import * import matplotlib import matplotlib.pyplot as plt # %matplotlib inline matplotlib.rcParams['figure.figsize']=(9.0,6.0) # ### <font color='blue'>1. Graph of $\lambda_{2,0}^{(4),10,1.0}(t)$ for $0 \leq t \leq 4$</font> # In the initial state, all 4 genes are located in the same island (st=0) n=10 M=1.0 K=4 k=2 st=0 # + lt = np.arange(0.001,4.0011,0.1) lv = [mk_F_iicr(n,M,K,k,st,t)[1] for t in lt] lim=-k*(k-1)/2/main_eigenvalue(n,M,k) tit = 'n-island model IICR: $\lambda_{'+str(k)+','+str(st)+'}^{('+str(K)+'),'+str(n)+','+str(M)+'}$' plt.plot(lt,lv,color='blue') plt.plot([0,4],[lim,lim],color='red',linestyle='dashed') plt.title(tit,fontsize=16,y=1.05) plt.axis([0,4,0,20]) plt.xlabel('Time',fontsize=14) plt.ylabel('IICR',fontsize=14) plt.tick_params(axis='both',which='major',labelsize=12) plt.show() # - # The limit when $t \to + \infty$ is: print 'lim =',lim # ### <font color='blue'>2. Graph of $\lambda_{k,0}^{(5),10,1.0}(t)$ for $2 \leq k \leq 5$ and $0 \leq t \leq 4$</font> # In the initial state, all 5 genes are located in the same island (st=0) n=10 M=1.0 K=5 kmax=5 st=0 tmin=0.001 tmax=4.001 dt=0.1 # + llpt = mk_fixed_K_iicrs(n,M,K,kmax, st, tmin,tmax,dt) tit = 'n-island model IICR: $\lambda_{k,'+str(st)+'}^{('+str(K)+'),' tit += str(n)+','+str(M)+'}$, $2 \leq k \leq'+str(kmax)+'$' for i in range(1,len(llpt)): plt.plot(llpt[0],llpt[i],label = "T {}".format(i)) plt.axis([0,4,0,20]) plt.xlabel('Time',fontsize=14) plt.ylabel('IICR',fontsize=14) plt.tick_params(axis='both',which='major',labelsize=12) plt.title(tit,fontsize=16,y=1.05) plt.legend(loc="best") plt.show() # - # ### <font color='blue'>3. Graph of $\lambda_{2,0}^{(K),4,1.0}(t)$ for $2 \leq K \leq 20$ and $0 \leq t \leq 4$</font> # In initial states (one for each value of K), all genes are located in the same island (st=0) n=4 M=1.0 Kmax=20 k=2 st=0 t0=0.001 tmax=4.001 dt=0.1 # + res= mk_fixed_k_iicrs(n,M,Kmax,k,st,t0,tmax,dt) lim=-k*(k-1)/2/main_eigenvalue(n,M,k) tit = 'n-island model IICR: $\lambda_{2,'+str(st)+'}^{(K),' tit += str(n)+','+str(M)+'}$, $2 \leq K \leq'+str(Kmax)+'$' for i in range(1,Kmax-k+2): plt.plot(res[:,0],res[:,i],label = "K {}".format(k+i-1)) plt.plot([0,4],[lim,lim],color='red',linestyle='dashed',label='limit') plt.axis([0,4,0,7]) plt.xlabel('Time',fontsize=14) plt.ylabel('IICR',fontsize=14) plt.tick_params(axis='both',which='major',labelsize=12) plt.title(tit,fontsize=16,y=1.05) plt.legend(bbox_to_anchor=(1.2,-0.015),loc=4) plt.show() # - # The limit when $t \to + \infty$ is: lim # The same graphic, below obtained under Maple and animated, shows the behavior of the IICC when $K \to +\infty$. # <img src="iicr_n4_M1_k2_st1.gif"> # It could be interesting to obtain a similar animated graphic using the Python package 'animate'.
test_nisland.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/yohanesnuwara/geostatistics/blob/main/geostatistics_with_python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="ptX0SSPOMtS9" import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import scipy import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) # + colab={"base_uri": "https://localhost:8080/"} id="-nqb3mtYhd5g" outputId="7bebf3f3-35db-4076-d9cd-1404efc15877" # !git clone https://github.com/yohanesnuwara/geostatistics # + [markdown] id="buDWfLQpj9zk" # ## Histograms and summary statistics # + colab={"base_uri": "https://localhost:8080/", "height": 408} id="E7KE8eEohxjP" outputId="daaaa3e3-a357-46e5-afe2-c539662b55bf" prm03 = np.loadtxt('/content/geostatistics/data/FU3PRM.DAT', skiprows=1) prm10 = np.loadtxt('/content/geostatistics/data/FU10PRM.DAT', skiprows=1) prm03_df = pd.DataFrame({'Depth': prm03[:,0], 'Permea': prm03[:,1], 'Poro': prm03[:,2]}) prm10_df = pd.DataFrame({'Depth': prm10[:,0], 'Permea': prm10[:,1], 'Poro': prm10[:,2]}) prm03_df # + colab={"base_uri": "https://localhost:8080/", "height": 711} id="vN7ExLjyilXi" outputId="21708b76-354a-43e0-bcc9-0101cb2a1ce2" plt.figure(figsize=(10,10)) plt.subplot(3,2,1) plt.hist(prm03_df['Poro'], bins=20, edgecolor='black', alpha=0.5) plt.xlabel('Porosity'); plt.ylabel('Frequency') plt.title('PRM03 Porosity Histogram') plt.subplot(3,2,2) plt.hist(prm10_df['Poro'], bins=20, edgecolor='black', alpha=0.5) plt.xlabel('Porosity'); plt.ylabel('Frequency') plt.title('PRM10 Porosity Histogram') plt.subplot(3,2,3) plt.hist(prm03_df['Permea'], bins=20, color='red', edgecolor='black', alpha=0.5) plt.xlabel('Permeability'); plt.ylabel('Frequency') plt.title('PRM03 Permeability Histogram') plt.subplot(3,2,4) plt.hist(prm10_df['Permea'], bins=20, color='red', edgecolor='black', alpha=0.5) plt.xlabel('Permeability'); plt.ylabel('Frequency') plt.title('PRM10 Permeability Histogram') plt.subplot(3,2,5) plt.hist(np.log10(prm03_df['Permea']), bins=20, color='green', edgecolor='black', alpha=0.5) plt.xlabel('Log Permeability'); plt.ylabel('Frequency') plt.title('PRM03 Log Permeability Histogram') plt.subplot(3,2,6) plt.hist(np.log10(prm10_df['Permea']+0.01), bins=20, # Trickery here +0.01 to add to 0 values color='green', edgecolor='black', alpha=0.5) # unless, log10 return -inf plt.xlabel('Log Permeability'); plt.ylabel('Frequency') plt.title('PRM10 Log Permeability Histogram') plt.tight_layout(2) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 288} id="9XYyTfD4o2Nd" outputId="9e4178e1-f9c2-4807-c827-e6bb1cf2d7ca" prm03_df.describe() # + colab={"base_uri": "https://localhost:8080/", "height": 288} id="H1Lw75F7qcdx" outputId="141ac5f5-d546-450d-da85-5c49c5bf8b45" prm03_df.describe() # + [markdown] id="VaOTyxMn2d1y" # ## Probability density function (PDF) and confidence interval (CI) # + [markdown] id="lpjdSWSd9WRc" # Until now there is a confusion if CI equals to percentile (as the Stats Thinking II in Datacamp itself declared so), however I refer to Dr. Pyrcz' notebook [here](https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/PythonDataBasics_Hypothesis.ipynb) that CI has different formula. So, I assume both are different (and I believe so). # + id="80mBtJnW2h9a" def conf_interval(data, pvalue): """ Determine confidence interval """ # Version 1 based on Stackoverflow: https://stackoverflow.com/questions/28242593/correct-way-to-obtain-confidence-interval-with-scipy CI = scipy.stats.norm.interval(pvalue, loc=np.mean(data), scale=np.std(data)) return CI # + colab={"base_uri": "https://localhost:8080/", "height": 296} id="KXf7JWe4-z8W" outputId="abb38047-b3b3-4e26-a90f-b0d7e9e39203" pvalue = 0.95 # Compute CI CI = conf_interval(prm03_df['Poro'], pvalue) print('{}% confidence interval between {} and {}'.format(int(pvalue * 100), CI[0], CI[1])) # Plot PDF sns.kdeplot(prm03_df['Poro'], color='blue') plt.axvline(CI[0], linestyle='--', color='red') plt.axvline(CI[1], linestyle='--', color='red') plt.show() # + [markdown] id="BWS3U8WB_11h" # For PRM03 well, we are 95% confident that porosity is between 13.25% and 34%. # + [markdown] id="DO4IQ72S7U23" # ## Cumulative distribution function (CDF) plot # + [markdown] id="fwpCPR8_7ZX3" # Visual tool to identify the probability of a thing and identify normal distribution. # + id="-L1nXlfE77Ic" def ecdf(data): """ Plot ECDF (Empirical Cumulative Distribution Function) """ n = len(data) x = np.sort(data) y = np.arange(1, n+1) / n plt.scatter(x, y, alpha=0.5) # + colab={"base_uri": "https://localhost:8080/", "height": 616} id="R9UhECkSvUWO" outputId="bc8a5871-e4e7-4c49-e872-61305d9ff95e" # plot CDF for poroperm of PRM03 and PRM10 plt.figure(figsize=(12,9)) plt.subplot(2,2,1) ecdf(prm03_df['Poro'].values) plt.title('CDF of PRM03 Porosity') plt.xlabel('Porosity (%)'); plt.ylabel('ECDF') plt.axhline(0.9, linestyle='--', color='red') # 90% probability line plt.axvline(29, linestyle='--', color='red') plt.subplot(2,2,2) ecdf(prm10_df['Poro'].values) plt.title('CDF of PRM10 Porosity') plt.xlabel('Porosity (%)'); plt.ylabel('ECDF') plt.axhline(0.9, linestyle='--', color='red') # 90% probability line plt.axvline(18, linestyle='--', color='red') plt.subplot(2,2,3) ecdf(prm03_df['Permea'].values) plt.title('CDF of PRM03 Permeability') plt.xlabel('Permeability (md)'); plt.ylabel('ECDF') plt.subplot(2,2,4) ecdf(prm10_df['Permea'].values) plt.title('CDF of PRM10 Permeability') plt.xlabel('Permeability (md)'); plt.ylabel('ECDF') plt.tight_layout(2) plt.show() # + [markdown] id="nChYQLFFux7a" # For PRM03, 90% probability a porosity is lower than 29%. For PRM10, 90% probability a porosity is lower than 18%. # + [markdown] id="YiGtWb1ukEzJ" # ## Probability distribution # + [markdown] id="YGbxq2_hGLzB" # Based on an oil field report, a pay zone has thickness with mean of 18 m and variance of 400 m2. Determine: # 1. The probability of the pay zone to have a thickness less than 20 m # # Solution: # $\sigma (std)=\sqrt {\sigma^2}=20$ # $$Z=\frac{X-\mu}{\sigma}$$ # $$Z=\frac{X-18}{20}$$ # # $$P(X>20)=P(Z>\frac{20-18}{20})=P(Z>0.1)=cdf(20)$$ # cdf is cumulative distribution function. R equivalent is `pnorm` # # 2. The probability of the pay zone to have a thickness over 20 m # # Solution: # # $$P(X<20)=P(Z<\frac{20-18}{20})=P(Z<0.1)=1-P(Z>0.1)=1-cdf(20)$$ # # 3. The probability of the pay zone to have a thickness between 20 m and 60 m # # Solution: # # $$P(20<X<60)=P(X<60)-P(X<20)=P(Z<\frac{60-18}{20})-P(Z<\frac{20-18}{20})=P(Z<2.1)-P(Z<0.1)=cdf(60)-cdf(20)$$ # # 4. Maximum thickness of the pay zone for a probability as large as 80% # # Solution: # # $$P(Z<\frac{X-18}{20})=0.8$$ # # Solve $Z=ppf(0.8)$; ppf is percent point function (inverse of CDF). R equivalent is `qnorm` # # Solve $X=20\cdot Z+18$ # # # + colab={"base_uri": "https://localhost:8080/", "height": 386} id="0N9pYBnQsGNb" outputId="8479dfc5-bcc6-4c8e-97dc-0c6f30db7f26" # Histogram of pay zone with Seaborn (sns) np.random.seed(10) poro = np.random.normal(18, 20, 100) # generate random numbers with size 100 sns.displot(poro, kde=True) # + colab={"base_uri": "https://localhost:8080/"} id="I4hNJXNtD2wT" outputId="d79d5e81-8825-4e64-ae6f-bddeb235a4b2" # Question 1 p1 = scipy.stats.norm.cdf(20, 18, 20) # 1st argument: thickness, 2nd: mean, 3rd: std print('The probability of the pay zone to have a thickness < 20 m is:', np.round(p1, 3)) # Question 2 p2 = 1 - scipy.stats.norm.cdf(20, 18, 20) p2 = scipy.stats.norm.sf(20, 18, 20) # equivalent to above print('The probability of the pay zone to have a thickness > 20 m is:', np.round(p2, 3)) # Question 3 p3 = scipy.stats.norm.cdf(60, 18, 20) - scipy.stats.norm.cdf(20, 18, 20) print('The probability of the pay zone to have a thickness between 20 and 60 m is:', np.round(p3, 3)) # Question 4 Z = scipy.stats.norm.ppf(0.8) x = 20 * Z + 18 print('Maximum thickness of pay zone to have probability 80% is: {} m'.format(np.round(x, 3))) # + [markdown] id="dtfO3zcUkKxY" # Based on a field report, a formation has porosity with mean 0.2 and variance 0.0004. The porosity is normally distributed. Determine: # 1. Probability of the formation to have porosity between 0.18 and 0.22 # 2. Probability of the formation is considered as a reservoir, if porosities less than 0.15 is considered not a reservoir # 3. The required standard deviation so that probability in (2) becomes 70% # # Solution: # # $$P(Z<\frac{0.15-0.2}{\sigma})=0.7$$ # # Solve $Z=ppf(0.7)$ # # Solve $\sigma=\frac{0.15-0.2}{Z}$ # 4. The required mean so that probability of the formation to have porosity more than 0.15 becomes 85% # Solution: # # $$P(Z<\frac{0.15-\mu}{0.02})=0.85$$ # # Solve $Z=ppf(0.85)$ # # Solve $\mu=0.15 - Z \cdot 0.02$ # + colab={"base_uri": "https://localhost:8080/"} id="fSRe3HOdqwC0" outputId="989e6bf9-5cf5-4ae4-cbe0-851061e50afe" mean = 0.2 var = np.sqrt(0.0004) # Question 1 p1 = scipy.stats.norm.cdf(0.22, mean, var) - scipy.stats.norm.cdf(0.18, mean, var) print('Probability of the formation to have porosity between 0.18 and 0.22 is:', np.round(p1, 3)) # Question 2 p2 = scipy.stats.norm.sf(0.15, mean, var) print('Probability of the formation to have porosity above 0.15 to be considered as reservoir:', np.round(p2, 3)) # Question 3 expected_p1 = 0.7 z1 = scipy.stats.norm.ppf(1 - expected_p1) std = 0.15 - 0.2 / z1 print('Std so that the formation having probability equals 70% to be considered as reservoir is:', np.round(std, 3)) # Question 4 expected_p2 = 0.85 z2 = scipy.stats.norm.ppf(1 - expected_p2) mean = 0.15 - z2 * 0.02 print('Mean so that the formation having probability equals 85% to be considered as reservoir:', np.round(mean, 3)) # + [markdown] id="dxa7TsKKlVwf" # ## Theoretical quantile plot # + [markdown] id="U6ksA9f-lXmk" # Is used to identify if the data is normally (Gaussian) distributed. The median is data where quantile equals 0.5. # + colab={"base_uri": "https://localhost:8080/", "height": 469} id="TwXzXBDrTHlB" outputId="c8387ead-7e94-4a51-e4d0-831510e63ccd" # synthetic data np.random.seed(10) size = 1000 aa = np.random.normal(0, 1, size) # create quantiles x = np.linspace(0,1,size) # crossplot sorted data vs theoretical quantiles plt.figure(figsize=(10,7)) plt.scatter(x, np.sort(aa), alpha=0.2) plt.xlabel('Quantile'); plt.ylabel('Sorted Data') plt.title('Theoretical Quantile', size=15, pad=15) plt.show() # + id="E48hultlpRwd" def theo_quant(data, color='blue', alpha=0.2): """ Create theoretical quantile plot """ size = len(data) q = np.linspace(0,1,size) plt.scatter(q, np.sort(data), color=color, alpha=alpha) plt.xlabel('Theoretical Quantiles') plt.ylabel('Sorted Data') # + colab={"base_uri": "https://localhost:8080/", "height": 711} id="YrMs9qe3p7Zu" outputId="807cf184-9592-4d54-8cf5-894f4aa9660c" plt.figure(figsize=(10,10)) plt.subplot(3,2,1) theo_quant(prm03_df['Poro'].values) plt.title('PRM03 Porosity') plt.subplot(3,2,2) theo_quant(prm10_df['Poro'].values) plt.title('PRM10 Porosity') plt.subplot(3,2,3) theo_quant(prm03_df['Permea'].values, color='red') plt.title('PRM03 Permeability') plt.subplot(3,2,4) theo_quant(prm10_df['Permea'].values, color='red') plt.title('PRM10 Permeability') plt.subplot(3,2,5) theo_quant(np.log10(prm03_df['Permea'].values), color='green') plt.title('PRM03 Log Permeability') plt.subplot(3,2,6) theo_quant(np.log10(prm10_df['Permea'].values), color='green') plt.title('PRM10 Log Permeability') plt.tight_layout(2) plt.show() # + [markdown] id="ixZYJDcinLDN" # ## Q-Q Plot # + [markdown] id="ljInvR5vq1Ow" # Q-Q plot practical explanation see [here](https://www.geeksforgeeks.org/qqplot-quantile-quantile-plot-in-python/). R equivalent is `qqnorm` and `qqline` # + colab={"base_uri": "https://localhost:8080/", "height": 513} id="p0YoVQBUlLbi" outputId="192485ab-899b-4f6f-b5db-25e5ce00a8ce" plt.figure(figsize=(8,8)) scipy.stats.probplot(aa, plot=plt) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 711} id="zIGV3dFxnOZj" outputId="419ce9ed-7bd2-4b9e-9cc3-590a09396150" plt.figure(figsize=(10,10)) plt.subplot(3,2,1) scipy.stats.probplot(prm03_df['Poro'], plot=plt) plt.title('PRM03 Porosity') plt.subplot(3,2,2) scipy.stats.probplot(prm10_df['Poro'], plot=plt) plt.title('PRM10 Porosity') plt.subplot(3,2,3) scipy.stats.probplot(prm03_df['Permea'], plot=plt) plt.title('PRM03 Permeability') plt.subplot(3,2,4) scipy.stats.probplot(prm10_df['Permea'], plot=plt) plt.title('PRM10 Permeability') plt.subplot(3,2,5) scipy.stats.probplot(np.log10(prm03_df['Permea']), plot=plt) plt.title('PRM03 Log Permeability') plt.subplot(3,2,6) scipy.stats.probplot(np.log10(prm10_df['Permea']+0.01), plot=plt) plt.title('PRM10 Log Permeability') plt.tight_layout(2) plt.show() # + [markdown] id="0h1RPv_Y8J6l" # ## Kurtosis # + [markdown] id="FpI7VonDCmCN" # Kurtosis is used to identify signal and noise in a time series data, such as a seismogram, i.e. to pick seismic events. # + colab={"base_uri": "https://localhost:8080/", "height": 168} id="TGth-0dl8Mih" outputId="7cb52c6e-a393-4292-8ff7-4b6da4ecbaca" # get seismogram data seis = np.loadtxt('/content/geostatistics/data/seis-ch1.txt', skiprows=1, usecols=1) # plot seismogram x = np.arange(len(seis)) plt.figure(figsize=(20,3)) plt.plot(x, seis) plt.xlim(0, max(x)) plt.xlabel('Index'); plt.ylabel('Amplitude') plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 308} id="2LZpmepKSc7v" outputId="0153fcc2-ddc0-45d5-b961-04da94ac9a03" # plot histogram # Gaussian at index 1000-2000, non-Gaussian at 2000-3000 plt.figure(figsize=(15,5)) plt.subplot(1,2,1) plt.hist(seis[1000:2000], bins=30, color='blue', edgecolor='black') plt.subplot(1,2,2) plt.hist(seis[2000:3000], bins=30, color='red', edgecolor='black') plt.show() # + id="Quiyl9M0Ceyp" def kurtosis(data, window=10): """ Calculate kurtosis over a specified window """ kurt = [] for i in range(len(data)): a = data[i:i+window] std, mean = np.std(data), np.mean(data) y = np.sum((a - mean)**4) / window k = y / std**4 kurt.append(k) return kurt # + colab={"base_uri": "https://localhost:8080/", "height": 290} id="87qs0RkyEbTq" outputId="e008f794-d060-4da3-810d-5b24824cdb26" # calculate rolling kurtosis with window 50 kurt = kurtosis(seis, window=50) # plot seismogram and kurtosis x = np.arange(len(seis)) plt.figure(figsize=(20,7)) plt.subplot(2,1,1) plt.plot(x, seis) plt.xlim(0, max(x)) plt.xlabel('Index'); plt.ylabel('Amplitude') plt.title('Seismogram', size=20, pad=15) plt.subplot(2,1,2) plt.plot(x, kurt/max(kurt), color='red') plt.xlim(0, max(x)) plt.xlabel('Index'); plt.ylabel('Kurtosis') plt.title('Normalized Kurtosis', size=20, pad=15) plt.tight_layout(2) plt.show() # + [markdown] id="R5KLfEthUYlO" # ## Cross-correlation # + [markdown] id="auG9Puc1YZgA" # Correlation between two data at zero-lag # + id="5MI65t7AX3lO" def xcor(x, y): """ Calculate cross-correlation between two data """ cxy = np.cov(x, y)[0,1] var1, var2 = np.var(x), np.var(y) xcor = cxy / np.sqrt(var1 * var2) return xcor # + [markdown] id="Z0R82pqKJQtD" # Test into synthetic data. Data `aa` and `bb` have independently randomness. The crosscorrelation will equal nearly 0, because there's no correlation. # + colab={"base_uri": "https://localhost:8080/", "height": 329} id="RC_7e439YGBm" outputId="d23fb159-0841-4396-fde3-e77299ad0b22" # test synthetic data aa = np.random.normal(0, 1, 1000) bb = np.random.normal(0, 1, 1000) print(xcor(aa, bb)) # using the created function print(np.corrcoef(aa, bb)[0,1]) # using Numpy built-in function # scatter plot of data plt.scatter(aa, bb, alpha=0.5) plt.xlabel('aa'); plt.ylabel('bb') plt.title('Scatter Plot') plt.show() # + [markdown] id="GuGbb-vjML3B" # Test to other synthetic data, one has positive correlation, another has negative correlation # + colab={"base_uri": "https://localhost:8080/", "height": 385} id="MmFISQ6lMSz6" outputId="9685f51d-f7a4-45f7-d4d2-6f8c0960efbe" # synthetic data x1 = x2 = np.linspace(0,100,100) noise = np.random.normal(0,1,100) * 10 y1 = 2 * x1 + noise y2 = -y1 xcor1 = xcor(x1, y1) xcor2 = xcor(x2, y2) print('Cross-correlation of data 1 is:', np.round(xcor1, 3)) print('Cross-correlation of data 2 is:', np.round(xcor2, 3)) # plot data plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.scatter(x1, y1, color='blue', alpha=0.5) plt.xlabel('x1'); plt.ylabel('y1') plt.subplot(1,2,2) plt.scatter(x2, y2, color='red', alpha=0.5) plt.xlabel('x2'); plt.ylabel('y2') plt.tight_layout(2) plt.show() # + [markdown] id="7R97LgiXPgTE" # Analyze cross-correlation between porosity and permeability of PRM03 well. # + colab={"base_uri": "https://localhost:8080/", "height": 368} id="25rrIVMEPwcJ" outputId="a1102551-9d10-427b-8d00-31bd00737f41" poroperm = xcor(prm03_df['Poro'].values, prm03_df['Permea'].values) print('Cross-correlation of poroperm in PRM03 well is:', np.round(poroperm, 3)) # plot data plt.figure(figsize=(7,5)) plt.scatter(prm03_df['Poro'].values, prm03_df['Permea'].values, c=prm03_df['Depth'], alpha=0.5) plt.xlabel('Poro'); plt.ylabel('Perm') plt.colorbar() plt.tight_layout(2) plt.show() # + [markdown] id="dpR9l5S3ZfYp" # ## Auto-correlation # + [markdown] id="4nUT9znkIZRH" # Is the cross-correlation at one portion of the data to another portion of the data (lags). # + id="5f40pnF3YWbJ" def autocor(x): """ Calculate auto-correlation in a data """ nm = len(x) autocor = np.zeros(nm) for i in range(nm): autocor[i] = np.corrcoef(x[i:nm-1], x[:nm-i-1])[0,1] return autocor # + [markdown] id="i566CWASI5rt" # Test into a synthetic data. The data `bb` consists of 9 times repeated sequence `aa`. The autocorrelation in the correlalogram will show that lag happens at every 100 inetrvals. # + colab={"base_uri": "https://localhost:8080/", "height": 328} id="ONrDyth0Gfbk" outputId="3611b350-cab4-41a5-cdf5-d3239df872f9" # test synthetic data aa = np.random.normal(0, 1, 100) bb = np.concatenate((aa, aa, aa, aa, aa, aa, aa, aa, aa)) # 9 times repeated aa # calculate autocorrelation ac = autocor(bb) # plot data index = np.arange(len(bb)) plt.figure(figsize=(15,6)) plt.subplot(2,1,1) plt.plot(index, bb) plt.title('Time series data') plt.xlabel('Index'); plt.ylabel('bb') plt.xlim(-10, max(index)) # plot correlalogram plt.subplot(2,1,2) plt.plot(index, ac, color='red') plt.title('Correlalogram') plt.xlabel('Index'); plt.ylabel('Cross-correlation') plt.xlim(-10, max(index)) plt.tight_layout(2) plt.show() # + [markdown] id="lWCvVPdgOJJ8" # Case study: An industry is dumping wastewater into underground, and some seismic activities are felt. Given the data of seismic activities, using autocorrelation identify is there any correlation between the wastewater injection and the seismic activities? # + colab={"base_uri": "https://localhost:8080/", "height": 349} id="NFwMrzEvPX6u" outputId="9ac364a4-063a-4bfb-d9bd-17120657199a" eq = pd.read_excel('/content/geostatistics/data/Wasteinjected.xlsx') eq.head(10) # + id="Hvos5veV1Xrl" def autocor2(x, y): """ Calculate auto-correlation between two data """ nm = len(x) # length of y must be the same as x autocor = np.zeros(nm) for i in range(nm): autocor[i] = np.corrcoef(x[i:nm-1], y[:nm-i-1])[0,1] return autocor # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="Z5BB60v41pYH" outputId="bc403edb-e2bd-41e5-c4b2-096b6195b7ce" # calculate autocorrelation x = eq.iloc[:,1].values # injected waste volume MMgal y = eq.iloc[:,2].values # number of earthquakes t = np.arange(len(x)) # months ac = autocor2(x, y) plt.plot(t, ac, '.-') plt.show() # + [markdown] id="Ew9RVWvD_CQp" # ## Hypothesis test I: one sample test # + [markdown] id="VYL036m5P1x5" # Test null hypothesis $H_0$ # # If after hypothesis test, $-Z_{crit}<Z_{cal}<+Z_{crit}$, then accept $H_0$ # # If $Z_{cal}<-Z_{crit}$ or $Z_{cal}>+Z_{crit}$, then reject $H_0$ # # โš ๏ธ Tips to state null hypothesis: # # * $H_0$ is always "something less than or equal to something". For instance: "Mean is less than or equal to 7" ($\mu \leq 7$). # * The alternate hypothesis $H_1$ is its contrary. In this case, "Mean is above 7" ($\mu>7$). # # + id="NKWBNPqeCDCt" def ttest_1sample(mean_pop, mean_samp, std_pop, num_samp, h0, alpha=0.05): """ Hypothesis test on one sample Input: mean_pop = mean of population (also called as the claimed mean) mean_samp = mean of sample (samples used to test the hypothesis) std_pop = standard deviation of population num_samp = number of samples h0 = null hypothesis, e.g. in a statement "Mean = 8 kg" alpha = significance level. default is 0.05 or 5% (95% confidence) Output: Zcal and Zcrit, decision = accept or reject h0, based on Z-value comparison, in a statement """ # Z calculated zcal = (mean_samp - mean_pop) / (std_pop / np.sqrt(num_samp)) # Z critical (two-tailed) zcrit1, zcrit2 = scipy.stats.norm.ppf([alpha/2, 1-(alpha/2)]) # Z-value @ p=0.025 and p=0.975 # print Zcal and Zcrit print('Calculated Z :', np.round(zcal, 3)) print('Critical Z : {}, {}'.format(np.round(zcrit1, 3), np.round(zcrit2, 3))) # hypothesis testing if zcal > zcrit1 and zcal < zcrit2: print('Accept that {}'.format(h0)) if zcal < zcrit1 or zcal > zcrit2: print('Reject that {}'.format(h0)) # + [markdown] id="ONue4Ke0__E4" # **Case Study 1** # # A designed material is claimed that it can withstand weights with mean of 8 kg (standard deviation of 0.5 kg). However, from 50 random samples it's found that they can only withstand to weights with mean of 7.8 kg. Use significance level 1%. # # Is the claim true? # # * Null hypothesis $H_0$: Claim is true ($\mu=8$) # # * Alternative hypothesis $H_1$: Claim is false ($\mu \neq 8$) # + colab={"base_uri": "https://localhost:8080/"} id="HSuh2RHmFmXn" outputId="b4be3caf-8a84-4d54-eedd-6301e4c25a69" # Input mean_pop = 8 # claimed mean mean_samp = 7.8 # true mean (from samples) std_pop = 0.5 # std of population num_samp = 50 # number of samples # Null hypothesis h0 = 'The material can withstand weights with mean 8 kg' # Run test ttest_1sample(mean_pop, mean_samp, std_pop, num_samp, h0, alpha=0.1) # + [markdown] id="Cjvd-I8-O11E" # **Case Study 2** # # From 100 random samples, it is found that mean life expectancy in USA is 71.8. Assuming that the whole population has life expectancy distribution with standard deviation of 8.9 years, are the samples enough to conclude that US people have mean life expectancy above 70? Use significance level 5%. # # * Null hypothesis $H_0$: Mean life expectancy under/equal to 70 ($\mu \leq 70$) # # * Alternative hypothesis $H_1$: Mean life expectancy above 70 ($\mu > 70$) # + colab={"base_uri": "https://localhost:8080/"} id="Ghzm4pUeO8KI" outputId="481223bc-28fa-417f-d3e6-50f0160ba563" # Input mean_pop = 70 # claimed mean mean_samp = 71.8 # true mean (from samples) std_pop = 8.9 # std of population num_samp = 100 # number of samples # Null hypothesis h0 = 'Mean life expectancy of US people is below or equal to 70' # Run test ttest_1sample(mean_pop, mean_samp, std_pop, num_samp, h0, alpha=0.05) # + [markdown] id="9Ry72km8WEpd" # ## Hypothesis test II: two sample T-test # + [markdown] id="rCh3kUZe1qkc" # Perform test to compare mean between two samples. Note that in stats, Mean 20.9 and 19.4 could be similar (statistically). So, the significance of such similarity should be tested. # # For example, I have a claim: # # > Your thermometer has mean error 0.02ยฐC larger than mine ๐ŸŒก๏ธ # # Beware when making a null hypothesis. Remember that a keyword for $H_0$ must be "less than $<$" or "equal to $=$". The alternate hypothesis $H_1$ is "more than $>$". # # So, related to the above claim, I have to switch into following hypotheses: # * $H_0$: Our thermometers mean error has no difference ($\mu_{you}=\mu_{mine}$ OR $\mu_{you}-\mu_{mine}=0$) # * $H_1$: Your thermometer mean error is larger than mine ($\mu_{you}>\mu_{mine}$ OR $\mu_{you}-\mu_{mine}=0.02$) # # + id="pUpp2PAUWK36" def ttest_2sample(d0, mean_samp1, mean_samp2, std_samp1, std_samp2, num_samp1, num_samp2, h0, alpha=0.05): """ Hypothesis test on two samples e.g. to test if mean of one sample equals mean of the another sample Input: d0 = expected (claimed) difference between mean of sample 1 and sample 2 * If expected no difference, or ฮผ1 = ฮผ2, input d0=0 * If expected difference ฮผ1-ฮผ2=5, input d0=5 mean_samp1, mean_samp2 = means of sample 1 and sample 2 std_samp1, std_samp2 = standard deviation of sample 1 and sample 2 num_samp1, num_samp2 = number of sample 1 and sample 2 h0 = null hypothesis, e.g. "Mean of sample 1 equals sample 2" alpha = significance level. Default is 0.05 Output: tcal, tcrit, decision = accept or reject h0, based on t-value comparison, in a statement """ # t-value calculated sp = np.sqrt(((std_samp1**2 * (num_samp1 - 1)) + (std_samp2**2 * (num_samp2 - 1))) / (num_samp1 + num_samp2 - 2)) tcal = ((mean_samp1 - mean_samp2) - d0) / (sp * np.sqrt((1 / num_samp1) + (1 / num_samp2))) # t-value critical (two-tailed) df = num_samp1 + num_samp2 - 2 # degree of freedom tcrit1, tcrit2 = scipy.stats.t.ppf([alpha/2, 1-(alpha/2)], df) # Default: t-value @ p=0.025 and p=0.975 # print tcal and tcrit print('Calculated t-value :', np.round(tcal, 3)) print('Critical t-value : {}, {}'.format(np.round(tcrit1, 3), np.round(tcrit2, 3))) # hypothesis testing if tcal > tcrit1 and tcal < tcrit2: print('Accept that {}'.format(h0)) if tcal < tcrit1 or tcal > tcrit2: print('Reject that {}'.format(h0)) # + [markdown] id="EASfydXz25_7" # **Case study 3** (Adapted from Dr. Pyrcz' [material & dataset](https://github.com/GeostatsGuy/PythonNumericalDemos/blob/master/PythonDataBasics_Hypothesis.ipynb)) # # Given 20 porosity measurements from 2 different rock units. Is the mean of porosity of Rock A similar to that of Rock B? # # * Null hypothesis $H_0$: $\mu_A=\mu_B$ or $\mu_A-\mu_B=0$ # # > Could also be $H0$: $\mu_A \leq \mu_B$ or $\mu_A-\mu_B \leq 0$ # # * Alternative hypothesis $H_1$: $\mu_A>\mu_B$ or $\mu_A-\mu_B>0$ # # * So, $d_0$ (claimed mean difference) is 0 # + colab={"base_uri": "https://localhost:8080/", "height": 198} id="yQh2yt276F7f" outputId="e07ed311-a269-4674-95e3-35e187f63a10" filepath = 'https://raw.githubusercontent.com/GeostatsGuy/GeoDataSets/master/PorositySample2Units.csv' sample = pd.read_csv(filepath) sample.head() # + colab={"base_uri": "https://localhost:8080/", "height": 495} id="FHYsvrqN6wWe" outputId="113ea91e-b07a-4eb8-8118-157351299fb4" poro1, poro2 = sample['X1'].values, sample['X2'].values # plot histograms and cdf plot plt.figure(figsize=(9,7)) plt.subplot(2,2,1) plt.hist(poro1, edgecolor='black') plt.title('Sample 1 Porosity Histogram') plt.subplot(2,2,2) plt.hist(poro2, edgecolor='black') plt.title('Sample 2 Porosity Histogram') plt.subplot(2,2,3) ecdf(poro1) plt.title('Sample 1 Porosity CDF') plt.subplot(2,2,4) ecdf(poro2) plt.title('Sample 2 Porosity CDF') plt.tight_layout(2) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="vyYgl52Wx2F8" outputId="012d6820-8fbf-4089-8e50-b00981b698db" # Input d0 = 0 # claimed difference between mean of two samples mean_samp1 = np.mean(poro1) # sample 1 mean mean_samp2 = np.mean(poro2) # sample 2 mean std_samp1 = np.std(poro1) # sample 1 std std_samp2 = np.std(poro2) # sample 2 std num_samp1 = 20 # number of sample 1 num_samp2 = 20 # number of sample 2 # Null hypothesis h0 = 'Porosity mean of sample 1 equals to that of sample 2' # Run test ttest_2sample(d0, mean_samp1, mean_samp2, std_samp1, std_samp2, num_samp1, num_samp2, h0, alpha=0.05) # + [markdown] id="eETqVeNCpjkG" # **Case study 4** # # An experiment was performed to compare the abrasive wear of two different laminated materials. Twelve pieces of material 1 were tested by exposing each piece to a machine measuring wear. Ten pieces of material 2 were similarly tested. In each # case, the depth of wear was observed. The samples of material 1 gave an average # (coded) wear of 85 units with a sample standard deviation of 4, while the samples # of material 2 gave an average of 81 with a sample standard deviation of 5. Can # we conclude at the 0.05 level of significance that the abrasive wear of material 1 # exceeds that of material 2 by more than 2 units? # + [markdown] id="GF96i_2dqkMu" # Claim: Abrasive wear of material 1 exceeds that of material 2 by more than 2 units. # # For a null hypothesis, "more than" cannot be $H_0$ (see explanation in Hypothesis test I). So, I have to switch, as follows: # # * Null hypothesis $H_0$: There is no difference in mean abrasive wear between two materials ($\mu_A=\mu_B$ or $\mu_A-\mu_B = 0$) # # * Alternative hypothesis $H_1$: Abrasive wear of material 1 exceeds that of material 2 by more than 2 units. ($\mu_A-\mu_B > 2$) # # * So, $d_0$ (claimed mean difference) is 2 # # So, if $H_0$ is accepted, then claim is wrong. Otherwise ($H_0$ is rejected), then claim is (statistically) right. # # Be careful... # + colab={"base_uri": "https://localhost:8080/"} id="SBiFlqUed7iL" outputId="6d0f4947-d04b-4b0a-9ac5-11e4c6cb689e" # Input d0 = 2 # claimed difference between mean of two samples mean_samp1 = 85 # sample 1 mean mean_samp2 = 81 # sample 2 mean std_samp1 = 4 # sample 1 std std_samp2 = 5 # sample 2 std num_samp1 = 12 # number of sample 1 num_samp2 = 10 # number of sample 2 # Null hypothesis # Note: don't forget to switch the claim h0 = 'There is no difference in mean abrasive wear between two materials' # Run test ttest_2sample(d0, mean_samp1, mean_samp2, std_samp1, std_samp2, num_samp1, num_samp2, h0, alpha=0.05) # + [markdown] id="mYBtM7VJn4Hq" # It means we cannot conclude that material A has mean abrasive wear 2 units larger than material B. # + [markdown] id="vDAp8xOW1h2q" # ## Hypothesis test III: two sample F-test # + [markdown] id="HAvZ6cCR1uw0" # Perform test to compare variance between two samples. # + id="MVvRU0mv1m7C" def ftest_2sample(var_samp1, var_samp2, num_samp1, num_samp2, h0, alpha=0.05): """ Hypothesis test on two samples e.g. to test if variance of one sample equals variance of the another sample Input: var_samp1, var_samp2 = variance of sample 1 and sample 2 mean_samp1, mean_samp2 = means of sample 1 and sample 2 Output: pvalue, decision = accept or reject h0, based on pvalue comparison, in a statement """ # compute p-value calculated pcal = 1 - scipy.stats.f.cdf(var_samp2 / var_samp1, dfn = num_samp2 - 1, dfd = num_samp1 - 1) print('Calculated p-value :', pcal) # hypothesis testing if pcal < alpha: print('Reject that {}'.format(h0)) else: print('Accept that {}'.format(h0)) # + colab={"base_uri": "https://localhost:8080/"} id="FgtUdCvgFaUQ" outputId="7c467d19-a4dc-45b5-fb03-f49ae860360a" # Input var_samp1 = np.var(poro1) # sample 1 mean var_samp2 = np.var(poro2) # sample 2 mean num_samp1 = 20 # number of sample 1 num_samp2 = 20 # number of sample 2 # Null hypothesis h0 = 'Porosity variance of sample 1 equals to that of sample 2' # Run test ftest_2sample(var_samp1, var_samp2, num_samp1, num_samp2, h0, alpha=0.05) # + [markdown] id="FfGSgPOioZBV" # ## Hypothesis test IV: $\chi^2$ (Chi)-test # + [markdown] id="ePamvjGI1_EV" # Perform test to identify whether data is normally distributed. # + id="5s0PNGOdPxKC" # + [markdown] id="3Aq_hW1J2hc5" # ## Hypothesis test V: with bootstrapping # + [markdown] id="zE0BhD4eHg89" # ## 1D Variogram (principle, code from scratch) # + [markdown] id="ljYBozUbCHP3" # In this part, I'd (only) like to demonstrate the principle of variogram, from plotting experimental (empirical) variogram with the function I built `variogram`, making variogram models (spherical, exponential, gaussian) with `vgm`, and fitting with `fit_variogram`. Applied in 1D (depth) data of porosity log. # # The lag distance between points is assumed to be uniformly 1. In real practice, lag distances are more complicated, and applied in 2D (x and y data). # # The next part, will use `Scikit Gstat` to do variogram analysis. # + id="2_F-MqJ-M1LL" w3429 = np.loadtxt('/content/geostatistics/data/34-29.DAT', skiprows=1) # well 34-29 # poroperm of well 34-29 perm3429, poro3429 = w3429[:,1], w3429[:,2] # + [markdown] id="F-Zx9hlTD1C6" # Plot the empirical (observation) variogram # + id="6wkPbyoj1wqe" def variogram(data, nlag): """ Plot variogram from 1D data """ nn = len(data) sv = np.zeros(nlag) # initialize semivariance h = np.arange(nlag) # lags (distance) for i in range(nlag): data1 = data[:nn-i-1] data2 = data[(i+1):nn] data3 = (data1 - data2)**2 sv[i] = 0.5 * np.mean(data3) # semivariance vv = h, sv # output return vv # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="fjjmPM0tXqRp" outputId="4bcb25d1-227e-4153-de40-985945c084c0" # Plot variogram, give cutoff nlag=25 vv = variogram(poro3429, nlag=25) plt.scatter(vv[0], vv[1]) plt.title('Observation Variogram') plt.xlabel('Lag'); plt.ylabel('Semivariance') plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="3N55nVTIGv8c" outputId="4ec19045-a1f6-47bc-c856-<KEY>" a=[0,1,2,3,4,5,6,7] a[:3+1] # Range 3, <= a[3+1:] # + [markdown] id="EkETqmTpD8t8" # Make variogram models. Reference for models [here](https://geostat-framework.readthedocs.io/projects/pykrige/en/stable/variogram_models.html) # + id="X6ZvdI5n2k7O" def vgm(psill, range, nlag, model, nugget=0): """ Plot variogram model """ h = np.linspace(0, nlag, 100) # lags (distance) if model=='Exp': sv = nugget + psill * (1 - np.exp(-h / (range / 3))) if model=='Gau': sv = nugget + psill * (1 - np.exp(-h**2 / (4 * range / 7)**2)) vm = h, sv return vm # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="zmwTQq0r4EGG" outputId="265d0a15-cd73-41a7-82d8-1f5aa4d20f26" # Plot experimental variogram, give cutoff nlag=25 vv = variogram(poro3429, nlag=25) plt.scatter(vv[0], vv[1], label='Observation') # Create variogram models and approach the experimental variogram vm1 = vgm(psill=35, range=10, nlag=25, model='Gau', nugget=5) vm2 = vgm(psill=35, range=10, nlag=25, model='Exp', nugget=5) plt.plot(vm1[0], vm1[1], color='red', label='Gau Model') plt.plot(vm2[0], vm2[1], color='purple', label='Exp Model') plt.title('Variogram') plt.xlabel('Lag'); plt.ylabel('Semivariance') plt.legend() plt.show() # + [markdown] id="T_3gO4EvD-tj" # Fit variogram models to observation variogram. # + id="ykazG_eGDzDi" def fit_variogram(vv, model): """ Fit experimental variogram with model """ from scipy.optimize import curve_fit h, sv_obs = vv def vgm_exp(h, psill, range, nugget): sv = nugget + psill * (1 - np.exp(-h / (range / 3))) return sv def vgm_gau(h, psill, range, nugget): sv = nugget + psill * (1 - np.exp(-h**2 / (4 * range / 7)**2)) return sv if model=='Exp': [psill, range, nugget], pcov = curve_fit(vgm_exp, h, sv_obs) if model=='Gau': [psill, range, nugget], pcov = curve_fit(vgm_gau, h, sv_obs) return psill, range, nugget # optimum parameters # + [markdown] id="3pM5NeDuQGct" # Fit with Gaussian model # + colab={"base_uri": "https://localhost:8080/", "height": 364} id="2kJjBeGiNvBZ" outputId="ae758ad6-d575-407b-f29e-04babafa9a8d" # Plot experimental variogram, give cutoff nlag=25 vv = variogram(poro3429, nlag=25) plt.scatter(vv[0], vv[1], label='Observation') # Fit variogram model to experimental variogram model = 'Gau' psill_best, range_best, nugget_best = fit_variogram(vv, model=model) print('Best parameters for {} model'.format(model)) print('Best partial sill : {}'.format(np.round(psill_best, 3))) print('Best range : {}'.format(np.round(range_best, 3))) print('Best nugget : {}'.format(np.round(nugget_best, 3))) # Plot variogram model with the best parameters vm = vgm(psill=psill_best, range=range_best, nlag=25, model=model, nugget=nugget_best) plt.plot(vm[0], vm[1], color='red', label='{} Model'.format(model)) plt.title('Variogram') plt.xlabel('Lag'); plt.ylabel('Semivariance') plt.legend() plt.show() # + [markdown] id="-g1a9DSMQN0L" # Fit with Exponential model # + colab={"base_uri": "https://localhost:8080/", "height": 364} id="0wtUgEqhQKE5" outputId="eb8719a1-d185-4eee-fecc-03a89e9ede48" # Plot experimental variogram, give cutoff nlag=25 vv = variogram(poro3429, nlag=25) plt.scatter(vv[0], vv[1], label='Observation') # Fit variogram model to experimental variogram model = 'Exp' psill_best, range_best, nugget_best = fit_variogram(vv, model=model) print('Best parameters for {} model'.format(model)) print('Best partial sill : {}'.format(np.round(psill_best, 3))) print('Best range : {}'.format(np.round(range_best, 3))) print('Best nugget : {}'.format(np.round(nugget_best, 3))) # Plot variogram model with the best parameters vm = vgm(psill=psill_best, range=range_best, nlag=25, model=model, nugget=nugget_best) plt.plot(vm[0], vm[1], color='purple', label='{} Model'.format(model)) plt.title('Variogram') plt.xlabel('Lag'); plt.ylabel('Semivariance') plt.legend() plt.show() # + [markdown] id="6tKAZfOXR01y" # ## 2D Variogram (using Scikit-Gstat) # + [markdown] id="8XA0KqvfYtyd" # After knowing the principle, let's more to a more realistic variogram analysis, now in 2D and the lag distances are more complicated (not 1 anymore). # # In R, the lag distance is expressed in the function: `variogram(width=1)`. Previously, we use 1. Now, because we don't exactly know the `width`, in Python, `scikit-gstat` automatically groups the lag distances, what is called as "binning". # # Apply 2D variogram analysis on our x, y, thickness data. # + colab={"base_uri": "https://localhost:8080/"} id="GPJTDhrtSIHt" outputId="379fa2a5-f3c2-4583-9eb0-a8e3000676df" # !pip install scikit-gstat # + id="ThHtu4gxkpaH" import skgstat # + id="3pR03OxVldhA" # load depth dataset depth = np.loadtxt('/content/geostatistics/data/dpth.txt', skiprows=1) x, y, z = depth.T coords = list(zip(x, y)) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="NWwS0Sxwq3EH" outputId="3665ba76-8731-49fd-dc4e-bb30aed3e84c" plt.scatter(x, y, c=z) plt.title('Scatter Plot') plt.xlabel('x'); plt.ylabel('y') plt.colorbar() plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 453} id="slR83vVGnjWf" outputId="58b77cea-d4e1-4fed-d337-2dcf17a75e42" # Calculate semivariance using skgstat vv = skgstat.Variogram(coords, z, n_lags=20, use_nugget=True) print('Lag distances (bins) on the x-axis :', vv.bins) print('Semivariances on the y-axis :', vv.experimental) # Plot variogram vv.plot(hist=False) plt.title('Variogram') plt.show() # + [markdown] id="B3K9XKFhy9pX" # Fit the variogram. # + colab={"base_uri": "https://localhost:8080/", "height": 381} id="--RV74PPuDzf" outputId="44f11bd6-f288-47e2-e4ac-0251d2bd4605" # Specify inputs for fitting vv.estimator = 'matheron' vv.model = 'gaussian' vv.fit_method = 'trf' # Trust Region Reflective optimizing method (default) # another is `lm` or Levenberg-Marquardt (used in scipy.curve_fit) # however, for this case, 'lm' is not too good vv.plot(hist=False) plt.title('Fitted Variogram') vv.describe() # + [markdown] id="uI3YYpqJzQQ6" # Do variogram analysis on another dataset from [<NAME>'s]() geostatsmodel repository. # + colab={"base_uri": "https://localhost:8080/", "height": 349} id="xGyAao-ky5pq" outputId="f2471a09-9d7b-43d6-dc61-35f0361c8619" filepath = 'https://raw.githubusercontent.com/cjohnson318/geostatsmodels/master/data/ZoneA.dat' zoneA = np.loadtxt(filepath, skiprows=10) x, y, poro = zoneA[:,0], zoneA[:,1], zoneA[:,3] coords = list(zip(x, y)) column_names = ["x", "y", "thk", "por", "perm", "log-perm", "log-perm-prd", "log-perm-rsd"] df = pd.DataFrame(zoneA, columns=column_names) df.head(10) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="CJf_cnlS1QfL" outputId="6f05536f-f85b-4f15-e7ad-9b5bafc10da3" plt.scatter(x, y, c=poro, cmap='jet') plt.title('Scatter Plot') plt.xlabel('x'); plt.ylabel('y') plt.colorbar() plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 520} id="2zbEbEaN1Wxp" outputId="aa4a7ab9-6a79-4d44-efdb-52a5663135bf" # Calculate semivariance using skgstat vv = skgstat.Variogram(coords, poro, n_lags=30, maxlag=10000, use_nugget=True) print('Lag distances (bins) on the x-axis :', vv.bins) print('Semivariances on the y-axis :', vv.experimental) # Plot variogram vv.plot(hist=False) plt.title('Variogram') plt.show() # + [markdown] id="1X8ZrJq-Ofa0" # Variogram models in `Scikit-gstat` are spherical, exponent, Gaussian, Matern, Stable, and cubic. # + colab={"base_uri": "https://localhost:8080/", "height": 399} id="SN4rLi1Z2M53" outputId="7686920a-c873-42a6-b676-a00e1ea00829" # Specify inputs for fitting vv.estimator = 'matheron' vv.model = 'matern' vv.fit_method = 'trf' # Trust Region Reflective optimizing method (default) # another is `lm` or Levenberg-Marquardt (used in scipy.curve_fit) # however, for this case, 'lm' is not too good vv.plot(hist=False) plt.title('Fitted Variogram') vv.describe() # + [markdown] id="AV3ZWfSkNffe" # ## 2D Variogram (directional variogram) # + [markdown] id="ToBK7iYMN7De" # ## Ordinary Kriging # + [markdown] id="Whb1T2OjS4Xn" # Again using `Scikit-gstat` to perform ordinary kriging on the previously fitted variogram. # + id="iMmeKMqDTTWa" ok = skgstat.OrdinaryKriging(vv, min_points=5, max_points=10, mode='exact') # + colab={"base_uri": "https://localhost:8080/"} id="KpxqZGiUU050" outputId="cc76a18c-ba2a-4acb-b7da-00d79b9fe35d" # build the target grid xx, yy = np.mgrid[0:99:100j, 0:99:100j] # field = ok.transform(xx.flatten(), yy.flatten()).reshape(xx.shape) # s2 = ok.sigma.reshape(xx.shape) yy # + colab={"base_uri": "https://localhost:8080/"} id="Rc7sIVpTVbvY" outputId="e7f33978-31c1-493e-cd31-77ad8ea9d526" x = np.linspace(0, 16000, 100) y = np.linspace(0, 20000, 100) xx, yy = np.meshgrid(x, y) field = ok.transform(xx.flatten(), yy.flatten()).reshape(xx.shape) # + colab={"base_uri": "https://localhost:8080/", "height": 271} id="YhrzizSjWL3a" outputId="39519cc9-4690-4ef3-adf1-7546c7ad1b27" plt.matshow(field.T, extent=(0, 20000, 0, 16000), origin='lower', cmap='jet') plt.colorbar()
project_notebooks/geostatistics_with_python.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #Covid Sitution Analysis Statewise ICU Beds # - import pandas as pd import numpy as np # %matplotlib inline from plotly import __version__ from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import cufflinks as cf init_notebook_mode(connected=True) cf.go_offline() df = pd.read_csv('ICU-beds-statewise.csv') df.head() df.iplot(kind='scatter',x='States',y='Total',mode='markers',size=10) df.iplot(kind='bar',x='States',y='Total',size=2) # + #df[['Number of hospitals in public sector','Number of hospitals in private sector']].iplot(kind='spread') # - df.iplot(kind='bubble',x='Number of hospitals in public sector',y='Number of hospitals in private sector',size='Total',xTitle='Public Hospital',yTitle='Private Hospital',title='Hospital Difference in Private vs Public Sector Statewise')
Covid-19-India-ICU-Beds.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import operator from collections import defaultdict from typing import Callable from dataclasses import dataclass, field operators = { 'inc': operator.add, 'dec': operator.sub, } comparisons = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt, } def parse_op(op): reg, op, value = op.split() value = int(value) op = operators[op] return lambda registers: operator.setitem( registers, reg, op(registers[reg], value)) or registers[reg] def parse_cond(cond): reg, cond, target = cond.split() target = int(target) cond = comparisons[cond] return lambda registers: cond(registers[reg], target) @dataclass class Instruction(object): line: str operation: Callable[[dict], int] condition: Callable[[dict], bool] @classmethod def from_line(cls, line): line = line.strip() instr, cond = line.split('if') return cls(line, parse_op(instr.strip()), parse_cond(cond.strip())) def execute(self, registers): if self.condition(registers): return self.operation(registers) return 0 def read_program(lines): return [Instruction.from_line(l) for l in lines if l.strip()] def largest_register_value(program): registers = defaultdict(int) return ( max(instr.execute(registers) for instr in program), max(registers.values()) ) test_program = read_program('''\ b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10 '''.splitlines()) assert largest_register_value(test_program) == (10, 1) # + import aocd data = aocd.get_data(day=8, year=2017) program = read_program(data.splitlines()) # - high_water_line, final_max = largest_register_value(program) print('Part 1:', final_max) print('Part 2:', high_water_line)
2017/Day 08.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Cifar10 Drift Detection with NVIDIA Triton # # In this example we will deploy an image classification model along with a drift detector trained on the same dataset. For in depth details on creating a drift detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/cd_ks_cifar10.html) as well. # # # Prequisites: # # * [Knative eventing installed](https://knative.dev/docs/install/) # * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) # * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) # * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` # * A cluster with NVIDIA GPUs available compatible with Triton Inference Server. # # Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 # !pip install -r requirements_notebook.txt # Ensure gateway installed # !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml # ## Setup Resources # !kubectl create namespace cifar10drift # %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10drift # !kubectl create -f broker.yaml # + # %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10drift spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10drift spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 # - # !kubectl apply -f event-display.yaml # Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. # %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: triton-cifar10 namespace: cifar10drift spec: predictors: - componentSpecs: - metadata: {} spec: containers: - image: nvcr.io/nvidia/tritonserver:20.08-py3 name: cifar10 resources: limits: cpu: "1" memory: 20Gi nvidia.com/gpu: "1" requests: cpu: "1" memory: 10Gi nvidia.com/gpu: "1" graph: implementation: TRITON_SERVER logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10drift/default modelUri: gs://seldon-models/triton/tf_cifar10 name: cifar10 type: MODEL name: default replicas: 1 protocol: kfserving # !kubectl apply -f cifar10.yaml # Create the pretrained Drift Detector. We forward replies to the message-dumper we started. Notice the `drift_batch_size`. The drift detector will wait until `drify_batch_size` number of requests are received before making a drift prediction. # %%writefile cifar10cd.yaml apiVersion: serving.knative.dev/v1 kind: Service metadata: name: drift-detector namespace: cifar10drift spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.6.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10cd - --http_port - '8080' - --protocol - kfserving.http - --storage_uri - gs://seldon-models/alibi-detect/cd/ks/cifar10-0_4_4 - --reply_url - http://hello-display.cifar10drift - --event_type - io.seldon.serving.inference.drift - --event_source - io.seldon.serving.cifar10cd - DriftDetector - --drift_batch_size - '5000' # !kubectl apply -f cifar10cd.yaml # Create a Knative trigger to forward logging events to our Outlier Detector. # %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: drift-trigger namespace: cifar10drift spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: drift-detector namespace: cifar10drift # !kubectl apply -f trigger.yaml # Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) # If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following # + #CLUSTER_IP="localhost:8004" # - # Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. TOKEN="<PASSWORD> <<PASSWORD>>" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10drift drift-detector -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_CD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_CD) # + import matplotlib.pyplot as plt import numpy as np import requests import json import tensorflow as tf tf.keras.backend.clear_session() train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'inputs': [{ "name":"input_1", "datatype": "FP32", "shape": [X.shape[0], 32, 32, 3], "data": X.flatten().tolist() }] } headers = { "Authorization":TOKEN, "Content-Type": "application/json" } res = requests.post('http://'+CLUSTER_IP+'/seldon/cifar10drift/triton-cifar10/v2/models/cifar10/infer', json=formData, headers=headers) if res.status_code == 200: j = res.json() y = np.array(j["outputs"][0]["data"]) y.shape = tuple(j["outputs"][0]["shape"]) return [classes[x.argmax()] for x in y] else: print("Failed with ",res.status_code) return [] def drift(X): formData = { 'inputs': [{ "name":"input_1", "datatype": "FP32", "shape": [1, 32, 32, 3], "data": X.flatten().tolist() }] } headers = {} headers = { "ce-namespace": "default","ce-modelid":"cifar10drift","ce-type":"io.seldon.serving.inference.request", \ "ce-id":"1234","ce-source":"localhost","ce-specversion":"1.0"} headers["Host"] = SERVICE_HOSTNAME_CD headers["Authorization"] = TOKEN res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() return od else: print("Failed with ",res.status_code) return [] # - # ## Normal Prediction idx = 1 X = X_train[idx:idx+1] show(X) predict(X) # ## Test Drift # We need to accumulate a large enough batch size so no drift will be tested as yet. # !kubectl logs -n cifar10drift $(kubectl get pod -n cifar10drift -l app=hello-display -o jsonpath='{.items[0].metadata.name}') # We will now send 5000 requests to the model in batches. The drift detector will run at the end of this as we set the `drift_batch_size` to 5000 in our yaml above. from tqdm.notebook import tqdm for i in tqdm(range(1,5000,500)): X = X_train[i:i+500] predict(X) # Let's check the message dumper and extract the first drift result. # res=!kubectl logs -n cifar10drift $(kubectl get pod -n cifar10drift -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Drift",j["data"]["is_drift"]==1) # Now, let's create some CIFAR10 examples with motion blur. from alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c corruption = ['motion_blur'] X_corr, y_corr = fetch_cifar10c(corruption=corruption, severity=5, return_X_y=True) X_corr = X_corr.astype('float32') / 255 show(X_corr[0]) show(X_corr[1]) show(X_corr[2]) # Send these examples to the predictor. for i in tqdm(range(0,5000,500)): X = X_corr[i:i+500] predict(X) # Now when we check the message dump we should find a new drift response. # res=!kubectl logs -n cifar10drift $(kubectl get pod -n cifar10drift -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Drift",j["data"]["is_drift"]==1) # ## Tear Down # !kubectl delete ns cifar10drift
components/drift-detection/nvidia-triton-cifar10/cifar10_drift.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Fixed and Random Effect Models: Identifying Relationships of Individuals Within and Between Groups # #### by [<NAME>](https://twitter.com/natematias), April 21, 2015 # # *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.* # # ## About Random Effects Models # In random effects models, we are fitting a model that includes [panel data](http://en.wikipedia.org/wiki/Panel_data), either multiple observations for an individual, or multiple observations like a group. # # Why do we use a different approach in this case? Groups and individuals are great examples of cases where the linear regression assumption of "*independence of observations*" does not apply. Imagine if we have observations of students from several schools. Observations of students*(level 1)* are not all independent from each other; we can assume that some of the variation in the observations comes from unobserved variables that students share within the same school, and that school experiences differ from each other at the group level*(level 2)* in ways that aren't observed in our dataset. Multilevel models allow us to account for the variation between individuals and also the variation between groups. # # Another use of Multilevel models is to model change, where we have observations from many individuals over time and we want to identify change over time. The individual observed events are grouped by the person in question. # # # ## Dataset # The dataset used here is a classic pedagogical dataset, from the [High School and Beyond study](https://nces.ed.gov/surveys/hsb/) by the National Center for Education Statistics, which followed high school students starting in 1980, continuing through 1982, 1984, 1986, and 1992. [The High School and Beyond study has its own wikipedia page](http://en.wikipedia.org/wiki/High_School_and_Beyond), which includes 48 published studies based on the data. # # ## Research Question: Do Catholic Schools and Students in Catholic Schools have Different Math Achievement from Public Schools, when Controlling For SES? # This example is drawn from the work of <NAME> and <NAME>, from class examples in the [S-052 class](http://my.gse.harvard.edu/course/gse-s052) at the Harvard Graduate School of Education. It also roughly follows the course of Chapters 3 and 4 of Singer, <NAME>., Willett, <NAME>. (2003) [Applied Longitudinal Data Analysis: Modeling Change and Event Occurrence](http://www.ats.ucla.edu/stat/examples/alda.htm). Oxford University Press. # # * **important note**: *The [MixedLM library](http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.mixed_linear_model.MixedLM.html) in statsmodels is relatively recent, so many of the methods outlined by the above authors are not yet possible in Python, notably analysis of variance components of the models and intra-class correlation. There is a Google Summer of Code proposal for 2015 to [add variance components to MixedLM](https://github.com/statsmodels/statsmodels/wiki/GSoC-2015-Proposal:-Improvements-to-Mixed-Effects-Models), but the announcement was 5 days away when I published this, so we shall have to see. Let's hope it works out. The approach taken here is the likelihood-based approach. Statsmodels [MixedLM can also be used with a Generalized Estimating Equation (GEE) approach](http://nbviewer.ipython.org/urls/umich.box.com/shared/static/lc6uf6dmabmitjbup3yt.ipynb).* # * For the Bayesian approach to multilevel methods, [<NAME>](http://biostat.mc.vanderbilt.edu/wiki/Main/ChrisFonnesbeck), assistant prof of biostatistics at Vanderbilt, has published a notebook showing how to do [Bayesian multilevel modeling with pymc](http://nbviewer.ipython.org/github/fonnesbeck/multilevel_modeling/blob/master/multilevel_modeling.ipynb).* # # # In this study, we want to know if catholic schools and public schools (and individual students in those schools) differ in their math achievement, when controlling for SES. In order to answer this question, we turn to a random effects model, which assumes that: # * the basic assumptions of linear regression # * the individual residuals (error) are normally distributed in the population # * the group residuals (error) are normally distributed in the population # # It's this final assumption that when satisfied allows us to make claims about the population of groups, and not just the groups represented in this dataset. The population model for a random effects model is: # # $$y_{ij} = \beta_{0} + \beta_{1}X_{ij} + u_{j} + \epsilon_{ij}$$ # $$u_{j} \space \widetilde\space \space i.i.d. N(0, \sigma^{2}_{u})$$ # $$\epsilon_{ij} \space \widetilde\space \space i.i.d. N(0, \sigma^{2}_{\epsilon})$$ # THINGS TO IMPORT # This is a baseline set of libraries I import by default if I'm rushed for time. # %matplotlib inline import codecs # load UTF-8 Content import json # load JSON files import pandas as pd # Pandas handles dataframes import numpy as np # Numpy handles lots of basic maths operations import matplotlib.pyplot as plt # Matplotlib for plotting import seaborn as sns # Seaborn for beautiful plots from dateutil import * # I prefer dateutil for parsing dates import math # transformations import statsmodels.formula.api as smf # for doing statistical regression import statsmodels.api as sm # access to the wider statsmodels library, including R datasets from collections import Counter # Counter is useful for grouping and counting import scipy from patsy import dmatrices # + # High School and Beyond Dataset # https://nces.ed.gov/surveys/hsb/ import urllib2 import os.path if(os.path.isfile("hsb.dta")!=True): response = urllib2.urlopen("http://www.stata-press.com/data/mlmus3/hsb.dta") if(response.getcode()==200): f = open("hsb.dta","w") f.write(response.read()) f.close() hsb_df = pd.read_stata("hsb.dta") print hsb_df[['mathach','ses']].describe() print print "CROSSTAB" print pd.crosstab(hsb_df['sector'], [hsb_df['female'],hsb_df['minority']]) # - # # Exploring Within-Group Variation and Between-Group Variation # Multilevel models make sense in cases where we might expect there to be variation between groups (*or in the time case, variation/differences between individuals across multible observations*). # # * *Within group variation*: the amount of variation attributable to individuals within a group # * *Between group variation*: the amount of variation attributable between groups # # One way to explore within and between group variation is to do boxplots of the outcome by group. When looking at the first plot, we try to gain an intuitive sense of how much the outcome varies by group and how much it varies within groups. In this case, it's not obvious that there are many differences between groups, since so many of the error bars overlap, so we'll have to find another way to assert that difference. # # In the second plot, we show the de-meaned math achievement, which allows us to look at the variation within schools, next to each other. # > *Note that the Pandas boxplot method only shows us the median line, which is why there's some jitter in the second plot. (Matplotlib apparently allows us to specify the mean with meanline=True, but I couldn't get the argument to pass through from Pandas.)* # + #generate de-meaned mathach sgp = school_gp.to_dict() def school_mathach(f): return float(f.mathach) - sgp['mathach'][f.schoolid] hsb_df['school_mathach'] = hsb_df.apply(school_mathach, 1) #make the Side-by-Side Boxplot fig = plt.figure(num=None, figsize=(8, 20), dpi=80, edgecolor='k') ax = fig.add_subplot(121) hsb_df.boxplot("mathach", by="schoolid", ax=ax, vert=False) plt.title("School Math Achievement", fontsize="16") ax2 = fig.add_subplot(122) hsb_df.boxplot("school_mathach", by="schoolid", ax=ax2, vert=False) plt.title("De-Meaned School Math Achievement", fontsize="16") plt.show() # - # # Predicting Math Achievement from SES with Linear Models # Another way to look at the group variation, let's compare two basic linear models, one of individual students, one with school means. In the following linear models, we see that there is there is indeed a relationship between SES and math achivement **between school mean math achievement**. However, just as the student-level model doesn't explain the group-level variation between schools, the school-level model doesn't explain the individual-level variation within schools. This is especially evident at high and low levels of SES or math achievement, where the group level model doesn't extend. # + result = smf.ols(formula = "mathach ~ ses", data = hsb_df).fit() print "===========================================================" print "MODEL 1: Regressing Student Math Achievement on Student SES" print result.summary() plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') plt.scatter(hsb_df.ses, hsb_df.mathach, marker=".", color="c") student_line, = plt.plot(hsb_df['ses'], result.predict(), "-", color="c") #plt.title("Predicting Math Achievement from SES Across all 7185 students", fontsize="16") school_gp = hsb_df.groupby("schoolid").aggregate(np.mean) result = smf.ols(formula = "mathach ~ ses", data = school_gp).fit() print print "===================================================================" print "MODEL 2: Regressing Mean School Math Achievement on Mean School SES" print result.summary() #plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') plt.scatter(school_gp.ses, school_gp.mathach, marker=".", color="r") school_line, = plt.plot(school_gp.ses, result.predict(), "-", color="r") plt.title("Predicting Math Achievement Scores from SES with Linear Regression", fontsize="16") plt.legend([student_line, school_line], ['All Students', 'School Means'], fontsize="14") plt.show() # - # # Fixed Effect Model: Predicting Math Achievement with De-Meaned SES # In the fixed effects model, we add $u_{j}$ to the model, denoting the group level variance, absorbing all the variance between groups in order to better estimate the variance within groups. # # $$y_{ij} = \beta_{0} + \beta_{1}X_{ij} + \mathbf{u_{j}} + \epsilon_{ij}$$ # $$\epsilon_{ij} \space \widetilde\space \space i.i.d. N(0, \sigma^{2}_{\epsilon})$$ # # In practice, we can do this in several equivalent ways. I show two here: # * add the school mean SES as a predictor to the model # * replace SES with the "de-meaned" SES rather than the SES as our predictor. In the de-meaned model, instead of using the SES of the individual in the school, we are using amount by which that student differs from the mean SES in the school. # # In both cases, we effectively remove the variation between groups from the model. The resulting SES or demeaned_ses predictor models the within-school variation between students. # # In the following models, notice how the slope for *ses* is the same as the slope for *demeaned_ses* in the two models. # calculate the demeaned_ses for each student def demeaned_ses(f): return f.ses - school_gp.to_dict()['ses'][f['schoolid']] # add the school mean SES to the dataframe for each student def schoolmean_ses(f): return school_gp.to_dict()['ses'][f['schoolid']] hsb_df['demeaned_ses'] = hsb_df.apply(demeaned_ses, axis=1) hsb_df['schoolmean_ses'] = hsb_df.apply(schoolmean_ses, axis=1) # + result_school_covary = smf.ols(formula = "mathach ~ ses + schoolmean_ses", data = hsb_df).fit() print "MODEL: Regressing Student Math Achievement on De-meaned Student SES" print result_school_covary.params result = smf.ols(formula = "mathach ~ demeaned_ses", data = hsb_df).fit() print print "MODEL: Regressing Student Math Achievement on De-meaned Student SES" print result.params print print "Notice how the slope for *ses* is the same as the slope for *demeaned_ses* in the two models" print plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') plt.scatter(hsb_df.demeaned_ses, hsb_df.mathach, marker=".", color="darkgrey") student_line, = plt.plot(hsb_df['demeaned_ses'], result.predict(), "-", color="darkgrey") plt.title("Predicting Math Achievement Scores from De-meaned SES", fontsize="16") plt.xlabel("De-meaned Socio-Economic Status", fontsize="14") plt.ylabel("Math Achivement", fontsize="14") plt.show() # - # ## Plotting the Fixed Effects Model for Individual Schools # We can plot the fixed effects model on a school-level basis using the model that uses the school mean as a covariate and then plotting the model for prototypical values of individual schools. # # It's important to note however that this model makes no claims about the population of all schools -- it just models the relationship between student math achievement and student SES, holding constant the variation in SES between schools. # + # highlight the maximum, and minimum max_school = school_gp[school_gp['ses'] == school_gp.ses.max()].index[0] min_school = school_gp[school_gp['ses'] == school_gp.ses.min()].index[0] hsb_df['fixed_preds'] = result_school_covary.predict() plt.figure(num=None, figsize=(12, 6), dpi=80, edgecolor='k') for schoolid in hsb_df.schoolid.unique(): if(schoolid!=max_school and schoolid!=min_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="lightgrey") for schoolid in hsb_df.schoolid.unique(): if(schoolid == max_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="r") maxline, = plt.plot(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].fixed_preds, "-", color="r") elif(schoolid == min_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="b") minline, = plt.plot(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].fixed_preds, "-", color="b") plt.legend([maxline, minline], ['School with Max SES', 'School with Min SES'], fontsize="12") plt.title("Fixed Effects Model Predicting Math Achievement Scores from SES & School Mean SES", fontsize="16") plt.xlabel("Socio-Economic Status", fontsize="14") plt.ylabel("Math Achivement", fontsize="14") plt.show() # - # # Random Effects Model # A random effects model makes the assumption that the variance attributable to groups is normal in the population (and centered on 0), allowing us to make claims about groups, and not just individual observations. In the school example, this would allow us to make claims about schools as well as the individuals within them. In a timeseries example, this is equally important, because it's only in the random effects world that we would be able to make claims about the population of things that we're observing over time. Correspondingly, our population model for the random effects model, although it has the same terms of the fixed effects model, has an additional assumption about $u_{j}$: # # $$y_{ij} = \beta_{0} + \beta_{1}X_{ij} + u_{j} + \epsilon_{ij}$$ # $$\mathbf{u_{j} \space \widetilde\space \space i.i.d. N(0, \sigma^{2}_{u})}$$ # $$\epsilon_{ij} \space \widetilde\space \space i.i.d. N(0, \sigma^{2}_{\epsilon})$$ ##http://statsmodels.sourceforge.net/devel/mixed_linear.html md = smf.mixedlm("mathach ~ ses", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() # In the above results, the *ses* coefficient of 2.390 is: # * the slope of the relationship between math achievement and ses among the population of students within a school # * also the slope of the relationship between math achievement and ses among the population of schools (In a timeseries situation, this becomes especially meaningful in cases where we add further covariates that explain differences between individuals over time) # # Comparing Linear, Grouped, De-Meaned, and Mixed Effects Models # For fun, here is a plot that shows all of the models that we have fit so far on the same plot. # + plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') result = smf.ols(formula = "mathach ~ ses", data = hsb_df).fit() print "MODEL 1: Regressing Student Math Achievement on Student SES" plt.scatter(hsb_df.ses, hsb_df.mathach, marker=".", color="c") student_line, = plt.plot(hsb_df['ses'], result.predict(), "-", color="c") school_gp = hsb_df.groupby("schoolid").aggregate(np.mean) result = smf.ols(formula = "mathach ~ ses", data = school_gp).fit() print result.summary() print print "MODEL 2: Regressing Mean School Math Achievement on Mean School SES" print result.summary() #plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') plt.scatter(school_gp.ses, school_gp.mathach, marker=".", color="r") school_line, = plt.plot(school_gp.ses, result.predict(), "-", color="r") result = smf.ols(formula = "mathach ~ demeaned_ses", data = hsb_df).fit() print "MODEL 3: Regressing Student Math Achievement on De-meaned Student SES" print result.summary() #plt.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') demeaned_line, = plt.plot(hsb_df['demeaned_ses'], result.predict(), "-", color="darkgrey") print print "MODEL 4: Regressing Student Math Achievement on Student SES Grouped by School in a Random Effects Model" md = smf.mixedlm("mathach ~ ses", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() def predict(x, key, result): return result.params.Intercept + result.params['ses']*x ses = np.linspace(hsb_df.ses.min(), hsb_df.ses.max(), 100) preds = [predict(x, 'ses',result) for x in ses] multi_line, = plt.plot(ses, preds, "-", color="m") plt.title("Predicting Math Achievement Scores from SES (schools=160) (students=7185)", fontsize="16") plt.legend([student_line, school_line, multi_line, demeaned_line], ['All Students (Total)', 'School Means (Between)', "Random Effects", "De-Meaned (within group, Fixed)"]) plt.show() # - # #Calculate Within Group Variance, Between Group Variance, and Intraclass Correlation of a Random Effects Models # In a random effects model, The **intraclass correlation** can be interpreted as: # * the group variation as a proportion of total variance # * the proportion of overall variation in math scores "accounted for by" the group # # Intraclass correlation is apparently still being debated, as outlined in [the Wikipedia page for intraclass correlation](http://en.wikipedia.org/wiki/Intraclass_correlation), and some people avoid this measure entirely. # # The statsmodels MixedLM model doesn't include within it any analysis of residuals, so of we want to consider the intraclass correlation in the model, we have to do it ourselves. I've written a method to collect the individual and group residuals. # # Note that I *think* the calculations presented here are correct, but I have only run them against a single test case, so you may want to doublecheck my work before lifting this code. # + ##http://statsmodels.sourceforge.net/devel/mixed_linear.html md = smf.mixedlm("mathach ~ ses", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() #store the model results to a variable models = {} m = "Model1" models[m] = {} models[m]['result'] = result def individual_residuals(f): observed_individual = f.mathach predicted_individual = result.params.Intercept + result.params['ses']*f.ses return observed_individual - predicted_individual def group_residuals(f): observed_group = school_gp.to_dict()['mathach'][f.schoolid] predicted_group = result.params.Intercept + result.params['ses']*f.schoolmean_ses return predicted_group - observed_group group_count = school_gp.count()[0] indiv_count = hsb_df.count()[0] resid_u = hsb_df.apply(group_residuals, 1) models[m]["sigma_u"] = np.std(resid_u) models[m]["sigma_u_err"] = models[m]["sigma_u"]/math.sqrt(group_count) resid_e = hsb_df.apply(individual_residuals, 1) models[m]["sigma_e"] = np.std(resid_e) models[m]["sigma_e_err"] = models[m]["sigma_e"]/math.sqrt(indiv_count) models[m]["icc"] = math.pow(models[m]["sigma_u"],2)/(math.pow(models[m]["sigma_u"],2) + math.pow(models[m]["sigma_e"],2)) models[m]["icc_err"] = icc/math.sqrt(group_count) print " stdev stderr" print "sigma_u (between group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_u"], 'e':models[m]["sigma_u_err"]} print "sigma_e (within group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_e"], 'e':models[m]["sigma_e_err"]} print "intraclass correlation: %(i).04f %(e).04f" % {'i':models[m]["icc"], 'e':models[m]["icc_err"]} print print "Z-Test of intraclass correlation:" print " H0: icc = 0 in the population" print " test-statistic: z=icc/SE(icc)" print " decision rule: z>z_crit" print " critical value: 1.96" print " z = %(z).04f" %{'z':models[m]["icc"] /models[m]["icc_err"]} # - # In this case, we see that there is a low intraclass correlation, suggesting that most of the variation in math achievement scores is within schools, but that there is a significant difference between the math achievement of schools on average in the model as well (as indicated by the Z test). # # # Using Pseudo-$R^{2}$ To Describe Changes in Variance Components # If we are interested in differences between the proportion of between-group or within group variance accounted for by competing models, we can generate a pseudo-$R^{2}$ measure by comparing the between and within group variances to those of a baseline model. # + # now generate the baseline model md = smf.mixedlm("mathach ~ 1", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() def individual_residuals(f): observed_individual = f.mathach predicted_individual = result.params.Intercept return observed_individual - predicted_individual def group_residuals(f): observed_group = school_gp.to_dict()['mathach'][f.schoolid] predicted_group = result.params.Intercept return predicted_group - observed_group group_count = school_gp.count()[0] indiv_count = hsb_df.count()[0] m = "Model0" models[m] = {} models[m]['result'] = result resid_u = hsb_df.apply(group_residuals, 1) models[m]["sigma_u"] = np.std(resid_u) models[m]["sigma_u_err"] = models[m]["sigma_u"]/math.sqrt(group_count) resid_e = hsb_df.apply(individual_residuals, 1) models[m]["sigma_e"] = np.std(resid_e) models[m]["sigma_e_err"] = models[m]["sigma_e"]/math.sqrt(indiv_count) models[m]["icc"] = math.pow(models[m]["sigma_u"],2)/(math.pow(models[m]["sigma_u"],2) + math.pow(models[m]["sigma_e"],2)) models[m]["icc_err"] = icc/math.sqrt(group_count) print " stdev stderr" print "sigma_u (between group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_u"], 'e':models[m]["sigma_u_err"]} print "sigma_e (within group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_e"], 'e':models[m]["sigma_e_err"]} print "intraclass correlation: %(i).04f %(e).04f" % {'i':models[m]["icc"], 'e':models[m]["icc_err"]} print print "Z-Test of intraclass correlation:" print " H0: icc = 0 in the population" print " test-statistic: z=icc/SE(icc)" print " decision rule: z>z_crit" print " critical value: 1.96" print " z = %(z).04f" %{'z':models[m]["icc"] /models[m]["icc_err"]} # - # ## Calculating Pseudo-$R^{2}$ # To calculate pseudo-$R^{2}$, we use the following equations: # # Between group variation: $R^{2}_{u} = \sigma_{u,0}^{2} - \sigma_{u,1}^{2}/\sigma_{u,0}^{2}$ # # Within group variation: $R^{2}_{e} = \sigma_{e,0}^{2} - \sigma_{e,1}^{2}/\sigma_{e,0}^{2}$ m0 = "Model0" m1 = "Model1" r2_u = math.pow(models[m0]['sigma_u'], 2) - math.pow(models[m1]['sigma_u'], 2)/math.pow(models[m0]['sigma_u'], 2) print "Pseudo R^2 for group variation: %(r).03f%%" % {'r':r2_u} r2_e = math.pow(models[m0]['sigma_e'], 2) - math.pow(models[m1]['sigma_e'], 2)/math.pow(models[m0]['sigma_e'], 2) print "Pseudo R^2 for individual variation: %(r).03f%%" % {'r':r2_e} # In the above pseudo $R^{2}$ calculations, we see that our model of math achievement on SES accounts for 8.44% of the between-group variation and 46.43% of the within-group variation. This is consistent with our intraclass correlation, which shows that in the model there is much more within-group variation than betwen-group variation. # # Level Two Predictors: Testing Our Hypothesis About Catholic Schools # At the beginning of this example, we asked if Catholic Schools and Students in Catholic Schools have different Math Achievement from Public Schools, when Controlling For SES? To answer this question, we add another predictor, a "level-2," group-level predictor that contains information about schools rather than individual students. # + # in this dataset, sector refers to whether the school is catholic(1) or public(0) from patsy import dmatrices md = smf.mixedlm("mathach ~ ses + sector", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() def individual_residuals(f): observed_individual = f.mathach predicted_individual = result.params.Intercept + result.params['ses']*f.ses + result.params['sector']*f.sector return observed_individual - predicted_individual def group_residuals(f): observed_group = school_gp.to_dict()['mathach'][f.schoolid] predicted_group = result.params.Intercept + result.params['ses']*f.schoolmean_ses + result.params['sector']*f.sector return predicted_group - observed_group group_count = school_gp.count()[0] indiv_count = hsb_df.count()[0] m = "Model2" models[m] = {} models[m]['result'] = result resid_u = hsb_df.apply(group_residuals, 1) models[m]["sigma_u"] = np.std(resid_u) models[m]["sigma_u_err"] = models[m]["sigma_u"]/math.sqrt(group_count) resid_e = hsb_df.apply(individual_residuals, 1) models[m]["sigma_e"] = np.std(resid_e) models[m]["sigma_e_err"] = models[m]["sigma_e"]/math.sqrt(indiv_count) models[m]["icc"] = math.pow(models[m]["sigma_u"],2)/(math.pow(models[m]["sigma_u"],2) + math.pow(models[m]["sigma_e"],2)) models[m]["icc_err"] = icc/math.sqrt(group_count) print " stdev stderr" print "sigma_u (between group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_u"], 'e':models[m]["sigma_u_err"]} print "sigma_e (within group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_e"], 'e':models[m]["sigma_e_err"]} print "intraclass correlation: %(i).04f %(e).04f" % {'i':models[m]["icc"], 'e':models[m]["icc_err"]} print print "Z-Test of intraclass correlation:" print " H0: icc = 0 in the population" print " test-statistic: z=icc/SE(icc)" print " decision rule: z>z_crit" print " critical value: 1.96" print " z = %(z).04f" %{'z':models[m]["icc"] /models[m]["icc_err"]} print m0 = "Model0" m1 = "Model2" r2_u = math.pow(models[m0]['sigma_u'], 2) - math.pow(models[m1]['sigma_u'], 2)/math.pow(models[m0]['sigma_u'], 2) print "Pseudo R^2 for group variation: %(r).03f%%" % {'r':r2_u} r2_e = math.pow(models[m0]['sigma_e'], 2) - math.pow(models[m1]['sigma_e'], 2)/math.pow(models[m0]['sigma_e'], 2) print "Pseudo R^2 for individual variation: %(r).03f%%" % {'r':r2_e} # - # ###Now add an interaction between sector and SES # + # in this dataset, sector refers to whether the school is catholic(1) or public(0) from patsy import dmatrices md = smf.mixedlm("mathach ~ ses + sector + sector:ses", data=hsb_df, groups=hsb_df["schoolid"]) result = md.fit() print result.summary() def individual_residuals(f): observed_individual = f.mathach predicted_individual = result.params.Intercept + result.params['ses']*f.ses + result.params['sector']*f.sector + result.params['sector:ses']*f.sector*f.ses return observed_individual - predicted_individual def group_residuals(f): observed_group = school_gp.to_dict()['mathach'][f.schoolid] predicted_group = result.params.Intercept + result.params['ses']*f.schoolmean_ses + result.params['sector']*f.sector + result.params['sector:ses']*f.sector*f.ses return predicted_group - observed_group group_count = school_gp.count()[0] indiv_count = hsb_df.count()[0] m = "Model3" models[m] = {} models[m]['result'] = result resid_u = hsb_df.apply(group_residuals, 1) models[m]["sigma_u"] = np.std(resid_u) models[m]["sigma_u_err"] = models[m]["sigma_u"]/math.sqrt(group_count) resid_e = hsb_df.apply(individual_residuals, 1) models[m]["sigma_e"] = np.std(resid_e) models[m]["sigma_e_err"] = models[m]["sigma_e"]/math.sqrt(indiv_count) models[m]["icc"] = math.pow(models[m]["sigma_u"],2)/(math.pow(models[m]["sigma_u"],2) + math.pow(models[m]["sigma_e"],2)) models[m]["icc_err"] = icc/math.sqrt(group_count) print " stdev stderr" print "sigma_u (between group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_u"], 'e':models[m]["sigma_u_err"]} print "sigma_e (within group variation): %(s).04f %(e).04f" % {'s':models[m]["sigma_e"], 'e':models[m]["sigma_e_err"]} print "intraclass correlation: %(i).04f %(e).04f" % {'i':models[m]["icc"], 'e':models[m]["icc_err"]} print print "Z-Test of intraclass correlation:" print " H0: icc = 0 in the population" print " test-statistic: z=icc/SE(icc)" print " decision rule: z>z_crit" print " critical value: 1.96" print " z = %(z).04f" %{'z':models[m]["icc"] /models[m]["icc_err"]} print m0 = "Model0" m1 = "Model3" r2_u = math.pow(models[m0]['sigma_u'], 2) - math.pow(models[m1]['sigma_u'], 2)/math.pow(models[m0]['sigma_u'], 2) print "Pseudo R^2 for group variation: %(r).02f%%" % {'r':r2_u} r2_e = math.pow(models[m0]['sigma_e'], 2) - math.pow(models[m1]['sigma_e'], 2)/math.pow(models[m0]['sigma_e'], 2) print "Pseudo R^2 for individual variation: %(r).02f%%" % {'r':r2_e} # - # # Plotting the Random Effects Model with a Level 2 Interaction # ## Showing Predictions of Students in Prototypical Schools # + #step one: find prototypical values of a catholic and a public school with an SES of 0. school_gp['p_abs_ses']=school_gp[np.isclose(school_gp.sector, 0.)].ses.map(lambda x: abs(x)) school_gp['c_abs_ses']=school_gp[np.isclose(school_gp.sector, 1.)].ses.map(lambda x: abs(x)) #public school with SES closest to 0: 1946 print school_gp[(np.isclose(school_gp.p_abs_ses,school_gp.p_abs_ses.min())) & (np.isclose(school_gp.sector, 0.))].ses #catholic school with SES closest to 0: 5650 print school_gp[(np.isclose(school_gp.c_abs_ses,school_gp.c_abs_ses.min())) & (np.isclose(school_gp.sector, 1.))].ses p_school = 1946 c_school = 5650 def predict(f): return result.params.Intercept + result.params['ses']*f.ses + result.params['sector']*f.sector + result.params['sector:ses']*f.sector*f.ses hsb_df['interaction_preds'] = hsb_df.apply(predict, 1) plt.figure(num=None, figsize=(12, 6), dpi=80, edgecolor='k') # PLOT A PREDICTION OF INDIVIDUAL MATH ACHIEVEMENT SCORES # FOR TWO SCHOOLS for schoolid in hsb_df.schoolid.unique(): if(schoolid!=max_school and schoolid!=min_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="lightgrey") for schoolid in hsb_df.schoolid.unique(): if(schoolid == p_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="r") p_line, = plt.plot(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].interaction_preds, "-", color="r") elif(schoolid == c_school): plt.scatter(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].mathach, marker=".", color="b") c_line, = plt.plot(hsb_df[hsb_df.schoolid == schoolid].ses, hsb_df[hsb_df.schoolid == schoolid].interaction_preds, "-", color="b") plt.legend([c_line, p_line], ['Students in a Catholic School with Mean SES', 'Students in a Public School with Mean SES'], fontsize="12") plt.suptitle("Predicting Individual Math Achievement Scores from SES & Sector", fontsize="16") plt.title("in a Multi-Level Random Effects Model, where SES=0", fontsize="16") plt.xlabel("Socio-Economic Status", fontsize="14") plt.ylabel("Math Achivement", fontsize="14") plt.show() # - # ## Plot Predictions for Catholic and Public Schools # + # PLOT SCHOOL MEAN CATHOLIC AND PUBLIC SCHOOL MATH ACHIEVEMENT plt.figure(num=None, figsize=(12, 6), dpi=80, edgecolor='k') plt.scatter(hsb_df.ses, hsb_df.mathach, marker=".", color="lightgrey") plt.scatter(school_gp[school_gp.sector==0.].ses, school_gp[school_gp.sector==0.].mathach, color="r") plt.scatter(school_gp[school_gp.sector==1.].ses, school_gp[school_gp.sector==1.].mathach, color="b") school_gp['interaction_preds'] = school_gp.apply(predict, 1) c_line, = plt.plot(school_gp[np.isclose(school_gp.sector, 1.)].ses, school_gp[np.isclose(school_gp.sector, 1.)].interaction_preds, "-", color="b") p_line, = plt.plot(school_gp[np.isclose(school_gp.sector, 0.)].ses, school_gp[np.isclose(school_gp.sector, 0.)].interaction_preds, "-", color="r") plt.suptitle("Predicting School Math Achievement Scores from SES & Sector", fontsize="16") plt.title("in a Multi-Level Random Effects Model", fontsize="16") plt.legend([c_line, p_line], ['Catholic Schools', 'Public Schools'], fontsize="12") plt.xlabel("Socio-Economic Status", fontsize="14") plt.ylabel("Math Achivement", fontsize="14") plt.show() # - # # So What's the Answer? Is there a difference in math achievement between Catholic and Public Schools? # In the random effects model we specified, the answer is yes. We see a significant difference between catholic and public school math achievement on average in the population (a claim supported by our RE model), and that this relationship is mediated by SES. *here's where we would then go on to identify prototypical values and talk about the difference between a public and catholic schools at various levels of SES, etc*
multilevel_models/Multilevel Models.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import random import datetime as dt import polaris polaris.iniciar('polaris.ini') from polaris.globais import bd from polaris.logistica import ( PontoMovimentacao, CadeiaLogistica ) from polaris.materiais import( ProdutoPortifolio ) from polaris.abastecimento import( EtapaBase, EtapaAbastecimento, FluxoAbastecimento, Sugestao, ItemSugestao, OrdemAbastecimento, ItemOrdemAbastecimento ) # - # Ativar PDMS inativos _sessao = bd.abrir_sessao_escrita() _sessao.query(PontoMovimentacao).update({PontoMovimentacao.ativo:True}, synchronize_session=False) _sessao.commit() _sessao.close() # + _sessao = bd.abrir_sessao_escrita() # Capturando lojas destinos - H048 _fornecedor = _sessao.query(PontoMovimentacao).filter(PontoMovimentacao.codigo_externo == "H001").first() _cliente = _sessao.query(PontoMovimentacao).filter(PontoMovimentacao.codigo_externo == "H014").first() # - # Configurando cadeia de fornecimento if not _cliente.cadeia_fornecimentos.filter(CadeiaLogistica._id_fornecedor == _fornecedor.id).first(): _cliente.inserir_cadeia_fornecimento(_fornecedor, _fornecedor.lead_time, [], portifolio_integral = True) # Pegando cadeia de fornecimento _cadeia_fornecimento = _cliente.cadeia_fornecimentos.filter_by(_id_fornecedor = _fornecedor.id).first() # Capturando etapas cadastradas _etp_sug = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "1").first() _etp_mod = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "6").first() _etp_lib = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "7").first() _etp_ped = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "2").first() _etp_fat = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "5").first() _etp_ent = _sessao.query(EtapaBase).filter(EtapaBase.codigo_externo == "4").first() # Configurando grade de abastecimento _grade = [ (dt.date(2017,9,28), dt.date(2017,9,28), dt.date(2017,9,29), dt.date(2017,9,29), dt.date(2017,9,30), dt.date(2017,10,2)), (dt.date(2017,10,1), dt.date(2017,10,1), dt.date(2017,10,2), dt.date(2017,10,2), dt.date(2017,10,3), dt.date(2017,10,3)), (dt.date(2017,10,3), dt.date(2017,10,3), dt.date(2017,10,4), dt.date(2017,10,4), dt.date(2017,10,5), dt.date(2017,10,6)), (dt.date(2017,10,5), dt.date(2017,10,5), dt.date(2017,10,6), dt.date(2017,10,6), dt.date(2017,10,7), dt.date(2017,10,9)), (dt.date(2017,10,8), dt.date(2017,10,8), dt.date(2017,10,9), dt.date(2017,10,9), dt.date(2017,10,10), dt.date(2017,10,11)), (dt.date(2017,10,10), dt.date(2017,10,10), dt.date(2017,10,11), dt.date(2017,10,11), dt.date(2017,10,12), dt.date(2017,10,13)) ] # Condicionando uma cadeia valida if _cadeia_fornecimento: # Inserindo fluxos nas datas estipuladas for g in _grade: # Desmembrando datas _dt_sug, _dt_mod, _dt_lib, _dt_ped, _dt_fat, _dt_ent = g # Criando novo fluxo _fluxo_abastecimento = FluxoAbastecimento(solicitante = _cadeia_fornecimento.cliente, fornecedor = _cadeia_fornecimento.fornecedor, produtos = list(_cadeia_fornecimento.portifolio)) # Adicionando etapas datadas no fluxo _fluxo_abastecimento.etapas.append(_etp_sug, posicao = 1, data = _dt_sug) _fluxo_abastecimento.etapas.append(_etp_mod, posicao = 2, data = _dt_mod) _fluxo_abastecimento.etapas.append(_etp_lib, posicao = 3, data = _dt_lib) _fluxo_abastecimento.etapas.append(_etp_ped, posicao = 4, data = _dt_ped) _fluxo_abastecimento.etapas.append(_etp_fat, posicao = 5, data = _dt_fat) _fluxo_abastecimento.etapas.append(_etp_ent, posicao = 6, data = _dt_ent) # Persistindo fluxo no banco _sessao.add(_fluxo_abastecimento) _sessao.commit() # + # Capturando um fluxo especifico _fluxo = _sessao.query(FluxoAbastecimento).filter(FluxoAbastecimento.codigo_interno == "297847293974892333").first() # Capturando uma respectiva etapa dentro do fluxo _etapa_sugestao = (_sessao.query(EtapaAbastecimento) .filter( (EtapaAbastecimento._id_fluxo_abastecimento == _fluxo.id) & (EtapaAbastecimento.codigo_interno == _etp_sug.codigo_interno) ) ).first() _etapa_liberado = (_sessao.query(EtapaAbastecimento) .filter( (EtapaAbastecimento._id_fluxo_abastecimento == _fluxo.id) & (EtapaAbastecimento.codigo_interno == _etp_mod.codigo_interno) ) ).first() _etapa_sugestao, _etapa_liberado # + # Declarando ordens _sugestao = Sugestao(origem=_fornecedor, destino=_cliente) _ordem = OrdemAbastecimento(origem=_fornecedor, destino=_cliente) for p in _fluxo.produtos: # Compondo itens para a sugestao _item = ItemSugestao() _item.quantidade = random.randrange(30,100) _item.produto = p _item.valor_unitario = random.randrange(30,100) _sugestao.itens.append(_item) # Compondo itens para a sugestao _item = ItemOrdemAbastecimento() _item.quantidade = random.randrange(30,100) _item.produto = p _item.valor_unitario = random.randrange(30,100) _ordem.itens.append(_item) # - _etapa_sugestao.sugestoes.append(_sugestao) _etapa_liberado.ordens.append(_ordem) _sessao.query(OrdemAbastecimento).all() (_sessao.query(OrdemAbastecimento) .join(EtapaAbastecimento, OrdemAbastecimento._id_etapa_abastecimento == EtapaAbastecimento.id) .filter(EtapaAbastecimento.codigo_externo == 6, EtapaAbastecimento.data == UtilDatetime.utc_str_para_datetime('2017-09-28T00:00:00Z').date())).all() from sirius.util.v1 import UtilDatetime UtilDatetime.utc_str_para_datetime('2017-09-28T00:00:00Z').date()
ipython-testes/HSource.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Introduction # In this file, we will download the weather information about the resorts according to their geo-information through # the weather API. import json import numpy as np import pandas as pd import requests import matplotlib.pyplot as plt # %matplotlib inline df_1 = pd.read_csv('resorts_googleinfo.csv') df_1_np = np.array(df_1) csv_list = df_1_np.tolist() csv_list[0][3:5] geo_list = csv_list[:] for i in range(len(geo_list)): geo_list[i] = geo_list[i][3:5] geo_list resort_geo_lat=geo_list[:] resort_geo_lng=geo_list[:] for i in range(len(resort_geo_lat)): resort_geo_lat[i]=resort_geo_lat[i][0] resort_geo_lng[i]=resort_geo_lng[i][1] resort_geo_lat len(geo_list) test2=geo_list[:] test2[1][0] len(test2) def request_data(geo_la,geo_lo): # LA 37.8267,-122.4233 , beijing 39.904200, 116.407396 lat = geo_la long = geo_lo api_key = "<KEY>" url = "https://api.darksky.net/forecast/%s/%s,%s?units=si" % (api_key, lat, long) response = requests.get(url) return json.loads(response.text) para_list=['humidity','pressure','windspeed','cloudcover','visibility','temperature_min','temperature_max'] all_data=[] for i in range(len(test2)): temp=request_data(test2[i][0],test2[i][1]) all_data.append(temp) all_data[1]["daily"]["data"][7]['humidity'] temperature_min=[] temperature_max=[] humidity=[] pressure=[] windspeed=[] cloudcover=[] visibility=[] for i in range(len(all_data)): temp_min=[] temp_max=[] temp_hum=[] temp_pre=[] temp_wind=[] temp_cc=[] temp_vis=[] for x in [0,1,2,3,4,5,6,7]: temperaturemin=all_data[i]["daily"]["data"][x]['temperatureMin'] temperaturemax=all_data[i]["daily"]["data"][x]['temperatureMax'] humidity_test=all_data[i]["daily"]["data"][x]['humidity'] pressure_test=all_data[i]["daily"]["data"][x]['pressure'] windspeed_test=all_data[i]["daily"]["data"][x]['windSpeed'] cloudcover_test=all_data[i]["daily"]["data"][x]['cloudCover'] visibility_test=all_data[i]["daily"]["data"][x]['visibility'] temp_min.append(temperaturemin) temp_max.append(temperaturemax) temp_hum.append(humidity_test) temp_pre.append(pressure_test) temp_wind.append(windspeed_test) temp_cc.append(cloudcover_test) temp_vis.append(visibility_test) temperature_min.append(temp_min) temperature_max.append(temp_max) humidity.append(temp_hum) pressure.append(temp_pre) windspeed.append(temp_wind) cloudcover.append(temp_cc) visibility.append(temp_vis) temperature_min_pd = pd.DataFrame(temperature_min, columns=['current', '1', '2','3','4','5','6','7']) temperature_max_pd = pd.DataFrame(temperature_max, columns=['current', '1', '2','3','4','5','6','7']) humidity_pd = pd.DataFrame(humidity, columns=['current', '1', '2','3','4','5','6','7']) pressure_pd = pd.DataFrame(pressure, columns=['current', '1', '2','3','4','5','6','7']) windspeed_pd = pd.DataFrame(windspeed, columns=['current', '1', '2','3','4','5','6','7']) cloudcover_pd = pd.DataFrame(cloudcover, columns=['current', '1', '2','3','4','5','6','7']) visibility_pd = pd.DataFrame(visibility, columns=['current', '1', '2','3','4','5','6','7']) # + temperature_min_pd.insert(0,'resort_geo_lat',resort_geo_lat) temperature_min_pd.insert(1,'resort_geo_lng',resort_geo_lng) temperature_max_pd.insert(0,'resort_geo_lat',resort_geo_lat) temperature_max_pd.insert(1,'resort_geo_lng',resort_geo_lng) humidity_pd.insert(0,'resort_geo_lat',resort_geo_lat) humidity_pd.insert(1,'resort_geo_lng',resort_geo_lng) pressure_pd.insert(0,'resort_geo_lat',resort_geo_lat) pressure_pd.insert(1,'resort_geo_lng',resort_geo_lng) windspeed_pd.insert(0,'resort_geo_lat',resort_geo_lat) windspeed_pd.insert(1,'resort_geo_lng',resort_geo_lng) cloudcover_pd.insert(0,'resort_geo_lat',resort_geo_lat) cloudcover_pd.insert(1,'resort_geo_lng',resort_geo_lng) visibility_pd.insert(0,'resort_geo_lat',resort_geo_lat) visibility_pd.insert(1,'resort_geo_lng',resort_geo_lng) # - temperature_min_pd.drop_duplicates(subset=None,keep='first',inplace=True) temperature_min_pd temperature_max_pd.drop_duplicates(subset=None,keep='first',inplace=True) humidity_pd.drop_duplicates(subset=None,keep='first',inplace=True) pressure_pd.drop_duplicates(subset=None,keep='first',inplace=True) windspeed_pd.drop_duplicates(subset=None,keep='first',inplace=True) cloudcover_pd.drop_duplicates(subset=None,keep='first',inplace=True) visibility_pd.drop_duplicates(subset=None,keep='first',inplace=True) temperature_min_np = np.array(temperature_min_pd) temperature_min_list = temperature_min_np.tolist() temperature_max_np = np.array(temperature_max_pd) temperature_max_list = temperature_max_np.tolist() humidity_np = np.array(humidity_pd) humidity_list = humidity_np.tolist() pressure_np = np.array(pressure_pd) pressure_list = pressure_np.tolist() windspeed_np = np.array(windspeed_pd) windspeed_list = windspeed_np.tolist() cloudcover_np = np.array(cloudcover_pd) cloudcover_list = cloudcover_np.tolist() visibility_np = np.array(visibility_pd) visibility_list = visibility_np.tolist() pressure_list[1] import pymysql db=pymysql.connect(host='localhost',user='root',password='<PASSWORD>@',database='ski_project_test1',charset='utf8mb4') cursor=db.cursor() cursor.execute('USE ski_project_test1') for category in para_list: sql='''CREATE TABLE IF NOT EXISTS %s( resort_geo_lat VARCHAR(255), resort_geo_lng VARCHAR(255), current FLOAT, day_1 FLOAT, day_2 FLOAT, day_3 FLOAT, day_4 FLOAT, day_5 FLOAT, day_6 FLOAT, day_7 FLOAT)'''%category cursor.execute(sql) for category in para_list: sql='''TRUNCATE TABLE %s'''%category cursor.execute(sql) for i in range(len(visibility_list)): query = 'insert into visibility(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = visibility_list[i][0] resort_geo_lng = visibility_list[i][1] current = visibility_list[i][2] day_1 = visibility_list[i][3] day_2 = visibility_list[i][4] day_3 = visibility_list[i][5] day_4 = visibility_list[i][6] day_5 = visibility_list[i][7] day_6 = visibility_list[i][8] day_7 = visibility_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(cloudcover_list)): query = 'insert into cloudcover(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = cloudcover_list[i][0] resort_geo_lng = cloudcover_list[i][1] current = cloudcover_list[i][2] day_1 = cloudcover_list[i][3] day_2 = cloudcover_list[i][4] day_3 = cloudcover_list[i][5] day_4 = cloudcover_list[i][6] day_5 = cloudcover_list[i][7] day_6 = cloudcover_list[i][8] day_7 = cloudcover_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(windspeed_list)): query = 'insert into windspeed(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = windspeed_list[i][0] resort_geo_lng = windspeed_list[i][1] current = windspeed_list[i][2] day_1 = windspeed_list[i][3] day_2 = windspeed_list[i][4] day_3 = windspeed_list[i][5] day_4 = windspeed_list[i][6] day_5 = windspeed_list[i][7] day_6 = windspeed_list[i][8] day_7 = windspeed_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(pressure_list)): query = 'insert into pressure(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = pressure_list[i][0] resort_geo_lng = pressure_list[i][1] current = pressure_list[i][2] day_1 = pressure_list[i][3] day_2 = pressure_list[i][4] day_3 = pressure_list[i][5] day_4 = pressure_list[i][6] day_5 = pressure_list[i][7] day_6 = pressure_list[i][8] day_7 = pressure_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(humidity_list)): query = 'insert into humidity(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = humidity_list[i][0] resort_geo_lng = humidity_list[i][1] current = humidity_list[i][2] day_1 = humidity_list[i][3] day_2 = humidity_list[i][4] day_3 = humidity_list[i][5] day_4 = humidity_list[i][6] day_5 = humidity_list[i][7] day_6 = humidity_list[i][8] day_7 = humidity_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(temperature_max_list)): query = 'insert into temperature_max(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = temperature_max_list[i][0] resort_geo_lng = temperature_max_list[i][1] current = temperature_max_list[i][2] day_1 = temperature_max_list[i][3] day_2 = temperature_max_list[i][4] day_3 = temperature_max_list[i][5] day_4 = temperature_max_list[i][6] day_5 = temperature_max_list[i][7] day_6 = temperature_max_list[i][8] day_7 = temperature_max_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() for i in range(len(temperature_min_list)): query = 'insert into temperature_min(resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' resort_geo_lat = temperature_min_list[i][0] resort_geo_lng = temperature_min_list[i][1] current = temperature_min_list[i][2] day_1 = temperature_min_list[i][3] day_2 = temperature_min_list[i][4] day_3 = temperature_min_list[i][5] day_4 = temperature_min_list[i][6] day_5 = temperature_min_list[i][7] day_6 = temperature_min_list[i][8] day_7 = temperature_min_list[i][9] values = (resort_geo_lat, resort_geo_lng, current, day_1, day_2, day_3,day_4,day_5,day_6,day_7) cursor.execute(query, values) db.commit() db.close()
ski_resort_project/weather_api_final.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Getting federal servers list import time import requests import pandas as pd from bs4 import BeautifulSoup from threading import Thread base = 'csv/' def requestHTMLPage(url): r = requests.get(url) while r.status_code != 200: time.sleep(10) r = requests.get(url) print("Loop em potencial") return r.content # url base of portal da transparencia (where there is the list of functionaries) urlBaseSite = "http://www.portaldatransparencia.gov.br/" urlBaseOrgaoExercicio = "servidores/OrgaoExercicio-ListaServidores.asp?CodOrg=26243&Pagina=" currentMonth = 4 content = requestHTMLPage(urlBaseSite + urlBaseOrgaoExercicio) soup = BeautifulSoup(content, "html.parser") pages = soup.find_all("div", id = "paginacao") # get the greater page number of functionaries maxPage = pages[0].select('a')[1].get('onclick') maxPage = int(maxPage[maxPage.find("(")+1:maxPage.find(")")]) maxPage # + def getName(sumarry): sumarry = sumarry.find_all('td') iterDetails = iter(sumarry) while True: try: currentDetail = next(iterDetails).getText() if 'Nome:' in currentDetail: name = next(iterDetails).getText().strip() except StopIteration: break return name def getMoneyValue(soup): basicRemuneration = soup.find_all('td') iterDetails = iter(basicRemuneration) money = "" while True: try: currentDetail = next(iterDetails).getText() if 'Remuneraรงรฃo bรกsica bruta' in currentDetail: money = next(iterDetails).getText().strip() except StopIteration: break return money def getMoneyInfo(moneyUrl): money = "-1000" for i in range(1, currentMonth+1): moneyPage = requestHTMLPage(urlBaseSite + moneyUrl + "&Ano=2017&Mes=" + str(i)) if 'Servidor sem ficha' in str(moneyPage): continue else: soup = BeautifulSoup(moneyPage, "html.parser") money = getMoneyValue(soup) break return money def getSumarryInfo(soup): sumarry = soup.find_all('div', id='resumo')[0] moneyUrl = sumarry.find_all('a')[0].get('href') name = getName(sumarry) money = getMoneyInfo(moneyUrl) return name, money # scraping post, class_, level, org (departament where funcionary works) # soup : page to be scraped # returns : tuple with post, class, level, org def getGeneralInfo(soup): details = soup.find_all('td') iterDetails = iter(details) post = "" class_ = "" level = "" org = "" while True: try: currentDetail = next(iterDetails).getText() if 'Cargo Emprego:' in currentDetail: post = next(iterDetails).getText().strip() elif 'Classe:' in currentDetail: class_ = next(iterDetails).getText().strip() elif 'Nรญvel:' in currentDetail: level = next(iterDetails).getText().strip() elif 'UORG:' in currentDetail: org = next(iterDetails).getText().strip() except StopIteration: break return post, class_, level, org # functionaryUrl : url page of functionary # returns : tuple with name, salary (called money), post, class, level and org (departament) def getFunctionaryInfo(functionaryUrl, infos): info = requestHTMLPage(urlBaseSite + 'servidores/' + functionaryUrl) soup = BeautifulSoup(info, "html.parser") name, money = getSumarryInfo(soup) post, class_, level, org = getGeneralInfo(soup) infos.append((name, money, post, class_, level, org)) # - # functionaries of a given page def getFunctionaryUrls(pageNumber): content = requestHTMLPage(urlBaseSite + urlBaseOrgaoExercicio + str(pageNumber)) soup = BeautifulSoup(content, "html.parser") functionaries = soup.find_all('div', id='listagem') functionariesList = [] for l in functionaries: table = l.find_all('tr') table = table[1:] for functionary in table: functionariesList.append(functionary.find_all('a')[0].get('href')) return functionariesList # + # save stuff def toString(name, money, post, class_, level, org): return name + ';' + money + ';' + post + ';' + class_ + ';' + level + ';' + org + '\n' def saveCSV(infos): file = open(base + 'servers.csv', 'w') file.write("name;money;post;class;level;org\n") for i in infos: file.write(toString(*i)) file.close() # + # using threads to get functionary info faster def callGetFunctionaryInfo(urls, infos): threads = list() for url in urls: thread = Thread(target=getFunctionaryInfo, args=(url, infos)) threads.append(thread) for t in threads: t.start() for t in threads: t.join() maxLen = 30 infos = [] urls = [] for i in range(0, maxPage): # for each page it gets all functionaries urls += getFunctionaryUrls(i + 1) if len(urls) >= maxLen: callGetFunctionaryInfo(urls, infos) urls = [] print("Current page " + str(i + 1)) if len(urls) > 0: callGetFunctionaryInfo(urls, infos) print("Finished") saveCSV(infos) # -
.ipynb_checkpoints/FederalServersScraping-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # + boeing = pd.read_csv('BA_data.csv') ebay = pd.read_csv('EBAY_data.csv') # - data = { 'Date': boeing['Date'], 'boeing': boeing['Close'], 'ebay': ebay['Close']} data = pd.DataFrame(data) data returns = np.log(data.iloc[:,1:] / data.iloc[:,1:].shift(1) ) returns weights = np.array([0.5,0.5]) pfolio_var = np.dot(weights.T, np.dot(returns.cov()*250, weights)) pfolio_var pfolio_vol = (np.dot(weights.T, np.dot(returns.cov()*250, weights)))**0.5 pfolio_vol print(str(round(pfolio_vol,5)*100)+'%') boeing_var_a = returns[['boeing']].var()*250 boeing_var_a ebay_var_a = returns[['ebay']].var()*250 ebay_var_a d_risk = pfolio_var - (weights[0]**2*boeing_var_a)- (weights[1]**2*ebay_var_a) d_risk float(boeing_var_a) boeing_var_a = returns['boeing'].var()*250 boeing_var_a ebay_var_a = returns['ebay'].var()*250 ebay_var_a d_risk = pfolio_var - (weights[0]**2*boeing_var_a)- (weights[1]**2*ebay_var_a) d_risk print(str(round(d_risk*100,3))+'%') n_dr_1 = pfolio_var - d_risk n_dr_1 n_dr_2 = (weights[0]**2*boeing_var_a) + (weights[1]**2*ebay_var_a) n_dr_2 n_dr_1 == n_dr_2
5. Portfolio Risk.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.5.1 # language: julia # name: julia-0.5 # --- # + using JSON using PyPlot PyPlot.matplotlib[:rc]("text", usetex=true) # allow tex rendering PyPlot.matplotlib[:rc]("font", family="serif") font1 = Dict("family"=>"serif","color"=>"k","weight"=>"normal","size"=>14) # - # weight parameters gamma1 = 1 gamma2 = 1 # + norObjFunDict = readstring("./results/norObjFunDict_$(gamma1)_$(gamma2).json"); norObjFunDict = JSON.parse(norObjFunDict); demandsDiffDict = readstring("./results/demandsDiffDict_$(gamma1)_$(gamma2).json"); demandsDiffDict = JSON.parse(demandsDiffDict); objInvVIDict = readstring("./results/objInvVIDict_$(gamma1)_$(gamma2).json"); objInvVIDict = JSON.parse(objInvVIDict); coeffs_dict = readstring("./results/coeffs_dict_$(gamma1)_$(gamma2).json"); coeffs_dict = JSON.parse(coeffs_dict); tapFlowVecDict = readstring("./results/tapFlowVecDict_$(gamma1)_$(gamma2).json"); tapFlowVecDict = JSON.parse(tapFlowVecDict); link_capac_dict = readstring("../temp_files/link_capac_dict_Anaheim.json"); link_capac_dict = JSON.parse(link_capac_dict); # - link_capac_vec = [link_capac_dict["$i"] for i=0:length(link_capac_dict)-1]; # + epsilon_2 = 1e-20 numIter = Int64[] for l = 1:length(norObjFunDict) if norObjFunDict["$l"] - norObjFunDict["$(l+1)"] < epsilon_2 push!(numIter, l) break end end # - # update plots based on convergence rate N = numIter[1]; max_scaled_flow = maximum([tapFlowVecDict["$N"][i] / link_capac_vec[i] for i = 1:length(link_capac_vec)]) # + using PyPlot ################# # Create Data # ################# x = [tapFlowVecDict["$N"][i] / link_capac_vec[i] for i = 1:length(link_capac_vec)] # Values nbins = 50 # Number of bins ########## # Plot # ########## # fig = figure("pyplot_histogram",figsize=(6,3)) # Not strictly required fig = figure(figsize=(7, 2)) ax = axes() # Not strictly required h = plt[:hist](x,nbins) # Histogram font1 = Dict("family"=>"serif","color"=>"k","weight"=>"normal","size"=>14) # grid("on") xlabel("scaled flow", fontdict=font1) ylabel("counts", fontdict=font1) savefig("./results/scaled_flow_histogram_Anaheim_$(gamma1)_$(gamma2).pdf") # + iterNum = 0:(N) demandsDiff = map(iterNum->demandsDiffDict["$iterNum"], iterNum + 1) # plot(iterNum, objFun, "s-g", label="True") fig = figure(figsize=(7, 2)) plot(iterNum, demandsDiff, "s-b", linewidth=1, markerfacecolor="None", markeredgecolor="b", markeredgewidth=1) # legend(loc="upper right",fancybox="true") grid("on") xlim(-.2, N + .2) ylim(minimum(demandsDiff)-.0005, maximum(demandsDiff)+.0005) xticks(0:N) xlabel(L"$l$", fontdict=font1) ylabel(L"$\|\textbf{g}^l - \textbf{g}^*\| / \| \textbf{g}^* \|$", fontdict=font1) savefig("./results/demandsDiff_biLev_Anaheim_$(gamma1)_$(gamma2).pdf") dire = "/home/jzh/Dropbox/Research/Data-driven_estimation_inverse_optimization/" * "Joint_problem_and_multi_class_Traffic/imag/" savefig(dire * "demandsDiff_biLev_Anaheim_$(gamma1)_$(gamma2).pdf", dpi=300, bbox_inches="tight") # + normObjInvVIDict = Dict{}() for key in keys(objInvVIDict) normObjInvVIDict[key] = objInvVIDict[key] / objInvVIDict["1"] end # + iterNum = 0:(N) objFunBiLev = map(iterNum->norObjFunDict["$iterNum"], iterNum + 1) # plot(iterNum, objFun, "s-g", label="True") fig = figure(figsize=(7, 2)) plot(iterNum, objFunBiLev, "o-g", label="BiLev", linewidth=1, markerfacecolor="None", markeredgecolor="g", markeredgewidth=1) # objFunInv = map(iterNum->normObjInvVIDict["$iterNum"], iterNum) # plot(iterNum, objFun, "s-g", label="True") # plot(iterNum, objFunInv, "s-r", label="InvVI", linewidth=1, # markerfacecolor="None", markeredgecolor="r", markeredgewidth=1) # legend(loc="upper right",fancybox="true", frameon=false) grid("on") xlim(-0.2, N + .2) ylim(.35, 1.05) xticks(0:N) yticks(0.4:0.1:1.0) xlabel(L"$l$", fontdict=font1) ylabel(L"$F^l/F^0$", fontdict=font1) savefig("./results/objFun_Anaheim_$(gamma1)_$(gamma2).pdf") dire = "/home/jzh/Dropbox/Research/Data-driven_estimation_inverse_optimization/" * "Joint_problem_and_multi_class_Traffic/imag/" savefig(dire * "objFun_Anaheim_$(gamma1)_$(gamma2).pdf", dpi=300, bbox_inches="tight") # - polyEval(coeffs, pt) = sum([coeffs[i] * pt^(i-1) for i = 1:length(coeffs)]); keys(coeffs_dict) # + iterN_1 = 1 iterN_2 = 2 iterN_3 = 3 iterN_4 = N+1 true_coeffs = [1, 0, 0, 0, .15] # true_coeffs = [1, .2, .5, .8, .15] est_coeffs_1 = coeffs_dict["(6,3.5,1.0,$iterN_1)"] est_coeffs_2 = coeffs_dict["(6,3.5,1.0,$iterN_2)"] est_coeffs_3 = coeffs_dict["(6,3.5,1.0,$iterN_3)"] est_coeffs_4 = coeffs_dict["(6,3.5,1.0,$iterN_4)"] xs = linspace(0, max_scaled_flow, 20) xs_true = linspace(0, max_scaled_flow, 20) zs_true = map(x->polyEval(true_coeffs, x), xs_true) zs_1 = map(x->polyEval(est_coeffs_1, x), xs) zs_2 = map(x->polyEval(est_coeffs_2, x), xs) zs_3 = map(x->polyEval(est_coeffs_3, x), xs) zs_4 = map(x->polyEval(est_coeffs_4, x), xs) fig = figure(figsize=(7,2)) plot(xs, zs_1, "^-m", label=L"$\hat f(\cdot)$ iteration 0", linewidth=1, markerfacecolor="None", markeredgecolor="m", markeredgewidth=1) plot(xs, zs_2, "+-b", label=L"$\hat f(\cdot)$ iteration 1", linewidth=1, markerfacecolor="None", markeredgecolor="b", markeredgewidth=1) plot(xs, zs_3, "o-c", label=L"$\hat f(\cdot)$ iteration 2", linewidth=1, markerfacecolor="None", markeredgecolor="c", markeredgewidth=1) plot(xs, zs_4, "*-g", label=L"$\hat f(\cdot)$ iteration" * " $(N)", linewidth=1, markerfacecolor="None", markeredgecolor="g", markeredgewidth=1) plot(xs_true, zs_true, "s-r", label=L"ground truth $f(\cdot)$", linewidth=1, markerfacecolor="None", markeredgecolor="r", markeredgewidth=1) legend(loc="upper left",fancybox="true", frameon=true) grid("on") # xlim(-0.1, max_scaled_flow+0.1); xlim(-0.1, 1.6); ylim(0.9, 2); xticks(0:0.2:1.6) yticks(1:0.2:2) xlabel("scaled flow", fontdict=font1) ylabel("scaled cost", fontdict=font1) savefig("./results/fitting_Anaheim_$(gamma1)_$(gamma2).pdf") dire = "/home/jzh/Dropbox/Research/Data-driven_estimation_inverse_optimization/" * "Joint_problem_and_multi_class_Traffic/imag/" savefig(dire * "fitting_Anaheim_$(gamma1)_$(gamma2).pdf", dpi=300, bbox_inches="tight") # - 1 - norObjFunDict["$(N+1)"]
12_2_develop_new_OD_demand_estimator_Anaheim_Dijkstra_uni_class/05_refine_iteration_results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import scipy.stats as sps import matplotlib.pyplot as plt import seaborn as sns import sklearn as skl from sklearn.feature_selection import RFECV from sklearn.linear_model import LogisticRegression from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn import tree from sklearn.model_selection import train_test_split import graphviz from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report,confusion_matrix # %matplotlib inline # FDR@3% for training/testing/oot # + data=pd.read_csv('0325_vars_final_zscale.csv') oot=pd.read_csv('0325_oot_final_zscale.csv') x = data.iloc[:,2:] y = data.iloc[:,1] x_oot = oot.iloc[:,2:] y_oot = oot.iloc[:,1] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0) clf = MLPClassifier(hidden_layer_sizes=[5,5]) clf.fit(x_train, y_train) NN_scores = clf.predict_proba(x_train)[:,1] X_train=x_train X_train['NN_scores']=NN_scores Train=X_train.join(y_train) Train=Train.sort_values(by=['NN_scores'],ascending=False) GoodTest=sum(Train['Fraud']==0) BadTest=sum(Train['Fraud']==1) r=0 l=[] culgood=0 culbad=0 for i in range(100): data=Train.iloc[r:min((i+1)*630,62977),] populationbin=i+1 numofrecord=len(data) numofgood=sum(data['Fraud']==0) numofbads=sum(data['Fraud']==1) percentagegood=numofgood/GoodTest*100 percentagebad=numofbads/BadTest*100 numofrecord=min((i+1)*630,62977)-r totalrecord=min((i+1)*630,62977) culgood+=numofgood culbad+=numofbads culpergood=culgood/GoodTest*100 culperbad=culbad/BadTest*100 KS=culperbad-culpergood FPR=culpergood/culperbad r=(i+1)*630 l.append([populationbin,numofrecord,numofgood,numofbads,percentagegood,percentagebad,totalrecord,culgood,culbad,culpergood,culperbad,KS,FPR]) l l=pd.DataFrame(l,columns=['populationbin','numofrecord','numofgood','numofbads','percentagegood','percentagebad','totalrecord','culgood','culbad','culpergood','culperbad','KS','FPR']) train_FDR=l.loc[2]['culperbad'] NN_scores = clf.predict_proba(x_test)[:,1] X_test=x_test X_test['NN_scores']=NN_scores Test=X_test.join(y_test) Test=Test.sort_values(by=['NN_scores'],ascending=False) GoodTest=sum(Test['Fraud']==0) BadTest=sum(Test['Fraud']==1) r=0 l=[] culgood=0 culbad=0 for i in range(100): data=Test.iloc[r:min((i+1)*210,20993),] populationbin=i+1 numofrecord=len(data) numofgood=sum(data['Fraud']==0) numofbads=sum(data['Fraud']==1) percentagegood=numofgood/GoodTest*100 percentagebad=numofbads/BadTest*100 numofrecord=min((i+1)*210,20993)-r totalrecord=min((i+1)*210,20993) culgood+=numofgood culbad+=numofbads culpergood=culgood/GoodTest*100 culperbad=culbad/BadTest*100 KS=culperbad-culpergood FPR=culpergood/culperbad r=(i+1)*210 l.append([populationbin,numofrecord,numofgood,numofbads,percentagegood,percentagebad,totalrecord,culgood,culbad,culpergood,culperbad,KS,FPR]) l l=pd.DataFrame(l,columns=['populationbin','numofrecord','numofgood','numofbads','percentagegood','percentagebad','totalrecord','culgood','culbad','culpergood','culperbad','KS','FPR']) test_FDR=l.loc[2]['culperbad'] NN_scores = clf.predict_proba(x_oot)[:,1] X_oot=x_oot X_oot['NN_scores']=NN_scores OOT=X_oot.join(y_oot) OOT=OOT.sort_values(by=['NN_scores'],ascending=False) GoodTest=sum(OOT['Fraud']==0) BadTest=sum(OOT['Fraud']==1) r=0 l=[] culgood=0 culbad=0 for i in range(100): data=OOT.iloc[r:min((i+1)*125,12427),] populationbin=i+1 numofrecord=len(data) numofgood=sum(data['Fraud']==0) numofbads=sum(data['Fraud']==1) percentagegood=numofgood/GoodTest*100 percentagebad=numofbads/BadTest*100 numofrecord=min((i+1)*125,12427)-r totalrecord=min((i+1)*125,12427) culgood+=numofgood culbad+=numofbads culpergood=culgood/GoodTest*100 culperbad=culbad/BadTest*100 KS=culperbad-culpergood FPR=culpergood/culperbad r=(i+1)*125 l.append([populationbin,numofrecord,numofgood,numofbads,percentagegood,percentagebad,totalrecord,culgood,culbad,culpergood,culperbad,KS,FPR]) l l=pd.DataFrame(l,columns=['populationbin','numofrecord','numofgood','numofbads','percentagegood','percentagebad','totalrecord','culgood','culbad','culpergood','culperbad','KS','FPR']) oot_FDR=l.loc[2]['culperbad'] print(train_FDR,test_FDR,oot_FDR) # - # Training Table # + data=pd.read_csv('0325_vars_final_zscale.csv') oot=pd.read_csv('0325_oot_final_zscale.csv') x = data.iloc[:,2:] y = data.iloc[:,1] x_oot = oot.iloc[:,2:] y_oot = oot.iloc[:,1] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0) clf = MLPClassifier(hidden_layer_sizes=[5,5]) clf.fit(x_train, y_train) NN_scores = clf.predict_proba(x_train)[:,1] X_train=x_train X_train['NN_scores']=NN_scores Train=X_train.join(y_train) Train=Train.sort_values(by=['NN_scores'],ascending=False) GoodTest=sum(Train['Fraud']==0) BadTest=sum(Train['Fraud']==1) r=0 l=[] culgood=0 culbad=0 for i in range(100): data=Train.iloc[r:min((i+1)*630,62977),] populationbin=i+1 numofrecord=len(data) numofgood=sum(data['Fraud']==0) numofbads=sum(data['Fraud']==1) percentagegood=numofgood/GoodTest*100 percentagebad=numofbads/BadTest*100 numofrecord=min((i+1)*630,62977)-r totalrecord=min((i+1)*630,62977) culgood+=numofgood culbad+=numofbads culpergood=culgood/GoodTest*100 culperbad=culbad/BadTest*100 KS=culperbad-culpergood FPR=culpergood/culperbad r=(i+1)*630 l.append([populationbin,numofrecord,numofgood,numofbads,percentagegood,percentagebad,totalrecord,culgood,culbad,culpergood,culperbad,KS,FPR]) l l=pd.DataFrame(l,columns=['populationbin','numofrecord','numofgood','numofbads','percentagegood','percentagebad','totalrecord','culgood','culbad','culpergood','culperbad','KS','FPR']) l.head(20)
NN model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Prepare and modify figures for paper. # + import numpy as np import pandas as pd import matplotlib.pyplot as plt #plt.style.use('ggplot') plt.style.use('seaborn-colorblind') #plt.style.use('dark_background') plt.rcParams['figure.dpi'] = 300 plt.rcParams['savefig.dpi'] = 300 plt.rcParams['savefig.bbox'] = 'tight' plt.rcParams['savefig.transparent'] = True # %matplotlib inline import datetime date = datetime.datetime.now().strftime('%Y%m%d') # - # # Data distribution # Adopted from build_models_07.ipynb. # + from sklearn.model_selection import train_test_split fig, axes = plt.subplots(2, 3, sharex='row', sharey='row', figsize=(7.5, 7)) merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv', index_col=0) ca_df = merge_df[merge_df.core != 'SO178-12-3'] # This core doesn't have CaCO3 measurement toc_y_train, toc_y_test = train_test_split(merge_df['TOC%'].values, test_size = 0.2, shuffle = True, random_state = 24) ca_y_train, ca_y_test = train_test_split(ca_df['CaCO3%'].values, test_size = 0.2, shuffle = True, random_state = 24) #ax.set_xlabel('wt (%)\n{}'.format(label)) for ax, y, label in zip(axes[0, :], [merge_df['TOC%'], toc_y_train, toc_y_test], ['Whole dataset', 'Training set', 'Test set']): ax.hist(y) ax.text(0.5, 0.8, "max.={:.1f}\nmin.={:.2f}\nN={}".format( np.max(y), np.min(y), len(y)), transform=ax.transAxes) for ax, y, label in zip(axes[1, :], [ca_df['CaCO3%'], ca_y_train, ca_y_test], ['Whole dataset', 'Training set', 'Test set']): ax.hist(y) ax.text(0.5, 0.8, "max.={:.1f}\nmin.={:.2f}\nN={}".format( np.max(y), np.min(y), len(y)), transform=ax.transAxes) ax.set_xlabel('wt (%)\n{}'.format(label)) axes[0, 0].set_ylabel('Count for TOC') axes[1, 0].set_ylabel('Count for Carbonate') fig.subplots_adjust(wspace=.05, top=.92) fig.savefig('results/data_hist_{}.png'.format(date)) # - np.unique(merge_df.core) merge_df.head() # ## Show data distribution of each step # ### Build datasets merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv', index_col=0) merge_df.core.unique() # + from sklearn.model_selection import train_test_split #merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv', index_col=0) SO264_core = merge_df.core.unique()[:-3] scale_1_df = merge_df[merge_df.core.isin(SO264_core)].copy() scale_2_ca = merge_df.loc[merge_df.core.isin(['LV28-44-3', 'LV29-114-3']), 'CaCO3%'] scale_2_toc = merge_df.loc[merge_df.core.isin(['LV28-44-3', 'LV29-114-3', 'SO178-12-3']), 'TOC%'] s1_toc_train, s1_toc_test, s1_ca_train, s1_ca_test = train_test_split(scale_1_df['TOC%'].values, scale_1_df['CaCO3%'].values, test_size = 0.2, shuffle = True, random_state = 24) s2_toc_train, s2_toc_test = train_test_split(scale_2_toc, test_size = 0.2, shuffle = True, random_state = 24) s2_ca_train, s2_ca_test = train_test_split(scale_2_ca, test_size = 0.2, shuffle = True, random_state = 24) # + fig, axes = plt.subplots(2, 3, sharex='row', sharey='row', figsize=(7.5, 7)) #Carbonate for ax, s1, s2 in zip(axes[0, :], [scale_1_df['CaCO3%'], s1_ca_train, s1_ca_test], [scale_2_ca, s2_ca_train, s2_ca_test]): y = np.hstack((s1, s2)) ax.hist([s1, s2], stacked=True, label=['1$^{st}$ scale up', '2$^{nd}$ scale up']) ax.text(0.5, 0.8, "Max.={:.1f}\nMin.={:.2f}\nN={}".format( np.max(y), np.min(y), len(y)), transform=ax.transAxes) # TOC for ax, s1, s2, label in zip(axes[1, :], [scale_1_df['TOC%'], s1_toc_train, s1_toc_test], [scale_2_toc, s2_toc_train, s2_toc_test], ['Whole dataset', 'Training set', 'Test set']): y = np.hstack((s1, s2)) ax.hist([s1, s2], stacked=True) ax.text(0.5, 0.8, "Max.={:.1f}\nMin.={:.2f}\nN={}".format( np.max(y), np.min(y), len(y)), transform=ax.transAxes) ax.set_xlabel('wt (%)\n{}'.format(label)) axes[0, 0].set_ylabel('Count for Carbonate') axes[1, 0].set_ylabel('Count for TOC') axes[0, 2].legend(loc='center right') fig.subplots_adjust(wspace=.05, top=.92) fig.savefig('results/data_hist_s1+2_{}.png'.format(date)) # + s1_toc = {'max': [], 'min': [], 'N':[]} s1_ca = {'max': [], 'min': [], 'N':[]} s2_toc = {'max': [], 'min': [], 'N':[]} s2_ca = {'max': [], 'min': [], 'N':[]} cols = [] for s, label, values in zip([s1_toc, s1_ca, s2_toc, s2_ca], ['s1_toc', 's1_ca', 's2_toc', 's2_ca'], [[scale_1_df['TOC%'], s1_toc_train, s1_toc_test], [scale_1_df['CaCO3%'], s1_ca_train, s1_ca_test], [scale_2_toc, s2_toc_train, s2_toc_test], [scale_2_ca, s2_ca_train, s2_ca_test]]): for value, dataset in zip(values, ['whole', 'train', 'test']): s['max'].append(np.max(value)) s['min'].append(np.min(value)) s['N'].append(len(value)) cols.append('{}_{}'.format(label, dataset)) # - data_info = pd.concat( [pd.DataFrame(s1_toc).T, pd.DataFrame(s1_ca).T, pd.DataFrame(s2_toc).T, pd.DataFrame(s2_ca).T], join='outer', axis=1 ) data_info.columns = cols data_info data_info.to_csv('results/data_distribution_{}.csv'.format(date)) # + fig, axes = plt.subplots(1, 2, figsize=(7, 5), sharey='row') for ax, analyte in zip(axes, ['TOC%', 'CaCO3%']): y = merge_df.loc[merge_df.core == 'SO264-15-2', analyte] ax.hist(y) ax.text(0.67, 0.85, "Max.={:.1f}\nMin.={:.2f}\nN={}".format( np.max(y), np.min(y), len(y)), transform=ax.transAxes) axes[0].set_xlabel('TOC wt (%)') axes[1].set_xlabel('CaCO$_{3}$ wt (%)') axes[0].set_ylabel('Count') fig.subplots_adjust(wspace=.05, top=.92) fig.savefig('results/data_hist_pilot_{}.png'.format(date)) # - # # The performance in the test set # It's for the results of the 1st scale up. from joblib import load model_ca = load('models/caco3_nmf+svr_model_20201013.joblib') model_toc = load('models/toc_nmf+svr_model_20201013.joblib') # + from sklearn.model_selection import train_test_split merge_df = pd.read_csv('data/spe+bulk_dataset_20201008.csv') X = merge_df.iloc[:, 1: -5].values X = X / X.sum(axis = 1, keepdims = True) y_ca = merge_df['CaCO3%'].values y_toc = merge_df['TOC%'].values X_train, X_test, y_ca_train, y_ca_test, y_toc_train, y_toc_test = train_test_split(X, y_ca, y_toc, test_size = 0.2, shuffle = True, random_state = 24) # - y_ca_predict = np.exp(model_ca.predict(X_test)) y_toc_predict = np.exp(model_toc.predict(X_test)) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_ca_test, y_ca_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_ca_test, y_ca_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_ca_test, y_ca_predict))) # - plt.plot(range(len(y_ca_predict)), y_ca_test, alpha=0.6, label='Measurement') plt.plot(range(len(y_ca_predict)), y_ca_predict, label='Prediction (R$^2$={:.2f})'.format(r2_score(y_ca_test, y_ca_predict))) #plt.text(12, -7, r'R$^2$={:.2f}, mean ab. error={:.2f}, max. ab. error={:.2f}'.format(grid.best_score_, mean_absolute_error(y_ttest, y_predict), max_error(y_ttest, y_predict))) plt.ylabel('CaCO$_3$ concentration (%)') plt.xlabel('Sample no.') plt.legend(loc = 'upper right') #plt.savefig('results/caco3_predictions_nmr+svr_{}.png'.format(date)) # The performance is not consist with that in build_models_04.ipynb... from dask.distributed import Client from dask_jobqueue import SLURMCluster cluster = SLURMCluster( project="aslee@10.110.16.5", queue='main', cores=40, memory='10 GB', walltime="00:10:00", log_directory='job_logs' ) client = Client(cluster) cluster.scale(10) #cluster.adapt(maximum=100) client client.close() cluster.close() # + from dask_ml.model_selection import train_test_split import dask.dataframe as dd merge_df = dd.read_csv('data/spe+bulk_dataset_20201008.csv') X = merge_df.iloc[:, 1: -5].to_dask_array(lengths=True) X = X / X.sum(axis = 1, keepdims = True) y = merge_df['CaCO3%'].to_dask_array(lengths=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, shuffle = True, random_state = 24) # - y_predict = np.exp(model_ca.predict(X_test)) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_test, y_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_test, y_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_test, y_predict))) # - plt.plot(range(len(y_predict)), y_test, alpha=0.6, label='Measurement') plt.plot(range(len(y_predict)), y_predict, label='Prediction (R$^2$={:.2f})'.format(r2_score(y_test, y_predict))) #plt.text(12, -7, r'R$^2$={:.2f}, mean ab. error={:.2f}, max. ab. error={:.2f}'.format(grid.best_score_, mean_absolute_error(y_ttest, y_predict), max_error(y_ttest, y_predict))) plt.ylabel('CaCO$_3$ concentration (%)') plt.xlabel('Sample no.') plt.legend(loc = 'upper right') #plt.savefig('results/caco3_predictions_nmr+svr_{}.png'.format(date)) # After some tryouts above, I realized train_test_split in dask_ml and sklearn produce different subsets although the random_state is setted same. In order to be consist with build_models_04.ipynb (having same subsets) and avoid data-snooping, I need to use dask here in the 1st scale up. Later in the 2nd scale it's nont needed because the works were submitted using scripts. # + from dask_ml.model_selection import train_test_split import dask.dataframe as dd merge_df = dd.read_csv('data/spe+bulk_dataset_20201008.csv') X = merge_df.iloc[:, 1: -5].to_dask_array(lengths=True) X = X / X.sum(axis = 1, keepdims = True) y_ca = merge_df['CaCO3%'].to_dask_array(lengths=True) y_toc = merge_df['TOC%'].to_dask_array(lengths=True) X_train, X_test, y_ca_train, y_ca_test, y_toc_train, y_toc_test = train_test_split(X, y_ca, y_toc, test_size = 0.2, shuffle = True, random_state = 24) # - from joblib import load model_ca = load('models/caco3_nmf+svr_model_20201013.joblib') model_toc = load('models/toc_nmf+svr_model_20201013.joblib') # + y_ca_predict = np.exp(model_ca.predict(X_test)) y_toc_predict = np.exp(model_toc.predict(X_test)) # change to np.array from dask array, which is easier for later fune-tuning plot y_ca_test = np.array(y_ca_test) y_toc_test = np.array(y_toc_test) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_toc_test, y_toc_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_toc_test, y_toc_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_toc_test, y_toc_predict))) # - plt.plot(range(len(y_toc_predict)), y_toc_test, alpha=0.6, label='Measurement') plt.plot(range(len(y_toc_predict)), y_toc_predict, label='Prediction (R$^2$={:.2f})'.format(r2_score(y_toc_test, y_toc_predict))) #plt.text(12, -7, r'R$^2$={:.2f}, mean ab. error={:.2f}, max. ab. error={:.2f}'.format(grid.best_score_, mean_absolute_error(y_ttest, y_predict), max_error(y_ttest, y_predict))) plt.ylabel('TOC concentration (%)') plt.xlabel('Sample no.') plt.legend(loc = 'upper right') #plt.savefig('results/toc_predictions_nmr+svr_{}.png'.format(date)) # Just for double check. The TOC's performance is consistent to build_models_05.ipynb. # ### Plot A # + from sklearn.metrics import r2_score fig, axes = plt.subplots(2, 1, figsize=(5, 7.5), sharex='col') axes[0].plot(range(len(y_ca_test)), y_ca_test, alpha=0.6, label='Measurement') axes[0].plot(range(len(y_ca_predict)), y_ca_predict, label='Prediction') axes[0].set_ylabel('CaCO$_3$ conc. (wt %, R$^2$={:.2f})'.format(r2_score(y_ca_test, y_ca_predict))) axes[1].plot(range(len(y_toc_test)), y_toc_test, alpha=0.6, label='Measurement') axes[1].plot(range(len(y_toc_predict)), y_toc_predict, label='Prediction') axes[1].set_ylabel('TOC conc. (wt %, R$^2$={:.2f})'.format(r2_score(y_toc_test, y_toc_predict))) axes[1].legend(loc='upper left') axes[1].set_yticks(np.linspace(0, 0.8, 5)) axes[1].set_xlabel('Sample no.') fig.subplots_adjust(hspace=.05) fig.savefig('results/1st_performance_test_a_{}.png'.format(date)) # + from sklearn.metrics import r2_score fig, axes = plt.subplots(2, 1, figsize=(7, 3.7), sharex='col') axes[0].plot(range(len(y_ca_test)), y_ca_test, alpha=0.6, label='Measurement') axes[0].plot(range(len(y_ca_predict)), y_ca_predict, label='Prediction') axes[0].set_ylabel('Carbonate conc.\n(wt %)') axes[0].set_yticks(np.linspace(0, 80, 3)) axes[0].set_xlim(-2, 77) axes[1].plot(range(len(y_toc_test)), y_toc_test, alpha=0.6, label='Measurement') axes[1].plot(range(len(y_toc_predict)), y_toc_predict, label='Prediction') axes[1].set_ylabel('TOC conc. (wt %)') axes[1].legend(loc='upper left', ncol=2) axes[1].set_yticks(np.linspace(0, 0.8, 3)) axes[1].set_xlabel('Sample no.') fig.subplots_adjust(hspace=.08) fig.savefig('results/1st_performance_test_a_{}.png'.format(date)) # - # ### Plot B # + fig, axes = plt.subplots(2, 1, figsize=(5, 7.5)) ind = np.argsort(y_ca_test) axes[0].scatter(y_ca_test[ind], y_ca_predict[ind], s=4, label='CaCO$_3$ (R$^2$={:.2f})'.format(r2_score(y_ca_test, y_ca_predict))) axes[0].plot(np.linspace(0, 90, 10), np.linspace(0, 90, 10), alpha=.5, c='gray') axes[0].set_ylabel('Predicted conc. (wt %)') axes[0].legend(loc = 'upper left') axes[0].set_aspect('equal') ind = np.argsort(y_toc_test) axes[1].scatter(y_toc_test[ind], y_toc_predict[ind], s=4, label='TOC (R$^2$={:.2f})'.format(r2_score(y_toc_test, y_toc_predict))) axes[1].plot(np.linspace(0, 0.8, 9), np.linspace(0, 0.8, 9), alpha=.5, c='gray') axes[1].set_ylabel('Predicted conc. (wt %)') axes[1].set_xlabel('Measured conc. (wt %)') axes[1].legend(loc = 'upper left') axes[1].set_aspect('equal') axes[1].set_yticks(np.linspace(0, 0.8, 5)) fig.subplots_adjust(hspace=.1) fig.savefig('results/1st_performance_test_b_{}.png'.format(date)) # - # ### Choose plot # Two plots use the same data (performance in the test set) but different illustrations. Both are used to demonstrate performance of predicetions commonly. Plot A provides the comparison of sample behaviors in different analytes since the x-axis are the sample number. It shows that, samples having bad predictions in TOC don't necessary have bad prediction in carbonate. Also, it looks subjectively better in accuracy. Plot B display the error distribution along concentration more directly, but loose the ability of making comparison in samples between analytes. I prefer plot A becuase the relation of error and concentration is not clear in our result, making the advantage of plot B less important. # # Test the 1st scale up models on the 2nd scale up dataset # During writing the paper, I realize the evaluation using models in 1st scale up and datasets in 2nd scale up need to be modified. The previous codes just fed the whole dataset in the 2nd scale up, including the 1st scale up, to the model to see how bad the predictions on the new dataset comparing to the old dataset in the same figure. I think it's a bit redundant because the old dataset contains modtly the training set of those models. The models should perform well on that. # ## Check two datasets merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv', index_col=0) merge_df merge_df[merge_df.core.isin(['LV28-44-3', 'LV29-114-3', 'SO178-12-3'])] merge_old = pd.read_csv('data/spe+bulk_dataset_20201008.csv', index_col=0) merge_old 699-382 merge_df.core.unique() # Those three new core only have 254 data points and the old dataset has 382. The new core should have 317 data points so there are 63 ghost points in the new dataset. pd.concat([ pd.DataFrame(np.unique(merge_df.core, return_counts=True), index=['core', 'N']).T.set_index('core'), pd.DataFrame(np.unique(merge_old.core, return_counts=True), index=['core', 'N']).T.set_index('core')], join='outer', axis=1) # It's just a double check. Two datasets look fine. from joblib import load model_ca = load('models/caco3_nmf+svr_model_20201013.joblib') model_toc = load('models/toc_nmf+svr_model_20201013.joblib') # + merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv') X = merge_df.iloc[:, 1: -5].values X = X / X.sum(axis = 1, keepdims = True) y_ca = merge_df.loc[merge_df.core.isin(['LV28-44-3', 'LV29-114-3']), 'CaCO3%'] y_toc = merge_df.loc[merge_df.core.isin(['LV28-44-3', 'LV29-114-3', 'SO178-12-3']), 'TOC%'] # - print(len(y_ca), len(y_toc)) y_ca_predict = np.exp(model_ca.predict(X[merge_df.core.isin(['LV28-44-3', 'LV29-114-3'])])) y_toc_predict = np.exp(model_toc.predict(X[merge_df.core.isin(['LV28-44-3', 'LV29-114-3', 'SO178-12-3'])])) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_ca, y_ca_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_ca, y_ca_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_ca, y_ca_predict))) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_toc, y_toc_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_toc, y_toc_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_toc, y_toc_predict))) # + from sklearn.metrics import r2_score fig, axes = plt.subplots(2, 1, figsize=(7, 3.7), sharex='col') axes[0].plot(range(len(y_ca)), y_ca, alpha=0.6, label='Measurement') axes[0].plot(range(len(y_ca_predict)), y_ca_predict, label='Prediction') axes[0].set_ylabel('Carbonate conc.\n(wt %)') #axes[0].set_yticks(np.linspace(0, 80, 3)) axes[0].set_xlim(-5, 320) axes[0].legend(loc='upper right', ncol=2) axes[1].plot(range(len(y_toc)), y_toc, alpha=0.6, label='Measurement') axes[1].plot(range(len(y_toc_predict)), y_toc_predict, label='Prediction') axes[1].set_ylabel('TOC conc. (wt %)') #axes[1].set_yticks(np.linspace(0, 0.8, 3)) axes[1].set_xlabel('Sample no.') fig.subplots_adjust(hspace=.08) fig.savefig('results/1st_performance_2nddataset_{}.png'.format(date)) print(date) # - # As we already know, the prediction based on extrapolation gives poor results. # # The performance in the test set # It's for the results of the 2nd scale up. from joblib import load model_ca = load('models/caco3_nmf+svr_model_20201216.joblib') model_toc = load('models/toc_nmf+svr_model_20201215.joblib') # + from sklearn.model_selection import train_test_split merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv') X = merge_df.iloc[:, 1: -5].values X = X / X.sum(axis = 1, keepdims = True) y_ca = merge_df.loc[merge_df.core != 'SO178-12-3', 'CaCO3%'].values y_toc = merge_df['TOC%'].values _, X_ca_test, _, y_ca_test = train_test_split( X[merge_df.core != 'SO178-12-3'], y_ca, test_size = 0.2, shuffle = True, random_state = 24) _, X_toc_test, _, y_toc_test = train_test_split( X, y_toc, test_size = 0.2, shuffle = True, random_state = 24) # - y_ca_predict = np.exp(model_ca.predict(X_ca_test)) y_toc_predict = np.exp(model_toc.predict(X_toc_test)) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_ca_test, y_ca_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_ca_test, y_ca_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_ca_test, y_ca_predict))) # + from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import max_error print('Scores in the test set:') print('R2 = {:.3f} .'.format(r2_score(y_toc_test, y_toc_predict))) print('The mean absolute error is {:.3f} (%, concetration).'.format(mean_absolute_error(y_toc_test, y_toc_predict))) print('The max. residual error is {:.3f} (%, concetration).'.format(max_error(y_toc_test, y_toc_predict))) # + from sklearn.metrics import r2_score fig, axes = plt.subplots(2, 1, figsize=(7, 3.7), sharex='col') axes[0].plot(range(len(y_ca_test)), y_ca_test, alpha=0.6, label='Measurement') axes[0].plot(range(len(y_ca_predict)), y_ca_predict, label='Prediction') axes[0].set_ylabel('Carbonate conc.\n(wt %)') axes[0].legend(loc='upper right') #axes[0].set_yticks(np.linspace(0, 80, 3)) axes[0].set_xlim(-3, 142) axes[1].plot(range(len(y_toc_test)), y_toc_test, alpha=0.6, label='Measurement') axes[1].plot(range(len(y_toc_predict)), y_toc_predict, label='Prediction') axes[1].set_ylabel('TOC conc. (wt %)') #axes[1].set_yticks(np.linspace(0, 0.8, 3)) axes[1].set_xlabel('Sample no.') fig.subplots_adjust(hspace=.08) fig.savefig('results/2nd_performance_test_{}.png'.format(date)) # - from sklearn.metrics import r2_score # + fig, axes = plt.subplots(1, 2, figsize=(5, 7.5)) ind = np.argsort(y_ca_test) axes[0].scatter(y_ca_test[ind], y_ca_predict[ind], s=4, label='CaCO$_3$ (R$^2$={:.2f})'.format(r2_score(y_ca_test, y_ca_predict))) xlim = axes[0].get_xlim() ylim = axes[0].get_ylim() axes[0].plot(xlim, ylim, alpha=.5, c='gray') axes[0].set_xlabel('Measured conc. (wt %)') axes[0].set_ylabel('Predicted conc. (wt %)') axes[0].set_xticks(np.linspace(0, 80, 5)) #axes[0].legend(loc = 'upper left') axes[0].text(.02, .9, 'CaCO$_3$ (R$^2$={:.2f})'.format(r2_score(y_ca_test, y_ca_predict)), transform=axes[0].transAxes) axes[0].set_aspect('equal') ind = np.argsort(y_toc_test) axes[1].scatter(y_toc_test[ind], y_toc_predict[ind], s=4, label='TOC (R$^2$={:.2f})'.format(r2_score(y_toc_test, y_toc_predict))) xlim = axes[1].get_xlim() ylim = axes[1].get_ylim() axes[1].plot(xlim, ylim, alpha=.5, c='gray') axes[1].set_xlabel('Measured conc. (wt %)') #axes[1].legend(loc = 'upper left') axes[1].text(.02, .9, 'TOC (R$^2$={:.2f})'.format(r2_score(y_toc_test, y_toc_predict)), transform=axes[1].transAxes) axes[1].set_aspect('equal') #axes[1].set_yticks(np.linspace(0, 0.8, 5)) #fig.subplots_adjust(wspace=.1) fig.savefig('results/2st_performance_test_b_{}.png'.format(date)) # - # # Draw spectrum merge_df = pd.read_csv('data/spe+bulk_dataset_20201215.csv', index_col=0) merge_df.core.unique() # + from sklearn.model_selection import train_test_split X = merge_df.iloc[:, : -5].values X = X / X.sum(axis = 1, keepdims = True) SO264_core = merge_df.core.unique()[:-3] s1_X_train, _ = train_test_split(X[merge_df.core.isin(SO264_core)], test_size = 0.2, shuffle = True, random_state = 24) s2_toc_train, _ = train_test_split(X[merge_df.core.isin(['LV28-44-3', 'LV29-114-3', 'SO178-12-3'])], test_size = 0.2, shuffle = True, random_state = 24) s2_ca_train, _ = train_test_split(X[merge_df.core.isin(['LV28-44-3', 'LV29-114-3'])], test_size = 0.2, shuffle = True, random_state = 24) # - print(s1_X_train.shape, s2_toc_train.shape, s2_ca_train.shape) # The sum of carbonate and TOC training data amounts fit to the histogram, respectively. for X_train in [s1_X_train, s2_ca_train, s2_toc_train, np.vstack((s1_X_train, s2_ca_train)), np.vstack((s1_X_train, s2_toc_train))]: fig, ax = plt.subplots(1, 1) ax.plot(range(2048), X_train.max(axis=0)) ax.plot(range(2048), X_train.min(axis=0)); plt.xlim(0, 520) # I don't have enough time to fine-tune a figure for all these spectra in different steps and analytes so I plot the figure of the 1st+2nd scale ups only for now. # + fig, axes = plt.subplots(1, 2, figsize=(7.2, 3), sharex='row', sharey='row') axes[0].plot(range(2048), np.vstack((s1_X_train, s2_ca_train)).max(axis=0), label='Max.') axes[0].plot(range(2048), np.vstack((s1_X_train, s2_ca_train)).min(axis=0), label='Min.') axes[0].set_xlim(0, 520) axes[0].set_ylabel('Normalized intensity') axes[0].set_xlabel('Channel, Carbonate') axes[1].plot(range(2048), np.vstack((s1_X_train, s2_toc_train)).max(axis=0), label='Max.') axes[1].plot(range(2048), np.vstack((s1_X_train, s2_toc_train)).min(axis=0), label='Min.') axes[1].set_xlabel('Channel, TOC') axes[1].legend() fig.subplots_adjust(wspace=.04) fig.savefig('results/spectral_range_{}.png'.format(date)) print(date) # - spe_list = [] ind_list = [] for X_train, label in zip([s1_X_train, s2_ca_train, s2_toc_train, np.vstack((s1_X_train, s2_ca_train)), np.vstack((s1_X_train, s2_toc_train))], ['s1 whole', 's2 ca', 's2 toc', 's1+s2 ca', 's1+s2 toc']): spe_list.append(X_train.max(axis=0)) spe_list.append(X_train.min(axis=0)) ind_list.append('{} max.'.format(label)) ind_list.append('{} min.'.format(label)) pd.DataFrame(spe_list, index=ind_list) pd.DataFrame(spe_list, index=ind_list).to_csv('results/spectral_range_{}.csv'.format(date)) print(date)
plot_for_paper_01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # My First Post in FastPages Blog # > Testing FastPages as my prefered Blogging Platform # # - toc: true # - badges: true # - comments: true # - categories: [jupyter] # # About # # So I'm just checking out the new fastpages blogging platform and this is my first post on this platform
_notebooks/11-04-20-jithin_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # Modelling an Advanced TablePulseTemplate # # [The SimpleTablePulse example](00SimpleTablePulse.ipynb) shows how a simple parametrized ```TablePT``` on one channel can implemented and how the interpolation works. # # This example demonstrates how to set up a more complex ```TablePT```. This means we will include multiple channels and use expressions for times and voltages. # # First lets reimplement the pulse from the previous example but this time with a second channel `'B'`, that has the same voltage values but negative. To do this, we extend the entry dict by a second item with the channel ID `'B'` as key and the entry list as value. # # Then we plot it to see that it actually works. # + # %matplotlib notebook from qupulse.pulses.plotting import plot from qupulse.pulses import TablePT param_entries = {'A': [(0, 0), ('ta', 'va', 'hold'), ('tb', 'vb', 'linear'), ('tend', 0, 'jump')], 'B': [(0, 0), ('ta', '-va', 'hold'), ('tb', '-vb', 'linear'), ('tend', 0, 'jump')]} mirror_pulse = TablePT(param_entries) parameters = {'ta': 2, 'va': 2, 'tb': 4, 'vb': 3, 'tend': 6} _ = plot(mirror_pulse, parameters, sample_rate=100) # - # You may have noticed that we already used an expression in the entry list: `'-va'` and `'-vb'`. Of course we can also do a bit more complex things with these than a simple negation. Let's have a look at the next example where we use some simple mathematical oeprators and built-in functions: expr_pulse = TablePT({'A': [(0, 'a_0'), ('t_1', 'a_0 + exp(theta)', 'hold'), ('t_2', 'Abs(x_0 - y_0)', 'linear')], 'B': [(0, 'b_0'), ('t_1*(b_0/a_0)', 'b_1', 'linear'), ('t_2', 'b_2')]}) _ = plot(expr_pulse, dict(a_0=1.1, theta=2, x_0=0.5, y_0=1, t_1=10, t_2=25, b_0=0.6, b_1=6, b_2=0.4)) # __Is there a requirement that all channels have the same duration?__ # # No. The shorter channels stay on their last value until the last channel is finished. The duration of the complete pulse template is given as the corresponding expression: # + param_entries = {'A': [(0, 0), ('t_A/2', 'va', 'hold'), ('t_A', 'vb', 'linear')], 'B': [(0, 0), ('t_B / 2', 'va', 'hold'), ('t_B', 'vb', 'linear')]} c_pulse = TablePT(param_entries) print(c_pulse.duration) _ = plot(c_pulse, dict(t_A=4, t_B=5, va=1, vb=2, t_wait = 2), sample_rate=100) # - # As you see channel `'A'` only was defined until 4ns and holds this level to the end of the pulse.
doc/source/examples/01AdvancedTablePulse.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .scala // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: Scala 2.11 // language: scala211 // name: scala211 // --- // Note: Running this for the first time will take a little while due to the kernel downloading some more dependencies. util.Properties.versionString
notebooks/Scala-Version.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [Root] # language: python # name: Python [Root] # --- # %matplotlib inline import pandas as pd import pylab as plt import seaborn from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import json import pandas as pd import statsmodels.api as sm from sklearn.cross_validation import KFold from sklearn.metrics import confusion_matrix from sklearn import preprocessing from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier as RF from sklearn.neighbors import KNeighborsClassifier as KNN import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc from sklearn.utils import shuffle from sklearn.metrics import roc_curve, auc import pylab from sklearn import svm from sklearn.linear_model import LogisticRegression from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.ensemble import RandomForestClassifier # from mpl_toolkits.basemap import Basemap import re import pylab as plt import seaborn from sklearn.linear_model import LinearRegression import numpy.random as nprnd import random # # Introduction # # # In this homework, you'll be required to load in a dataset which has about 500 features. By using # Lasso ($L^1$) regression, we'll find the optimal constraint on the $L^1$ norm which gives us the best # $R^2$. Then we'll plot the results. # # Recall we minimize the following on ** training data: $(x_i,y_i)$** # # $$\min_{\beta} \frac{1}{N} \sum_{i=1}^N (y_i - \beta \cdot x_i)^2 + \lambda \|\beta \|_{L^1}.$$ # # # Denoting $\beta_{\lambda}$ as the minimum of the above, we then choose $\lambda$ to maximize $R^2$ on **testing data: $(x_j,y_j)$** # # $$ \max_{\lambda} 1 - \frac{\sum_{j} (y_j - \beta_{\lambda} \cdot x_j)^2}{\sum_j (y_j - \bar y)^2}$$ # # # Lasso Regularization # ## Problem 1 # a) Load in hw2data.csv from ../data into a pandas dataframe. # + # load data #pd.set_option('display.max_columns', 500) df = pd.read_csv('/Users/apple/python-introduction-caitlinwang/data/hw2data.csv') df.head() # - # b) Set to be the y variable in the dataframe from a and X to be the remaining features. X = df.drop(labels='y',axis=1) y = df['y'] # c) As shown in the Booking.com example, using Lasso regression, find the regularization strength # which optimizes the $R^2$. # # **Hint:** Take a range of alpha from `np.logspace(-8,-3,1000)` # + X = X.as_matrix().astype(np.float) y = y.as_matrix().astype(np.float) X_train, X_test,y_train,y_test = train_test_split(X,y, test_size = 0.2) scaler = preprocessing.StandardScaler().fit(X_train) X_train = scaler.transform(X_train) scaler = preprocessing.StandardScaler().fit(X_test) X_test = scaler.transform(X_test) # + #split data to training and testing part import numpy # parameter setting alphas = np.logspace(-8, 0, 1000) clf = Lasso() # coefs = numpy.ones([1000,500]) i = 0 scores=[] # use Lasso to do the regularization for a in alphas: clf.set_params(alpha=a) clf.fit(X_train, y_train) scores.append(clf.score(X_test,y_test)) # coefs[i,:] = clf.coef_ # i +=1 # # plot coefficient change # fig = plt.figure(1) # fig.set_size_inches(10,10) # axes = fig.add_subplot(1,1,1) # axes.plot(alphas, coefs) # axes.set_xscale('log') # axes.set_xlim(axes.get_xlim()[::-1]) # reverse axis # plt.xlabel('alpha') # plt.ylabel('weights') # plt.title('Ridge coefficients as a function of the regularization') # plt.axis('tight') index_opt = np.array(scores).argmax() opt_alpha = alphas[index_opt] opt_score = max(scores) #plot the R^2 fig = plt.figure(2) fig.set_size_inches(10,10) axes = fig.add_subplot(1,1,1) axes.plot(alphas, scores) axes.set_xscale('log') axes.set_xlim(axes.get_xlim()[::-1]) # reverse axis plt.xlabel('alpha') plt.ylabel('R^2') plt.title('R^2 when do LASSO Regression') plt.axis('tight') plt.show() print "index",index_opt print "alpha",opt_alpha print "Best score", opt_score # - # d) Plot the training perforamnce versus the testing performance, and observe whree the test performance is # maximized. I've written an outline of the code you need. # + import matplotlib.pyplot as plt import numpy as np alphas = np.logspace(-8, -1, 1000) clf = Lasso() train_errors = list() test_errors = list() for alpha in alphas: clf.set_params(alpha=alpha) clf.fit(X_train, y_train) train_errors.append(clf.score(X_train, y_train)) test_errors.append(clf.score(X_test, y_test)) i_alpha_optim = np.argmax(test_errors) alpha_optim = alphas[i_alpha_optim] print("Optimal regularization parameter : %s" % alpha_optim) # Estimate the coef_ on full data with optimal regularization parameter clf.set_params(alpha=alpha_optim) coef = clf.fit(X, y).coef_ coef_ = clf.fit(X_train,y_train).coef_ fig = plt.figure(1) fig.set_size_inches(10,10) plt.semilogx(alphas, train_errors, label='Train') plt.semilogx(alphas, test_errors, label='Test') plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k', linewidth=3, label='Optimum on test') plt.legend(loc='lower left') # plt.ylim([0, 1.2]) plt.xlabel('Regularization parameter') plt.ylabel('Performance') # Show estimated coef_ vs true coef fig = plt.figure(2) fig.set_size_inches(10,10) plt.subplot(2, 1, 2) plt.plot(coef, label='True coef') plt.plot(coef_, label='Estimated coef') plt.legend() plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26) plt.show() # - # e) Plot the top coefficients based on this optimal paramter. Why do you think so many are zero? # + X = df.drop(labels='y',axis=1) clf.set_params(alpha=alpha_optim) coef_ = clf.fit(X_train,y_train).coef_ df_coeffs = pd.DataFrame({'coeffs':coef_, 'name':X.columns.values}) df_coeffs[-10:-1].plot(y='coeffs',kind='bar') df_coeffs=df_coeffs.sort(['coeffs']) df_coeffs[-10:-1].plot(y='coeffs',kind='bar') # - # For the figure one,I plot the last ten coeffecient without sorting, as we can see there are a lot 0s in the coeffecients. The reason for it is that we are using LASSO to do the regularization, using the L1 norm penalty tends to set all the coefficents to zeros and eliminating the unimportant features. # f) Compute the $R^2$ with the optimal coefficient found above on 5 folds using cross_val_score and plot the # results. Does the model work well on all random subsets? # + from sklearn.model_selection import cross_val_score from sklearn.model_selection import ShuffleSplit clf = Lasso(alpha=alpha_optim) scores = cross_val_score(clf, X, y, cv=5) plt.ylim([-1,1]) plt.xlabel('lambda') plt.ylabel('R^2') plt.title('Performance on 5 folds with optimal alpha =') plt.bar(range(1,6),scores) plt.show() # Random cross validation scores cv = ShuffleSplit(n_splits=5, test_size=0.2, random_state=42) scorer = cross_val_score(clf, X, y, cv=cv) plt.bar(range(1, 6), scorer) plt.title('Random cross validation scores') plt.show() # - # As we can see the model works well the R^2 is pretty approximate to 1 and the standard deviation is small. # And then we try to shuffle the data and choose the subset randomly and as we can see we still have good results. So it's a good model # f) Repeat e) but using cross validation. Use error bars on the features which are the standard deviation of the # coefficiens obtained above. For this problem I"ll walk you through the code. You just need to apply your optimal # $\alpha$ found above. # + from sklearn.cross_validation import KFold from sklearn import preprocessing def run_cv_coeffs(X,y,clf_class,**kwargs): # Construct a kfolds object kf = KFold(len(y),n_folds=5,shuffle=True) y_pred = y.copy() coeffs=[] # Iterate through folds for train_index, test_index in kf: X_train, X_test = X[train_index], X[test_index] y_train = y[train_index] # Initialize a classifier with key word arguments clf = clf_class(**kwargs) clf.fit(X_train,y_train) y_pred[test_index] = clf.predict(X_test) coeffs.append(clf.coef_) return coeffs scaler = preprocessing.StandardScaler() X_scaled = X.as_matrix().astype(np.float) X_scaled = scaler.fit_transform(X) coeffs=run_cv_coeffs(X_scaled,np.array(y),Lasso,alpha=alpha_optim) # - def get_coeffs(coeffs): """compute the average coefficients and the standard deviation """ coeffs_avgd = [(coeffs[0][i] + coeffs[1][i] + coeffs[2][i] + coeffs[3][i] + coeffs[4][i])/5 for i in range(0,len(X.columns))] coeffs_std = [np.std([coeffs[0][i],coeffs[1][i],coeffs[2][i],coeffs[3][i],coeffs[4][i]]) for i in range(0,len(X.columns))] return coeffs_avgd, coeffs_std coeffs_avg,coeffs_std=get_coeffs(coeffs) dfCoeffs = pd.DataFrame({'type':X.columns.values, 'coef':coeffs_avg, 'std':coeffs_std}) dfCoeffs = dfCoeffs[(dfCoeffs['coef']>1) |(dfCoeffs['coef']<-1) ] plt.figure(figsize=(15,15)) dfCoeffs_sorted = dfCoeffs.sort(['coef'])[::-1] yerr_vals = dfCoeffs_sorted['std'].values dfCoeffs_sorted.plot(x='type',y='coef',kind='bar',yerr=yerr_vals,figsize=(15,15))
.ipynb_checkpoints/Homework 2 - Regularization with Lasso -checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # In this notebook the FSC curves from some relion star files are plotted from StarIO import read_star, write_star # Star IO functions from here: https://github.com/cschlick/StarIO import pandas as pd # %matplotlib inline df_dict = read_star("examples/run_it013_half2_model.star") df_dict.keys() df = df_dict["model_class_1"] df df.plot(y="rlnGoldStandardFsc",x="rlnResolution",style="-")
Plot FSC.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import json import sys # + def read_json(input_file): with open(input_file) as f: line = f.readlines(2) print(line) # - read_json('data_1513309512.json') # + active="" #
12_Hangman_P2/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Notebook Contents # In this notebook the idea os to generate the necessary enviornment lattices for the multi-agent system which are based on calculation of Eucledian Distances. # Hence the lattices which are generated in this notebook include. # 1. Distance form Facades (NSEW) # 2. Distance from Roof / FLoor # 3. Quiteness lattice (Distance from source of sound) # # The steps followed in the notebook inculde : # 1. Load all the assets required for simulation # 2. Load the excel files showing the points of interest (In Quiteness Lattice it is the co-ordinates of the Sound source) # 3. Calculate the distances using Scipy https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html # 4. Vizualise the lattices on the building # 5. Save the lattices as pickle objects # # # Initilization import os import sys import topogenesis as tg import pickle import pyvista as pv import pandas as pd import trimesh as tm import scipy as sc from scipy.spatial import distance import itertools from itertools import cycle import numpy as np import numpy.ma as ma np.random.seed(0) np.set_printoptions(threshold=sys.maxsize) from ladybug.sunpath import Sunpath # + #Design Details Self_development_plots_path = os.path.relpath('Site_self_development_plots.obj') Self_development_backyards_path = os.path.relpath('Site_self_development_backyards.obj') Site_buildings_path = os.path.relpath('Site_buildings.obj') Site_green_areas_path = os.path.relpath('Site_green_areas.obj') Site_roads_path = os.path.relpath('Site_base_roads.obj') Site_context_shading_path= os.path.relpath('Site_surrounding_buildings_for_shading.obj') Offices_block= os.path.relpath('Site_office_blocks.obj') # Site details Site_base_path = os.path.relpath('Site_base_block.obj') Site_surrounding_buildings_path = os.path.relpath('Site_surrounding_buildings.obj') Site_water_bodies_path = os.path.relpath('Site_water_bodies.obj') Site_roads_path = os.path.relpath('Site_roads.obj') Site_other_buildings_path = os.path.relpath('Site_other_buildings.obj') # load the mesh from file # Design elements Self_development_plots_mesh = tm.load(Self_development_plots_path) Self_development_backyards_mesh = tm.load(Self_development_backyards_path) Site_building_mesh = tm.load(Site_buildings_path) Site_green_areas_mesh = tm.load(Site_green_areas_path) Site_roads_mesh = tm.load(Site_roads_path) Site_context_shading_mesh = tm.load(Site_context_shading_path) Site_offices_zone_mesh = tm.load(Offices_block) #Site elements Site_base_mesh = tm.load(Site_base_path) Site_surrounding_buildings_mesh = tm.load(Site_surrounding_buildings_path) Site_water_bodies_mesh = tm.load(Site_water_bodies_path) Site_roads_mesh = tm.load(Site_roads_path) Site_other_buildings_mesh = tm.load(Site_other_buildings_path) # Check if the mesh is watertight #print(envelope_mesh.is_watertight) #print(context_mesh.is_watertight) # - # # Define Points for Quiteness # ## import from Rhino # Csv to points Complete_file = pd.read_excel('Quiteness_points.xlsx', sheet_name=0,engine='openpyxl',header = None ) design_criterias= list(Complete_file.head(n=0)) array_excel = Complete_file.to_numpy() # Csv to points Complete_file_GA = pd.read_excel('Points_of_interest.xlsx', sheet_name=0,engine='openpyxl',header = None ) design_criterias_GA= list(Complete_file_GA.head(n=0)) array_excel_GA = Complete_file_GA.to_numpy() Noise_sources = array_excel.T Noise_sources_GA = array_excel_GA.T # # Define Points for Closeness Facades len(Noise_sources_GA) # # Vizualise the meshes and points # + # convert mesh to pv_mesh def tri_to_pv(tri_mesh): faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3) pv_mesh = pv.PolyData(tri_mesh.vertices, faces) return pv_mesh # initiating the plotter p = pv.Plotter(notebook=True) # adding the meshes # Design meshes p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#f4acb7') p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd',opacity= 0.5) #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_surrounding_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) #p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd',opacity= 0.5) p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_points( Noise_sources, color='#e63946') # plotting p.show(use_ipyvtk=True) # + # convert mesh to pv_mesh def tri_to_pv(tri_mesh): faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3) pv_mesh = pv.PolyData(tri_mesh.vertices, faces) return pv_mesh # initiating the plotter p = pv.Plotter(notebook=True) # adding the meshes # Design meshes p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#f4acb7',opacity = 0.1) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd',opacity= 0.5) p.add_mesh(tri_to_pv(Site_offices_zone_mesh), color='#bdb2ff') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_surrounding_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) ##p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd',opacity= 0.5) p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_points( Noise_sources_GA, color='#e63946') # plotting p.show(use_ipyvtk=True) # - # # Import lattice # loading the lattice from csv lattice_path = os.path.relpath('voxelized_envelope_3m_voxel_size_for_offices.csv') envelope_lattice = tg.lattice_from_csv(lattice_path) envelope_lattice.size # # Visualize the Context Mesh + Envelope Lattice # + # convert mesh to pv_mesh def tri_to_pv(tri_mesh): faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3) pv_mesh = pv.PolyData(tri_mesh.vertices, faces) return pv_mesh # initiating the plotter p = pv.Plotter(notebook=True) p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes # Design meshes p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_offices_zone_mesh), color='#bdb2ff',opacity= 0.8) #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_surrounding_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') # plotting p.add_points( Noise_sources_GA, color='#e63946') p.show(use_ipyvtk=True,screenshot=' Closeness_to_grren_Areas_problem.png') # - # # Find the voxel Eucledian coordinates # convert to lattice init_lattice = envelope_lattice +1 availability_lattice_voxels = tg.to_lattice(init_lattice, init_lattice) voxel_coordinates= availability_lattice_voxels.centroids flattened_lattice = envelope_lattice.flatten() # # Find distances for Quiteness # The distance from each source of sound is calculated and the minimum distance from them is choosen # + Eucledian_distance = sc.spatial.distance.cdist(# convert mesh to pv_mesh def tri_to_pv(tri_mesh): faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3) pv_mesh = pv.PolyData(tri_mesh.vertices, faces) return pv_mesh # initiating the plotter p = pv.Plotter(notebook=True) p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes # Design meshes p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_offices_zone_mesh), color='#bdb2ff',opacity= 0.8) #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_surrounding_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') # plotting p.add_points( Noise_sources_GA, color='#e63946') p.show(use_ipyvtk=True,screenshot=' Closeness_to_grren_Areas_problem.png'),voxel_coordinates) # - noise_from_each_source = Eucledian_distance.T Average_quiteness_indexing= np.argmin(noise_from_each_source, axis=1) Average_quiteness_values = [] for branch,index in zip(noise_from_each_source,Average_quiteness_indexing): Average_quiteness_values.append(branch[index]) Quiteeness_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Average_quiteness_values))]) padded_array = np.array(Quiteeness_lattice_padded) Quiteness_lattice_np = Quiteeness_lattice_padded.reshape(envelope_lattice.shape) Quiteness_lattice =tg.to_lattice(Quiteness_lattice_np, Quiteness_lattice_np.shape) # # Find distances for Green Areas Eucledian_distance_GA = sc.spatial.distance.cdist(Noise_sources_GA,voxel_coordinates) noise_from_each_source_GA = Eucledian_distance_GA.T Average_quiteness_indexing_GA= np.argmin(noise_from_each_source_GA, axis=1) Average_quiteness_values_GA = [] for branch,index in zip(noise_from_each_source_GA,Average_quiteness_indexing_GA): Average_quiteness_values_GA.append(branch[index]) Quiteeness_lattice_padded_GA= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Average_quiteness_values_GA))]) padded_array_GA = np.array(Quiteeness_lattice_padded_GA) Quiteness_lattice_np_GA = Quiteeness_lattice_padded_GA.reshape(envelope_lattice.shape) Quiteness_lattice_GA =tg.to_lattice(Quiteness_lattice_np_GA, Quiteness_lattice_np_GA.shape) # # Find distances for Facade calculations Y_coordinates= voxel_coordinates.T[1].flatten() X_coordinates= voxel_coordinates.T[0].flatten() # + Building_classification_north_south_facades =[] for center in Y_coordinates: if center >= 18 and center <= 30: Building_classification_north_south_facades.append(center-17) #print("1st") elif center >= 40 and center <= 82: Building_classification_north_south_facades.append(center-41) # print("2nd") elif center >= 82: Building_classification_north_south_facades.append(center-83) #print("3rd") else: Building_classification_north_south_facades.append(center) # + Building_classification_east_west_facades =[] for center,value in zip(Y_coordinates,X_coordinates): if center <= 90: Building_classification_east_west_facades.append(10-value) #print("1st") elif center >= 91: Building_classification_east_west_facades.append(130-value) #print("2nd") # - # # Facade Distances to North Facade Distance_inverse_y_axis_north = [i for i in reversed(Building_classification_north_south_facades)] Distance_north_facade_full_lattice= np.tile(Distance_inverse_y_axis_north,352) North_facade_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Distance_inverse_y_axis_north))]) North_facade_array = np.array(North_facade_lattice_padded) north_facade_lattice_np = North_facade_array.reshape(envelope_lattice.shape) North_facade_lattice =tg.to_lattice(north_facade_lattice_np, north_facade_lattice_np.shape) # # Facade Distances to South Facade South_facade_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Building_classification_north_south_facades))]) Souh_facade_array = np.array(South_facade_lattice_padded) South_facade_lattice_np = Souh_facade_array.reshape(envelope_lattice.shape) South_facade_lattice =tg.to_lattice(South_facade_lattice_np, South_facade_lattice_np.shape) # # Facade Distances to West Facade West_facade_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Building_classification_east_west_facades))]) West_facade_array = np.array(West_facade_lattice_padded) West_facade_lattice_np = West_facade_array.reshape(envelope_lattice.shape) West_facade_lattice =tg.to_lattice(West_facade_lattice_np, West_facade_lattice_np.shape) # # Facade Distances to East Facade Distance_inverse_y_axis_west = [i for i in reversed(Building_classification_east_west_facades)] West_facade_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Distance_inverse_y_axis_west))]) East_facade_array = np.array(West_facade_lattice_padded) East_facade_lattice_np = East_facade_array.reshape(envelope_lattice.shape) East_facade_lattice =tg.to_lattice(East_facade_lattice_np, East_facade_lattice_np.shape) # # Find distances from Ground calculations Distance_from_ground_complete_lattice = voxel_coordinates.T[2] envelope_lattice.size Distance_from_ground_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Distance_from_ground_complete_lattice))]) padded_ground_distance_array = np.array(Distance_from_ground_lattice_padded) padded_ground_distance_array_np = padded_ground_distance_array.reshape(envelope_lattice.shape) Distance_from_ground = tg.to_lattice(padded_ground_distance_array_np, padded_ground_distance_array_np.shape) envelope_lattice.shape # # Find distances from Roof calculations all_heights_reversed= [i for i in reversed(voxel_coordinates.T[2])] Distance_from_roof_complete_lattice = np.tile(all_heights_reversed, int(envelope_lattice.size/11)) Distance_from_roof_lattice_padded= np.array([num if boolean else 0 for boolean, num in zip(flattened_lattice, cycle(Distance_from_roof_complete_lattice))]) padded_roof_distance_array = np.array(Distance_from_roof_lattice_padded) padded_roof_distance_array_np = padded_roof_distance_array.reshape(envelope_lattice.shape) Distance_from_roof = tg.to_lattice(padded_roof_distance_array_np, padded_roof_distance_array_np.shape) # # Visualize the Quiteness Lattice # + ###### initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Quiteness"] = Quiteness_lattice.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="magma", clim=clim, opacity=opacity, opacity_unit_distance=5,) p.add_points( Noise_sources, color='#e63946') # plotting #p.camera_position = [(87, 269, 373), (-300, 70, -0), (0, 0, 1)] #p.image_depth p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.show(use_ipyvtk=True,screenshot='Quiteness_lattice.png') # - # # Viz Closeness to Green areas # + ###### initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Closeness to Green Areas"] = Quiteness_lattice_GA.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="magma", clim=clim, opacity=opacity, opacity_unit_distance=5,) #p.add_points( Noise_sources, color='#e63946') # plotting #p.camera_position = [(87, 269, 373), (-300, 70, -0), (0, 0, 1)] #p.image_depth p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.add_points( Noise_sources_GA, color='#9bf6ff') p.show(use_ipyvtk=True,screenshot=' Closeness_to_grren_Areas_viz.png') # - p.camera_position # # Visualize the N Facade Lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from North Facade"] = North_facade_lattice.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = [0, 0.75, 0.7, 0.75, 0.8] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) # plotting p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.show(use_ipyvtk=True,screenshot='Distance_from_North_Facade.png') # - # # Visualize the S Facade Lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from South Facade"] = South_facade_lattice.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = [0, 0.75, 0.7, 0.75, 0.8] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) # plotting p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.show(use_ipyvtk=True,screenshot='Distance_from_South_Facade.png') # - # # Visualize the E Facade Lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from East Facade"] = East_facade_lattice.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5 opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) p.camera_position = [(281.2198164557486, 195.20681864151288, 263.2631846148646), (-125.74100344423854, 28.782304005903896, -35.52262026413212), (-0.4754479563154929, -0.31327193009210785, 0.8220766014501246)] # plotting p.show(use_ipyvtk=True,screenshot='Distance_from_East_Facade.png') # - # # Visualize the W Facade Lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from West Facade"] = West_facade_lattice.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5 opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) # plotting p.camera_position = [(281.2198164557486, 195.20681864151288, 263.2631846148646), (-125.74100344423854, 28.782304005903896, -35.52262026413212), (-0.4754479563154929, -0.31327193009210785, 0.8220766014501246)] p.show(use_ipyvtk=True,screenshot='Distance_from_West_Facade.png') # - # # Visualize the Terrace Lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from Roof"] = Distance_from_roof.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5 opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) # plotting p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.show(use_ipyvtk=True,screenshot='Distance_from_Roof.png') # - # # Visualize the Ground lattice # + # initiating the plotter p = pv.Plotter(notebook=True) # Create the spatial reference grid = pv.UniformGrid() # Set the grid envelope_lattice: shape because we want to inject our values grid.dimensions = envelope_lattice.shape # The bottom left corner of the data set grid.origin = envelope_lattice.minbound # These are the cell sizes along each axis grid.spacing = envelope_lattice.unit # Add the data values to the cell data grid.point_arrays["Distance from ground"] = Distance_from_ground.flatten(order="F") # Flatten the Lattice # fast visualization of the lattice envelope_lattice.fast_vis(p) # adding the meshes #p.add_mesh(tri_to_pv(Self_development_plots_mesh), color='#b8f2e6') p.add_mesh(tri_to_pv(Self_development_backyards_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_building_mesh), color='#ff9b54',opacity = 0.3) p.add_mesh(tri_to_pv(Site_green_areas_mesh), color='#8ac926') p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') #Site meshes p.add_mesh(tri_to_pv(Site_base_mesh), color='#faedcd') p.add_mesh(tri_to_pv(Site_other_buildings_mesh), color='#cdb4db') p.add_mesh(tri_to_pv(Site_water_bodies_mesh), color='#bde0fe',opacity= 0.5) p.add_mesh(tri_to_pv(Site_roads_mesh), color='#adb5bd') p.add_mesh(tri_to_pv(Site_context_shading_mesh), color='#cdb4db') # adding the volume opacity = [0, 0.75, 0, 0.75, 1.0] clim = [0, 100] p.add_volume(grid, cmap="viridis", opacity=opacity, shade=False) # plotting p.camera_position = [(-30.918138503987137, 252.13468433505227, 141.27150258463084), (-132.52727934148325, 29.061346168534897, -31.80320438629297), (-0.1996427382461422, -0.5422754627817726, 0.8161373043369582)] p.show(use_ipyvtk=True,screenshot='Distance_from_Ground.png') # - North_facade_lattice # # Pickle all Lattices # + #Quiteness_mtrx = pickle.dump( Quiteness_lattice, open( "Quiteness_lattice.p", "wb" ) ) # + #North_facade_mtrx = pickle.dump( North_facade_lattice, open( "North_facade_lattice.p", "wb" ) ) # + #South_facade_mtrx = pickle.dump( South_facade_lattice, open( "South_facade_lattice.p", "wb" ) ) # + #East_facade_mtrx = pickle.dump( East_facade_lattice, open( "East_facade_lattice.p", "wb" ) ) # + #West_facade_mtrx = pickle.dump( West_facade_lattice, open( "West_facade_lattice.p", "wb" ) ) # + #Terrace_facade_mtrx = pickle.dump( Distance_from_roof, open( "Distance_from_roof.p", "wb" ) ) # + #Ground_facade_mtrx = pickle.dump( Distance_from_ground, open( "Distance_from_ground.p", "wb" ) ) # + #Closeness_to_green_areas_mtrx = pickle.dump( Quiteness_lattice_GA, open( "Closeness_to_green_areas.p", "wb" ) ) # -
03.Unit_assignment_problem/Category_two/Enviornment_Simulations/Eucledian Lattices Notebook.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import requests import pandas as pd from bs4 import BeautifulSoup import os def getUrlOfImdbImg(imdbid): url = f'https://www.imdb.com/title/tt{str(imdbid).zfill(7)}/' response = requests.get(url) content = response.content soup = BeautifulSoup(content) div = soup.find("div", {"class": "poster"}) img = div.find('img') url = img['src'] return url data_path = os.path.join(os.environ['USERPROFILE'], 'Desktop\heckthon\QMDB\data\processed_data\movies_with_kws.csv') df = pd.read_csv(data_path) ids = df['imdbId'].values for i in range(len(urls), len(ids)): print(i) imdbid = ids[i] urls.append(getUrlOfImdbImg(imdbid)) df['imgUrl'] = urls df.to_csv(data_path, index=False) len(urls) len(df) len(urls)
cloud/ScrapePicture.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="CqoJTEpMwYEX" # # Hypothesis Testing # + id="SRyalNhBwYEg" import numpy as np import scipy.stats as st # + [markdown] id="BfLPEqeWwYEk" # ## Section 1 : z-Test # + [markdown] id="36yUehGzwYEl" # ### Example 1.1 : Ages of Medical doctors # A researcher believes that the mean age of medical doctors in a large hospital system is older than the average age of doctors in the United States, which is 46. Assume the population standard deviation is 4.2 years. A random sample of 30 doctors from the system is selected, and the mean age of the sample is 48.6. Test the claim at ฮฑ = 0.05. # + id="Aoe9SYQjwYEn" #H0 : ฮผ = 46, Ha : ฮผ > 46 n = 30 xbar = 48.6 mu = 46 sigma = 4.2 alpha = 0.05 # + id="6BpB2xgLwYEp" colab={"base_uri": "https://localhost:8080/"} outputId="7bcfee27-1bdb-4471-fa01-dccaa67a02de" z_critical = abs(st.norm.ppf(alpha)) #Absolute value taken as the it's a right-tailed test and the original value will be negative z_critical # + id="d1FOOo4gwYEs" colab={"base_uri": "https://localhost:8080/"} outputId="0f518772-d5f7-48fb-8fa6-3aa20d78be7e" z = (xbar-mu)/(sigma/np.sqrt(n)) z # + id="dKy0LaOqwYEu" colab={"base_uri": "https://localhost:8080/"} outputId="1a495b79-21a8-45ee-ce1e-3466b4d387a8" if (z < z_critical): #Right-tailed test print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis") # + [markdown] id="dLrvzvqLwYEv" # ## Section 2 : z-Test using P-value # + [markdown] id="oIgM_qrgwYEw" # ### Example 2. 1 : Wind Speed # # # A researcher claims that the average wind speed in a certain city is 8 miles per hour. A sample of 32 days has an average wind speed of 8.2 miles per hour. The standard deviation of the population is 0.6 mile per hour. At ฮฑ = 0.05, is there enough evidence to reject the claim? Use the P-value method. # + id="oIjmOuuewYEx" #H0 : ฮผ = 8 and Ha : ฮผ != 8 n = 32 xbar = 8.2 mu = 8 sigma = 0.6 alpha = 0.05 # + id="ZcqzVHkMwYEz" colab={"base_uri": "https://localhost:8080/"} outputId="1e59be88-0a0e-44c2-8d33-cf641ae85c62" z = (xbar-mu)/(sigma/np.sqrt(n)) z # + id="vpht1-vUwYE0" colab={"base_uri": "https://localhost:8080/"} outputId="c1730ecc-0b13-45aa-df6a-1736a8ed568e" p_val = (1 - st.norm.cdf(abs(z))) * 2 p_val # + id="a5xB5hGNwYE1" colab={"base_uri": "https://localhost:8080/"} outputId="e3474634-37d3-4227-badb-d95e8987b98c" if (p_val > alpha): print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis") # + [markdown] id="PKbTSgeUwYE2" # ## Section 3 : t-Test # + [markdown] id="QHbI7nfxwYE3" # ### Example 3.1 : Hospital Infections # A medical investigation claims that the average number of infections per week at a ยญhospital in southwestern Pennsylvania is 16.3. A random sample of 10 weeks had a mean number of 17.7 infections. The sample standard deviation is 1.8. Is there enough evidence to reject the investigatorโ€™s claim at ฮฑ = 0.05? Assume the variable is normally distributed. # + id="tXt4hXfMwYE3" #H0 : ฮผ = 16.3, Ha : ฮผ != 16.3 n = 10 degrees_of_freedom = n-1 xbar = 17.7 mu = 16.3 s = 1.8 alpha = 0.05 # + id="TR61SnfpwYE5" colab={"base_uri": "https://localhost:8080/"} outputId="517285ab-2127-45e9-b817-3fe03e37b506" t = (xbar - mu)/(s / np.sqrt(n)) t # + id="cghi5O50wYE6" colab={"base_uri": "https://localhost:8080/"} outputId="17727ba9-04f6-4a70-8d93-0063475ecb0c" t_critical = st.t.ppf(alpha/2, degrees_of_freedom) t_critical # + id="3yfDRP_cwYE7" colab={"base_uri": "https://localhost:8080/"} outputId="e107dcde-d2d0-4c56-da6d-c729c5556f1f" if (abs(t) > abs(t_critical)): #Absolute value taken as the it's a two-tailed test and the original t_critical value might be negative print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis") # + [markdown] id="jAv5OBMMwYE8" # ## Section 4 : t-Test using P-value # + [markdown] id="-n_nLH5GwYE8" # ### Example 4.1 : Joggerโ€™s Oxygen Uptake # A physician claims that joggersโ€™ maximal volume oxygen uptake is greater than the average of all adults. A random sample of 15 joggers has a mean of 40.6 milliliters per kilogram (ml/kg) and a standard deviation of 6 ml/kg. If the average of all adults is 36.7 ml/kg, is there enough evidence to support the physicianโ€™s claim at ฮฑ = 0.05? Assume the variable is normally distributed. # + id="ZaXBybM8wYE8" #H0 : ฮผ = 36.7, Ha : ฮผ > 36.7 n = 15 degrees_of_freedom = n-1 xbar = 40.6 mu = 36.7 s = 6 alpha = 0.05 # + id="oxPgEnYcwYE9" colab={"base_uri": "https://localhost:8080/"} outputId="b4ff47cc-f7fe-4739-a95e-b6107b56d71a" t = (xbar - mu)/(s / np.sqrt(n)) t # + id="YrVjQG0KwYE9" colab={"base_uri": "https://localhost:8080/"} outputId="3c693d87-3ad1-44d5-d9e8-56db4090fc05" p_val = (1 - st.t.cdf(abs(t), degrees_of_freedom)) #"1 - cdf" because it's a right-tailed test p_val # + id="lohi1A1FwYE-" colab={"base_uri": "https://localhost:8080/"} outputId="1427fd17-9aa3-4ccf-dc05-364d4ae6029e" if (p_val > alpha): print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis") # + [markdown] id="69DcbUCHwYE_" # ## Section 5 : Chi-Square Test # + [markdown] id="x2jBSHBswYE_" # ### Example 5.1 : IQ Test # A psychologist wishes to see if the variance in IQ of 10 of her counseling patients is less than the variance of the population, which is 225. The variance of the IQs of her 10 patients was 206. Test her claim at ฮฑ = 0.05. # + id="dT0XxmJRwYFA" #H0 : ฯƒ2 = 225, Ha : ฯƒ2 < 225 n = 10 degrees_of_freedom = n-1 s_square = 206 sigma_square = 225 alpha = 0.05 # + id="9QyBTRk8wYFA" colab={"base_uri": "https://localhost:8080/"} outputId="ca9b491e-f0bb-44f9-8b56-d90c406c502b" chi_square = ((n-1)*s_square)/sigma_square chi_square # + id="nhgKAnpdwYFA" colab={"base_uri": "https://localhost:8080/"} outputId="e9610454-eb34-44c5-cf1e-89198824e902" chi_square_critical = st.chi2.ppf(alpha, degrees_of_freedom) #"1-alpha" as per Bluman's table chi_square_critical # + id="sXzs0xmIwYFB" colab={"base_uri": "https://localhost:8080/"} outputId="04a9e004-2d5a-4bc5-8575-8adab40649d3" if (chi_square > chi_square_critical): print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis") # + [markdown] id="1E4qTb9fwYFB" # ## Section 6 : Chi-Square Test using P-Value # + [markdown] id="fzgqC-onwYFC" # ### Example 6.1 : Car Inspection Times # A researcher knows from past studies that the standard deviation of the time it takes to inspect a car is 16.8 minutes. A random sample of 24 cars is selected and inspected. The standard deviation is 12.5 minutes. At ฮฑ = 0.05, can it be concluded that the standard deviation has changed? Use the P-value method. Assume the variable is normally distributed. # + id="iMCnHAMGwYFD" #H0 : ฯƒ = 16.8, Ha : ฯƒ != 16.8 n = 24 degrees_of_freedom = n-1 s = 12.5 sigma = 16.8 alpha = 0.05 # + id="k8b0MvRKwYFD" colab={"base_uri": "https://localhost:8080/"} outputId="8a761af2-89b7-4df1-e892-8adccba4ae72" chi_square = ((n-1)*(s**2))/sigma**2 chi_square # + id="pVQHh1RTwYFF" colab={"base_uri": "https://localhost:8080/"} outputId="c2cb4096-73d7-4349-d464-1e8661736986" p_val = st.chi2.cdf(chi_square, degrees_of_freedom)*2 p_val # + id="kJyWUAYewYFF" colab={"base_uri": "https://localhost:8080/"} outputId="f51d219f-93a2-4931-bf8a-2aa039256727" if (p_val > alpha): print("Null hypothesis cannot be rejected") else: print("Reject null hypothesis")
Hypothesis_Testing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import timm import pandas as pd import numpy as np import pathlib import os import torch timm.list_models("*xcit*") # + pycharm={"name": "#%%\n"} if os.name == 'nt': temp = pathlib.PosixPath pathlib.PosixPath = pathlib.WindowsPath model = timm.create_model('volo_d1_224', pretrained=True, num_classes=0) model # + pycharm={"name": "#%%\n"} list(model.children())[-2].weight.shape[0] # + pycharm={"name": "#%%\n"} x = torch.rand(1, 3, 224, 224) feature_extractor = model feature_extractor(x).size() # + pycharm={"name": "#%%\n"} model.ex # + pycharm={"name": "#%%\n"} list(model.children())[-1].weight.shape[1] # + pycharm={"name": "#%%\n"} # + pycharm={"name": "#%%\n"} timm.create_model('volo_d1_224', pretrained=True) # + pycharm={"name": "#%%\n"} import pandas as pd df = pd.read_csv('../../data/external/results-imagenet-real.csv') df_224 = df[(df['img_size'] <= 300) & (df['param_count'] < 60)] df_224.sort_values(by='top1', ascending=False)[:10][["model", "top1", "param_count", "img_size"]] # + pycharm={"name": "#%%\n"} df_224.sort_values(by='top5', ascending=False) # + pycharm={"name": "#%%\n"} df_224 = df[(df['img_size'] <= 300) & (df['param_count'] < 30)] df_224.sort_values(by='top1', ascending=False)[["model", "top1", "param_count", "img_size"]]
notebooks/Playground/timm_exploration.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### General advice (delete this cell before submitting for review) # # > * When adding **Products used**, embed the hyperlink to that specific product on the DE Africa Explorer using the `[product_name](product url)` syntax. # > * When writing in Markdown cells, start each sentence on a **new line**. # This makes it easy to see changes through git commits. # > * To faciliate the easy conversion of these notebooks into a docs help page, check the [known issues](https://github.com/GeoscienceAustralia/dea-docs/wiki/Known-issues) for formatting regarding the conversion of notebooks to DE Africa docs using Sphinx. # Things to be aware of: # * Sphinx is highly sensitive to bulleted lists: # * Ensure that there is an empty line between any preceding text and the list # * Only use the `*` bullet (`-` is not recognised) # * Sublists must be indented by 4 spaces # * Two kinds of formatting cannot be used simultaneously: # * Hyperlinked code: \[\`code_format\`](hyperlink) fails # * Bolded code: \*\*\`code_format\`\*\* fails # * Headers must appear in hierarchical order (`#`, `##`, `###`, `####`) and there can only be one title (`#`). # > * Use the [PEP8 standard](https://www.python.org/dev/peps/pep-0008/) for code. To make sure all code in the notebook is consistent, you can use the `jupyterlab_code_formatter` tool: select each code cell, then click `Edit` and then one of the `Apply X Formatter` options (`YAPF` or `Black` are recommended). This will reformat the code in the cell to a consistent style. # > * In the final notebook cell, include a set of relevant **keywords** which are used to build the DE Africa User Guide's [Keyword Index](https://docs.digitalearthafrica.org/en/latest/genindex.html). # * Use the list of approved documentation keywords on the [wiki page](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks/wiki/List-of-Documentation-Keywords). # * Avoid using keywords that link to specific modules in `deafrica_tools`. # * Use all lower-case (unless the tag is an acronym), separate words with spaces. Note that Sentinel satellites are canonically named with hyphens connecting name and number, while Landsat satellites are not: `sentinel-2`, `landsat 8` # * Ensure the keywords cell below is in `Raw` format, rather than `Markdown` or `Code`. # # # Descriptive title that follows notebook filename # # * **Products used:** # [ls8_sr](https://explorer.digitalearth.africa/ls8_sr), # [wofs_ls_summary_annual](https://explorer.digitalearth.africa/wofs_ls_summary_annual), # * **Special requirements:** An _optional_ description of any special requirements # * **Prerequisites:** An _optional_ list of any notebooks that should be run or content that should be understood prior to launching this notebook # # + raw_mimetype="text/restructuredtext" active="" # **Keywords** :index:`data used; landsat 8` # - # ## Background # An *optional* overview of the scientific, economic or environmental management issue or challenge being addressed by Digital Earth Africa. # For `Beginners_Guide` or `Frequently_Used_Code` notebooks, this may include information about why the particular technique or approach is useful or required. # If you need to cite a scientific paper or link to a website, use a persistent DOI link if possible and link in-text (e.g. [Dhu et al. 2017](https://doi.org/10.1080/20964471.2017.1402490)). # ## Description # A _compulsory_ description of the notebook, including a brief overview of how Digital Earth Africa helps to address the problem set out above. # It can be good to include a run-down of the tools/methods that will be demonstrated in the notebook: # # 1. First we do this # 2. Then we do this # 3. Finally we do this # # *** # ## Getting started # # Provide any particular instructions that the user might need, e.g. To run this analysis, run all the cells in the notebook, starting with the "Load packages" cell. # ### Load packages # Import Python packages that are used for the analysis. # # Use standard import commands; some are shown below. # Begin with any `iPython` magic commands, followed by standard Python packages, then any additional functionality you need from the `Tools` package. # + # %matplotlib inline import datacube import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt # - # ### Connect to the datacube # # Connect to the datacube so we can access DE Africa data. # The `app` parameter is a unique name for the analysis which is based on the notebook file name. dc = datacube.Datacube(app='DEA_notebooks_template') # ### Analysis parameters # # An *optional* section to inform the user of any parameters they'll need to configure to run the notebook: # # * `param_name_1`: Simple description (e.g. `example_value`). Advice about appropriate values to choose for this parameter. # * `param_name_2`: Simple description (e.g. `example_value`). Advice about appropriate values to choose for this parameter. # param_name_1 = 'example_value' param_name_2 = 'example_value' # ## Heading 1 # Use headings to break up key steps/stages of the notebook. # # Use markdown text for detailed, descriptive text explaining what the code below does and why it is needed. # # > **Note:** Use this markdown format (sparingly) to draw particular attention to an important point or caveat # Use code comments for low-level documentation of code a = 1 # ### Subheading 1 # Use subheadings to break up steps within a single section. # Use code comments for low-level documentation of code b = 2 # ## Heading 2 # Use markdown text for detailed, descriptive text explaining what the code below does and why it is needed. # Use code comments for low-level documentation of code c = 3 # *** # # ## Additional information # # **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). # Digital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. # # **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). # If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks). # # **Compatible datacube version:** print(datacube.__version__) # **Last Tested:** from datetime import datetime datetime.today().strftime('%Y-%m-%d')
DEAfrica_notebooks_template.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Lesson 3 - Homework - Pandas and Numpy # ### Hi again! :) # # #### For today's homework, you will further explore the dataset recipe.csv. So start with importing the two key libraries: NumPy and pandas and loading the .csv file. Use the first column as index. # #### Drop all the columns that are of Boolean type. We won't need them. # # #### Keep the new dataframe stored in the same variable as the first one. # #### In some of the columns, there are less than 100 values available. Please drop them, too. We will learn how to deal with non-available values next time. # # #### Keep the new dataframe stored in the same variable as the first one. # #### Enough dropping. How big is your DataFrame now? # #### Too big. The columns are fine, but we will restrict ourselves to 50 recipes. Please choose any 50 recipes (hint: maybe the first 50? :) ). # # #### Keep the new dataframe stored in the same variable as the first one. # #### Display only the columns referring to Fiber. # #### And now the columns referring to Fiber for recipes from rows numbered 10 to 30. # #### Cool. Now choose your favourite recipe and display only the respective row in the DataFrame. # #### And now the columns referring to Fiber FOR your favourite recipe. # #### One last thing. What is the difference between accessing the column "vegetarian" in those two ways: # - df["vegetarian"] # - df[["vegetarian"]] # # #### (df is the name of your DataFrame). # # Hint: what are the types of these two? # # ## Please remember that difference. # # Exercises on Numpy # 1. Write a NumPy program to create an array of the integers from 10 to 50 # 2. And print the Even and odd integers from the above array # 3. Write a NumPy program to convert an array to a float type. # # __Expected output__: # # Original array # [1, 2, 3, 4] # # Array converted to a float type: # [ 1. 2. 3. 4.] # 4. Create a 2X2 integer array and print it's values and then print max along the axis 1 of that result. # # 5. Create a 2-d array named ints and perform the following operations # # - Print second row of ints # # - Print all elements of ints that are greater than six # # - Double every element of ints # # - Replace the third column of ints # ## #See you!!1
lesson03/homework/homework.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/sulaimanbehzad/Classifying-Images/blob/main/Image_Classifier.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="iXCGKES9z2uu" # # Classifiers # The purpose of this project is to train two classifiers: # 1. Captions classifier # 2. Image classifier # + id="enfmzwTK6_aE" import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from sklearn.preprocessing import LabelBinarizer, LabelEncoder from sklearn.metrics import confusion_matrix import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from keras import utils from keras.preprocessing import image from keras.models import Model from tensorflow.keras.applications import EfficientNetB2 from tensorflow.keras.applications import ResNet50 from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from keras.models import Sequential from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization from keras import backend as K from keras.utils import np_utils from keras import regularizers # + [markdown] id="quS7tRcgGr7x" # ## Part 2: Image Classifier # + [markdown] id="yfMeZzMowXzN" # setting-up the parameters for image loader # + id="GHaOQDvwwTcR" img_width, img_height = 224, 224 path_train_images = r'/content/drive/MyDrive/dataset/train/images' path_test_images = r'/content/drive/MyDrive/dataset/test/images' path_dataset = r'/content/drive/MyDrive/dataset' nb_train_samples = 532 nb_validation_samples = 380 epochs = 50 batch_size = 32 # + [markdown] id="BHFOqsxG7o9K" # ### Data Acquisition # im_generator was repurposed to apply some mandatory disnormalities in images to make up for the small dataset, but it had a bad imapct on training # + id="T4nuvNJyqkjg" # im_generator = ImageDataGenerator( # rotation_range=30, # zoom_range=0.15, # width_shift_range=0.2, # height_shift_range=0.2, # shear_range=0.15, # horizontal_flip=True, # fill_mode="nearest") im_generator = ImageDataGenerator( # featurewise_center=True, samplewise_center=True, # rescale = 1/255., fill_mode="nearest" ) # + colab={"base_uri": "https://localhost:8080/"} id="16_Horyqqx-c" outputId="603d048b-c216-4411-99f7-de38de26640e" train_df = im_generator.flow_from_directory( path_train_images, # validation_split=0.2, class_mode="categorical", shuffle=False, # seed=123, target_size=(img_height, img_width), batch_size=batch_size, ) # + colab={"base_uri": "https://localhost:8080/"} id="aiwu2rTHxCaf" outputId="08e33bd4-2984-45d1-84a4-ef5cefa82d6e" val_df = im_generator.flow_from_directory( path_test_images, # validation_split=0.2, class_mode="categorical", shuffle=False, # seed=123, target_size=(img_height, img_width), batch_size=batch_size, ) # + colab={"base_uri": "https://localhost:8080/"} id="rnpsFcjnxkCS" outputId="860fc1e3-e8f5-4fbc-992e-09081037d955" tags = train_df.labels print(f'tags are: {tags} \n and length of tags is: {len(tags)}') # + [markdown] id="dE34FxI1w_wn" # If we try to put a data augmentor model before the pretrained model it will affect the performance of pretrained model badly since the pretrained model expects the input data to be raw (unprocessed) # + id="v0mYjMg5BAVT" # data_augmentation = keras.Sequential( # [ # layers.experimental.preprocessing.RandomFlip("horizontal", # input_shape=(img_height, # img_width, # 3)), # layers.experimental.preprocessing.RandomRotation(0.1), # layers.experimental.preprocessing.RandomZoom(0.1), # ] # ) # + [markdown] id="kfFbNubn9CSr" # ### Pretrained model acqusition # For feature extraction purposes we set include_top to false, it's whethere to include the fully connected layer at top_of the network # + id="T021o5FTLifw" colab={"base_uri": "https://localhost:8080/"} outputId="98c64ba6-3ad6-453f-beee-0c8feba4805c" model_resnet = ResNet50(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3)) model_resnet.trainable = False model_resnet.summary() # + colab={"base_uri": "https://localhost:8080/"} id="GpZ9WJCHVDUg" outputId="c126556f-1e13-4796-94e2-7a5b5a8f421a" model_efficient = EfficientNetB2(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3)) model_efficient.trainable = False model_efficient.summary() # + [markdown] id="ymMD897yxkr8" # ### Feature Extraction: # In this stage we use the pretrained model as a feature extractor # * X_train_e is the prediction/features of the training data # * X_test_e is the prediction/features of the test/validation data # + id="cH_0_eSAxzRm" X_train_e = model_efficient.predict(train_df, batch_size=batch_size) # X_train_r = model_resnet.predict(train_df, batch_size=batch_size) # + id="lyTCXNfByfJ9" X_test_e = model_efficient.predict(val_df, batch_size=batch_size) # X_test_r = model_resnet.predict(val_df, batch_size=batch_size) # + id="GtWzjCOOqauj" # X_train.to_csv(r'/content/drive/MyDrive/dataset/train/X_train.csv', index=False) # X_test.to_csv(r'/content/drive/MyDrive/dataset/test/X_test.csv', index=False ) # + id="CEFkHE0FBA01" # X_train = pd.read_csv('/content/drive/MyDrive/dataset/train/X_train.csv') # X_test = pd.read_csv('/content/drive/MyDrive/dataset/test/X_test.csv') # X_test # + id="Ty3lGfibx0IX" # plt.figure(figsize=(15, 10)) # for im, lbl in train_df.take(1): # for i in range(4): # ax = plt.subplot(3, 3, i + 1) # plt.imshow(im[i].numpy().astype("uint8")) # plt.title(tags[lbl[i]]) # plt.axis("off") # + id="oih2A4e9yt9x" # AUTOTUNE = tf.data.AUTOTUNE # train_df = train_df.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE) # validation_df = validation_df.cache().prefetch(buffer_size=AUTOTUNE) # + id="hLm3GFK4y7V7" # normalization_layer = layers.experimental.preprocessing.Rescaling(1./255) # + id="4EAFs0lmzxed" # normalized_df = train_df.map(lambda x, y: (normalization_layer(x), y)) # image_batch, labels_batch = next(iter(normalized_df)) # first_image = image_batch[0] # # Notice the pixels values are now in `[0,1]`. # print(np.min(first_image), np.max(first_image)) # + [markdown] id="ZGh7UMdMzHxd" # here we change the lables to one-hot representation # + id="nYBhLq8S1h7k" y_train = utils.to_categorical(train_df.labels) y_test = utils.to_categorical(val_df.labels) # + colab={"base_uri": "https://localhost:8080/"} id="jPavFd6Ep14o" outputId="2e6defaa-3a3d-4999-fd78-2e2a19af1da7" y_train # + [markdown] id="tZVw0OkXzT8L" # ### The actual model # the following model was optimised on accuracy level to have the number of layers, dropout rate, regularization hyperparameter, optimizer and number of # number units in each layer such as below: # + id="8AZmamEb0wAc" from tensorflow.keras.optimizers import SGD opt = SGD(lr=1e-3, momentum=0.9, decay=1e-3 / 25) reg_hyp = 0 model = Sequential([ layers.Flatten(), BatchNormalization(), layers.Dense(512, activation='selu', kernel_regularizer=regularizers.L2(reg_hyp)), layers.Dropout(0.6), BatchNormalization(), layers.Dense(256, activation='selu', kernel_regularizer=regularizers.L2(reg_hyp)), layers.Dropout(0.5), BatchNormalization(), layers.Dense(128, activation='selu', kernel_regularizer=regularizers.L2(reg_hyp)), layers.Dropout(0.5), BatchNormalization(), layers.Dense(64, activation='selu', kernel_regularizer=regularizers.L2(reg_hyp)), layers.Dropout(0.5), BatchNormalization(), layers.Dense(19, activation='softmax') ]) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # + [markdown] id="H-_eZS-10__D" # we will train the model in two steps # + colab={"base_uri": "https://localhost:8080/"} id="7xZL1Ejb1bt0" outputId="1ba02dc5-2b8a-469e-c486-52ba3ca5acef" history = model.fit( X_train_e, y_train, epochs=25, shuffle=True, validation_data=(X_test_e, y_test), batch_size=128 ) # + colab={"base_uri": "https://localhost:8080/"} id="SqMeZhCR1x3t" outputId="98b46821-73b5-4db1-e986-cfd8c0af9bce" history2 = model.fit(X_train_e, y_train, epochs=50, shuffle=True, validation_data=(X_test_e, y_test), batch_size=128, initial_epoch=history.epoch[-1]) # + [markdown] id="-cnij4kg1IvI" # in the second step the model tends to overfit we can control this by setting the regularization parameter, but it will keep the model at a lower accuracy # to rephrase, the model will not generalise as welll # + id="03UtmK0O1YY-" colab={"base_uri": "https://localhost:8080/"} outputId="05290649-d7d8-4787-9072-f86a2cc4823a" model.summary() # + id="mG3xW1ODS-Gj" colab={"base_uri": "https://localhost:8080/"} outputId="f8749470-8b36-4b1a-b14f-b07bdc7d2bca" score = model.evaluate(X_test_e, y_test, batch_size=batch_size, verbose=1) print(f'Test loss:{score[0]}') print(f'Test accuracy:{score[1]}') # + colab={"base_uri": "https://localhost:8080/", "height": 716} id="kg63Qq-_2iiH" outputId="d9867172-1568-4705-f72c-bf7b216c9ff4" acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(25) plt.figure(figsize=(16, 12)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.show() # + [markdown] id="a4DY36fvjP_v" # We tried the models below: # 1. VGG16 # 2. InceptionV3 # 3. InceptionResnetV2 # 4. ResNet50 # 5. Resnet50v2 # 6. EfficientNetB0 - B5 # # the highest accuracy was obtained from EfficientNetB2 and ResNet50, while the first one is simpler in comparison its performance in this context proved to be better. # # # #
Image_Classifier.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .sos # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: SoS # language: sos # name: sos # --- # + [markdown] kernel="SoS" # # How to use named output in data-flow style workflows # + [markdown] kernel="SoS" # * **Difficulty level**: easy # * **Time need to lean**: 10 minutes or less # * **Key points**: # * Output can be grouped by names, which can be referred to by `[name]` # * Function `named_output(name)` refers to output with `name` in any step # * Return value of `name_output(name)` can also have groups # # + [markdown] kernel="SoS" # ## Limitations of basic dataflow-based workflows # + [markdown] kernel="SoS" # In our tutorial on [How to define and execute basic SoS workflows](doc/user_guide/forward_workflow.html) we introduced basic dataflow-based workflows as follows: # + kernel="SoS" !rm DEG.csv # %run plot [global] excel_file = 'data/DEG.xlsx' csv_file = 'DEG.csv' figure_file = 'output.pdf' [convert] input: excel_file output: csv_file run: expand=True xlsx2csv {_input} > {_output} [plot] input: csv_file output: figure_file R: expand=True data <- read.csv('{_input}') pdf('{_output}') plot(data$log2FoldChange, data$stat) dev.off() # + [markdown] kernel="SoS" # Basically, when the input of step `plot` (`csv_file`) is unavailable, SoS looks in the script for another step that generates this output. If it can be found, it will execute that step to produce the required input before step `plot` is executed. # + [markdown] kernel="SoS" # A limitation of this kind of workflow is that the output of another step has to be determined "easily" either from the `output` statement itself, or with variable definitions from the `global` section. The following workflow would fail because the step of the output is defined as # # ``` # output: _input.with_suffix('csv') # ``` # # which takes the `_input` of the step and replaces its suffix with `.csv`. Because the `_output` depends on `_input`, it cannot be used to generate `data/DEG.csv` directly. # + kernel="SoS" !rm -f data/DEG.csv # %run plot [global] excel_file = 'data/DEG.xlsx' csv_file = 'data/DEG.csv' figure_file = 'output.pdf' [convert] input: excel_file output: _input.with_suffix('.csv') run: expand=True xlsx2csv {_input} > {_output} [plot] input: csv_file output: figure_file R: expand=True data <- read.csv('{_input}') pdf('{_output}') plot(data$log2FoldChange, data$stat) dev.off() # + [markdown] kernel="SoS" # ## Named output # + [markdown] kernel="SoS" # Similar to input statement, output of SoS steps can also be named. In the following example # # * 4 substeps are defined with `i=0`, `1`, `2`, and `3` # * The output of each substep is `f'a_{i}.txt'` and `f'b_{i}.txt'` (`a_0.txt`, `b_0.txt` etc). # * The outputs are grouped to group `a` and `b`. # * The output of the entire step consist of `_output` of substeps, which becomes the `_input` of the next step. This is how we can example the output of step `10`. # + kernel="SoS" # %run [10] input: for_each=dict(i=range(4)) output: a=f'a_{i}.txt', b=f'b_{i}.txt' _output.touch() [20] print(f'{_input} with sources {_input.sources}') print(_input['a']) # + [markdown] kernel="SoS" # As we can see, there are four substeps for step `20`. The `_input` of substeps has two files with names `a` and `b`, and we can refer to the targets with name `a` with `_input['a']`. # + [markdown] kernel="SoS" # ## Function `named_output` <a id="named_output"></a> # + [markdown] kernel="SoS" # <div class="bs-callout bs-callout-primary" role="alert"> # <h4>Function <code>named_output(name, group_by, ...)</code></h4> # <p>Function <code>named_output</code> refers the named output of any SoS step defined in the script. Using <code>named_output</code> in the <code>input</code> statement of a step will create an dependency on the step with the named output, and insert the named output as input of the step.</p> # </div> # + [markdown] kernel="SoS" # The problem we had with complex output can be resolved by function `named_output()`. For example, the aforementioned workflow can be written as # + kernel="SoS" !rm -f data/DEG.csv # %run plot [global] excel_file = 'data/DEG.xlsx' csv_file = 'data/DEG.csv' figure_file = 'output.pdf' [convert] input: excel_file output: csv = _input.with_suffix('.csv') run: expand=True xlsx2csv {_input} > {_output} [plot] input: named_output('csv') output: figure_file R: expand=True data <- read.csv('{_input}') pdf('{_output}') plot(data$log2FoldChange, data$stat) dev.off() # + [markdown] kernel="SoS" # Here `named_output('csv')` refers to any step that produces an output with name `csv`, which is the step `convert` in this workflow. The input of step `plot` is the return value of `named_output('csv')` which is `data/DEG.csv`, although its exact name can only be identified after the conversion step is executed. # + [markdown] kernel="SoS" # <div class="bs-callout bs-callout-warning" role="alert"> # <h4>Uniqueness of names of output</h4> # <p>Although outputs of steps can be identified with arbitrary names and mulitple steps can have the same names for outputs, names refered by function <code>named_output</code> have to be unique.</p> # </div> # + [markdown] kernel="SoS" # <div class="bs-callout bs-callout-warning" role="alert"> # <h4><code>named_output()</code> can only be called from input statements</h4> # <p><code>named_output()</code> is a function provided by SoS to define input of steps and can only be called from input statements.</p> # </div> # + [markdown] kernel="SoS" # ## Groups of output returned by `named_output` * # + [markdown] kernel="SoS" # As we have seem, the output of a step can have multiple groups. In this case the return value of `named_output(name)` consists of the `name` part of all groups. # # In the following example, `named_output('a')` obtains the `a` part of the output of step `A`, which consists of 4 groups. During the execution of the workflow, step `A` is executed to generate input for step `default`, which consists of 4 steps with `_input` equals `a_0.txt`, `a_1.txt` etc. # + kernel="SoS" # %run -v0 [A] input: for_each=dict(i=range(4)) output: a=f'a_{i}.txt', b=f'b_{i}.txt' _output.touch() [default] input: named_output('a') output: _input.with_suffix('.bak') print(f'Generating {_output}') _output.touch() # + [markdown] kernel="SoS" # <div class="bs-callout bs-callout-warning" role="alert"> # <h4>Option <code>group_by</code> of function <code>output_from</code></h4> # <p>Option <code>group_by</code> regroups the groups returned by <code>output_from</code> # </div> # + [markdown] kernel="SoS" # If you would like to remove the groups or re-group the returned files using another method, you can use the `group_by` option of function `output_from`. For example, the `group_by='all'` option in the following example groups all 4 input files into a single group: # + kernel="SoS" # %run -v0 [A] input: for_each=dict(i=range(4)) output: a=f'a_{i}.txt', b=f'b_{i}.txt' _output.touch() [default] input: named_output('a', group_by='all') output: [x.with_suffix('.bak') for x in _input] print(f'Generating {_output}') _output.touch() # + [markdown] kernel="SoS" # ## `named_output()` with skipped substeps # + [markdown] kernel="SoS" # Function `named_output` obtains outputs, actually substeps output from another step. There is, however, a case when a substep is skipped and leaves no output. In this case, the substep output is dicarded. # # For example, when a substep in the step `A` of the following workflow is skipped, the result from `named_output('A')` contains only the output of valid substeps. # + kernel="SoS" # %run -v0 [A] input: for_each=dict(i=range(4)) output: A=f'output_{i}.txt' skip_if(i == 2, 'Skip substep 2') _output.touch() [default] input: named_output('A') print(_input) # + [markdown] kernel="SoS" # However, if you would like to keep consistent number of substeps across steps, you can handle get output from all substeps by using option `remove_empty_groups=False`. # + kernel="SoS" # %run -v0 [A] input: for_each=dict(i=range(4)) output: A=f'output_{i}.txt' skip_if(i == 2, 'Skip substep 2') _output.touch() [default] input: named_output('A', remove_empty_groups=False) print(_input) # + [markdown] kernel="SoS" # ## Further reading # # * [How to include output from another step in a SoS step](output_from.html) # * [How to use Makefile-style rules to generate required files](auxiliary_steps.html) # * [How to execute workflow to generate specific output](target_oriented.html)
src/user_guide/named_output.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Author: <NAME> # # Project 1: Applied Statistics # This is the first project in the AIML course offered by Great Learning. The project is split into 3 parts covering probability # basics, EDA, visualisation and inferential statistics. # <b>Part 1:</b> Contains 6 questions on probabiity which require detailed answers including assumptions, explanations and calculations <br> # <b>Part 2:</b> Contains a dataset from SPORTS domain on which EDA needs to be performed to arrive at a conclusion on performance <br> # <b>Part 3:</b> Contains a dataset from STARTUP ECOSYSTEM from which statistical inferences need to be derived # Let us begin with <b>Part 1</b> # ## Part 1: Question Based # ### Q1: Please refer the table below to answer below questions # <table align="center"> # <th>Planned to purchase Product A</th> # <th>Actually placed and order for Product A - Yes</th> # <th>Actually placed and order for Product A - No</th> # <th>Total</th> # <tr> # <td>Yes</td> # <td>400</td> # <td>100</td> # <td>500</td> # </tr> # <td>No</td> # <td>200</td> # <td>1300</td> # <td>1500</td> # <tr> # <td>Total</td> # <td>600</td> # <td>1400</td> # <td>2000</td> # </tr> # </table> # <b>1.1</b> Refer to the above table and find the joint probability of the people who planned to purchase and actually # placed an order. # This is a simple probability calculation where P(planned to purchase and actually placed order) is the proportion of people who planned to purchase and placed order (400) with respect to total number (2000) print("P(planned to purchase and actually placed order)= %.2f" %(400/2000)) # <b>1.2</b> Refer to the above table and find the joint probability of the people who planned to purchase and actually # placed an order, given that people planned to purchase # This is a conditional probability where # P(planned to purchase and actually placed order given planned to purchase) = P(planned to purchase and actually placed order)/ P(planned to purchase) print("P(planned to purchase and actually placed order given planned to purchase) = P(planned to purchase and actually placed order)/ P(planned to purchase)") print("P(planned to purchase and actually placed order given planned to purchase) = %.2f" %(400/500)) # ### Q2: An electrical manufacturing company conducts quality checks at specified periods on the roducts it manufactures. Historically, the failure rate for the manufactured item is 5%. Suppose a random sample of 10 manufactured items is selected. Answer the following questions # <b>2.1</b> Probability that none of the items are defective? # This is an example of a binomial event where the products can either be defective or not defective. <br> # <blockquote> # p = P(sample is defective) = 5% = 0.05<br> # n = Number of samples = 10 # </blockquote> # # Hence the probability distribution for this can be obtained via the stats.binom.pmf or stats.binom.cdf functions with n=10 and p=0.05, depending on whether we need cumulative or point probability import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns import scipy.stats as stats p = 0.05 # probability that sample is defective n = 10 # number of samples x= np.arange(0,11) prob_dist = stats.binom.pmf(x,n,p) print("Probability that none of the items are defective = %.3f" %(prob_dist[0])) # <b>2.2</b> Probability that exactly one of the items is defective? print("Probability that one of the items is defective = %.3f" %prob_dist[1]) # <b>2.3</b> Probability that two or fewer of the items are defective? # <blockquote>Probability that two or fewer of the items is defective = Probability (0 defective or 1 defective or 2 defectives) </blockquote> # Since, these are mutually exclusive events, # <blockquote>Probability that two or fewer of the items is defective = Probability (0 defective) + Probability (1 defective) + Probability (2 defectives) </blockquote> # print("Probability that two or fewer items are defective = %.3f" %prob_dist[0:3].sum()) # <b>2.4</b> Probability that three or more of the items are defective ? # Applying same additive rule as above: print("Probability that three or more items are defective = %.3f" %prob_dist[3:11].sum()) # ### Q3: A car salesman sells on an average 3 cars per week. # <b>3.1</b> Probability that in a given week he will sell some cars # This experiment, with no restriction on the maximum number of "trials/events" can be described by Poisson Distribution. # <blockquote> lambda = Average sales rate = 3 cars/week </blockquote> # Hence the probability distribution for this can be obtained via the stats.poisson.pmf or stats.poissonm.cdf functions with lambda=3, depending on whether we need cumulative or point probability # avg_rate = 3 # lambda x= np.arange(0,20) prob_dist = stats.poisson.pmf(x,avg_rate) print("Probability that he sells some cars = 1- Probability that he sells no cars = %.3f" %(1-prob_dist[0])) # <b>3.2</b> Probability that in a given week he will sell 2 or more but less than 5 cars. # Applying the addition rule, since selling 2 cars or 3 cars or 4 cars are all mutually exclusive events: print("Probability that he sells 2 or more but less than 5 cars = %.3f" %(prob_dist[2:5].sum())) # <b>3.3</b> Plot the poisson distribution function for cumulative probability of cars sold per-week vs number of cars sold perweek. prob_dist_cum = stats.poisson.cdf(x,avg_rate) #calculate the cumulative probability distribution plt.plot(x, prob_dist_cum) plt.title("Cumulative Probability Disttribution") plt.xlabel("Cars Sold per Week") plt.ylabel("Cumulative Probability") # ### Q4: Accuracy in understanding orders for a speech based bot at a restaurant is important for the Company X which has designed, marketed and launched the product for a contactless delivery due to the COVID-19 pandemic. Recognition accuracy that measures the percentage of orders that are taken correctly is 86.8%. Suppose that you place order with the bot and two friends of yours independently place orders with the same bot. Answer the following questions # <b>4.1</b> What is the probability that all three orders will be recognised correctly? # This experiment is again a binomial distribution with <br> # <blockquote>p = 0.868<br> # n = 3</blockquote # # Hence the probability distribution for this can be obtained via the stats.binom.pmf or stats.binom.cdf functions with n=3 and p=0.868, depending on whether we need cumulative or point probability x=np.arange(0,4) p=0.868 n=3 binom_dist = stats.binom.pmf(x,n,p) print("Probability that all three orders will be recognised correctly = %.3f" %binom_dist[3]) # <b>4.2</b> What is the probability that none of the three orders will be recognised correctly? print("Probability that none of the orders will be recognised correctly = %.3f" %binom_dist[0]) # <b>4.3</b> What is the probability that at least two of the three orders will be recognised correctly? # Appying addition rule here since probability of getting atleast 2 orders right is same as sum of probability of 2 orders right and probability of 3 orders right print("Probability that atleast 2 out of 3 orders will be recognised correctly = %.3f" %(binom_dist[2]+binom_dist[3])) # ### Q5: A group of 300 professionals sat for a competitive exam. The results show the information of marks obtained by them have a mean of 60 and a standard deviation of 12. The pattern of marks follows a normal distribution. Answer the following questions # <b>5.1</b> What is the percentage of students who score more than 80. # As mentioned in the question, this is a normal distribution with <br> # <blockquote> loc = mean = 60<br> # scale = standard deviation = 12</blockquote> # # Hence, the probability distribution can be obtained by using stats.norm.cdf function, as per the value mentioned # loc = 60 scale =12 print ("Percentage of students scored > 80 = %0.2f%%" %((1-stats.norm.cdf(80,loc,scale))*100)) # <b>5.2</b> What is the percentage of students who score less than 50 print ("Percentage of students scored < 50 = %0.2f%%" %(stats.norm.cdf(50,loc,scale)*100)) # <b>5.3</b> What should be the distinction mark if the highest 10% of students are to be awarded distinction? # Highest 10% of students implies we need to find the z10 that will corresponding to P(z>z10)=10%. For this, we can use the inverse distribution function p=0.1 z10 = stats.norm.isf(0.1) print("z10 = %0.3f" %z10) x = z10*scale + loc print("The cut-off for distinction should be = %0.2f%%" %x) # ### Q6: Explain 1 real life industry scenario [other than the ones mentioned above] where you can use the concepts learnt in this module of Applied statistics to get a data driven business solution. # The concept of Bayes Theorem can be very well applied to Spam Filters for e-mail. The filters fundamentally follow Bayes Theorem in detecting if a mail is spam or not basis the words contained in the e-mail. As per Bayes Theorem, the below probabilities will be available apriori basis sample data<br> # <blockquote> # P(Spam) = probability that a given e-mail is spam (based on hisotrical data) <br> # P(Word/Spam) = probabiity that a given word occurs in a spam e-mail <br> # P(Ham) = probability that a given e-mail is not spam (ham ; based on historical data) <br> # P(Word/Ham) = probaility that a given word occurs in ham e-mail</blockquote> # # Hence, # $$ P(Spam/Word) = \frac{P(Word/Spam)*P(Spam)}{P(Word/Spam)*P(Spam)+P(Word/Ham)*P(Ham)}\\ $$ # # The data on the apriori probabilities can also be updated as we process more and more e-mails in the above system. # ## Part 2: Project Based # <b>Domain:</b> Sports # <b>Context:</b> Company X manages the men's top professional basketball division of the American league system. # The dataset contains information on all the teams that have participated in all the past tournaments. It has data # about how many baskets each team scored, conceded, how many times they came within the first 2 positions, # how many tournaments they have qualified, their best position in the past, etc. # <b>Data Description:</b> Basketball.csv - The data set contains information on all the teams so far participated in # all the past tournaments. # **Attribute Information:** # 1. **Team:** Team's name # 2. **Tournament:** Number of played tournaments # 3. **Score:** Team's score so far # 4. **PlayedGames:** Games played by the team so far # 5. **WonGames:** Games won by the team so far # 6. **DrawnGames:** Games drawn by the team so far # 7. **LostGames:** Games lost by the team so far # 8. **BasketScored:** Basket scored by the team so far # 9. **BasketGiven:** Basket scored against the team so far # 10. **TournamentChampion:** How many times the team was a champion of the tournaments so far # 11. **Runner-up:** How many times the team was a runners-up of the tournaments so far # 12. **TeamLaunch:** Year the team was launched on professional basketball # 13. **HighestPositionHeld:** Highest position held by the team amongst all the tournaments played # **Project Objective:** Companyโ€™s management wants to invest on proposal on managing some of the best # teams in the league. The analytics department has been assigned with a task of creating a report on the # performance shown by the teams. Some of the older teams are already in contract with competitors. Hence # Company X wants to understand which teams they can approach which will be a deal win for them. # importing packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.style as style; style.use('fivethirtyeight') # %matplotlib inline import seaborn as sns import scipy.stats as stats from statsmodels.formula.api import ols import statsmodels.api as sm from scipy.stats import chi2 from datetime import datetime, date # Read the data & check the first 5 rows df = pd.read_csv("DS - Part2 - Basketball.csv") df.head(5) # number of entries in the dataset df.shape # check the data types of each attribute, followed by the non-zero entry count df.dtypes # We see that there are total of 61 entries in the dataset and 13 attributes. Of these 13 attributes, there are only 2 attributes that are numeric whie the rest are of type object. This means we will have to check if there are any odd entries in these columns df.info() # All columns have non-null entries throughout. # data summary for all attributes df.describe(include='all').T # check the last 5 entries in the dataset df.tail(5) # creating a deep copy of the dataframe df1 = df.copy(deep=True) # Now we replace all "-" entries with 0. df1.replace('-',np.nan, inplace = True) df1 = df1.fillna(0) df1.info() # convert object dtype attributes to int df1= df1.astype({"Score": np.int64, "PlayedGames": np.int64, "WonGames": np.int64, "DrawnGames": np.int64, "LostGames": np.int64, "BasketScored": np.int64, "BasketGiven": np.int64,"TournamentChampion": np.int64, "Runner-up": np.int64}) df1.info() # Now, we have converted all the numeric columns into integer datatypes. <br> We move to the TeamLaunch attribute. This has multiple typesof anomalous data as mentioned below: # * xxxxtoyy # * xxxx-yy # * xxxx~yy # * xxxx_yy # # We will now remove these using a lambda function and retain only the first year (in a combined year entry) in a separate column called YearLaunch and create a column called Age which contains the age of the team in years # + def comb2single(x): if 'to' in x: return x.split('to')[0] elif '-' in x: return x.split('-')[0] elif '~' in x: return x.split('~')[0] elif '_' in x: return x.split('_')[0] else: return x df1["YearLaunch"] = df1["TeamLaunch"].apply(comb2single) df1 = df1.astype({"YearLaunch": np.int64}) # convert YearLaunch to datatype int today = date.today() df1["Age"] = df1["YearLaunch"].apply(lambda x: today.year-x) # subtract YearLaunch from current year to get team age # - df1.head() # Dropping TeamLaunch and proceeding df1.drop('TeamLaunch',axis=1,inplace=True) df1.info() # Now we have the data ready for analysis purposes! # We introduce 3 new metrices # - **BasketDiff** - Difference between 'BasketScored' & 'BasketGiven' per 'PlayedGames' # - **Win_Percent** - Percentage of 'WonGames' over 'PlayedGames' # - **Podium_Fin** - Percentage of Podium Finishes ('TournamentChampion'+'Runner-up') over 'Tournament' df1['BasketDiff'] = (df1['BasketScored'] - df1['BasketGiven'])/df1['PlayedGames'] df1['Win_Percent'] = df1['WonGames']/df1['PlayedGames']*100 df1['Podium_Fin'] = (df1['TournamentChampion']+df1['Runner-up'])/df1['Tournament']*100 df1['Win_Percent']=df1['Win_Percent'].fillna(value=0) df1.head(5) # ### Exploratory Data Analysis #Dropping unncessary columns df1.drop(['BasketScored','BasketGiven','WonGames','DrawnGames','LostGames','TournamentChampion','Runner-up'],inplace=True,axis=1) df1.describe() # We see that 50% of the teams were launched in the last 70 years. The oldest team was launched in 1929 and there were 10 such teams. # To reach a meaningful recommendation for Company X, we will adopt the below approach: # 1. The company wants to know a list of probable candidate teams where they can invest for good returns. We will target 4-5 teams as a recommendation # 2. We know that some of the older teams already have sponsorships with competitors. Hence, we will focus on more recently established teams # 3. We will then evaluate certain performance metrices such as Conversion ratio Avg, score per game, (Champions/Runner-up) to Tournament played, Baskets Difference, % Games Won, # 4. See which metrices best relate to Success ((Conversion ratio)) # 5. We have to be careful of teams that have played very few games and also the ones that have not achieved any positions plt.figure(figsize=(5,5)) sns.heatmap(df1.corr()) # Plotting the distribution of HighestPositionHeld sns.countplot('HighestPositionHeld',data=df1) plt.legend() # Defining a set to capture Potential Investment Candidates as derived through our analysis candidates =set() # Identifying Top 5 scoring teams df1.sort_values('Score',ascending=False).head() # Add these to candidates candidates.update(df1.sort_values('Score',ascending=False).head()['Team'].unique()) candidates # Similarly checking the lowest ranked teams by Score df1.sort_values('Score',ascending=False).tail() # Next let us identify the teams with maximum BasketDiff # Identifying Top 5 teams by greatest BasketDiff df1.sort_values('BasketDiff',ascending=False).head() # Similarly checking the lowest ranked teams by BasketDiff df1.sort_values('BasketDiff',ascending=False).tail() # This list is essentially the same as the Top 5 scorers and hence no new candidate added to the list. Now, let us look at the Win_Percent and see which teams have won the most amount of matches they have played #Identifying Top 5 teams by greatest Win_Percent df1.sort_values('Win_Percent',ascending=False).head() # Similarly checking the lowest ranked teams by Win_Percent df1.sort_values('Win_Percent',ascending=False).head() # This list too is the same as the Top5 scorers and hence no new candidates are added. Next, let us analyse the Podium_Fin variable #Identifying Top 5 teams by greatest Podium_Fin df1.sort_values('Podium_Fin',ascending=False).head() # Alas! This list too is the same as top 5 scorersand hance no new candidates. # Similarly checking the lowest ranked teams by Podium_Fin df1.sort_values('Podium_Fin',ascending=False).tail() # Next, let us look at the prevailing correlations between the data and see if any parameter correlates to Podium_Fin or TournamentChampion or Highest Position # Creating a temporary dataframe for easier plotting df1_temp=df1[['Team','Tournament','Score','PlayedGames',"BasketDiff", 'Age','Win_Percent','Podium_Fin','HighestPositionHeld']] sns.pairplot(df1_temp) # We note the following from this graph: # - There are very few teams that have finsihed on the podium ever (Podium_Fin) # - Win_Percent is high (>30%) for teams which have held high positions or finished on the podium atleast once # - BasketDiff is >0 for teams that have held high positions or finished on the podium atleast once # # 1. Teams aged older than 20 are the ones that have achieved Highest Positions < 5. They also have the best Win_Percent and Podium_Fin # 2. Teams that have played > 4 tournaments are the ones that have achieved Highest Positions < 5 # 3. As teams play more games (PlayedGames/Tournament) the chances of success (HighestPositionHed/Podium_Fin) also increase, which is understandable as the teams will get better and adapt to the tournament better with exposure # Older teams have been most successful, but some of them already are having sponsorship deals with competitors. Hence, we should focus on other teams, apart from the oldest ones. Also, we see that chancesof success increase with more games. Hence, we should define a cut-off for the games # + #Checking the box plot for Age & PlayedGames fig,ax = plt.subplots(1,2) fig.set_figheight(5) fig.set_figwidth(10) sns.boxplot(df1['Age'],ax=ax[0]) sns.boxplot(df1['Tournament'],ax=ax[1]) # - sns.scatterplot(x=df1['Age'],y=df1['Tournament']) #plotting a distribution of Team Age plt.figure(figsize=(10,5)) df1['Age'].plot.hist(bins=100) #print out the oldest teams df1[df1['Age']==df1['Age'].max()] # Hence, we can set the below cut-offs: # <blockquote>Maximum Age = Q3 = 92.0 <i> from distplot</i><br> # Minimum Age = 20.0 <i> from pairplot</i><br> # Minimum Tournament = Q1 = 4 <i> from pairplot</i> # </blockquote> # # With this we will create a subset of our dataset and proceed with further analysis sns.scatterplot(x=df1['Age'],y=df1['Tournament']) plt.axhline(4,linewidth = 1, color='red') #Tournament cut-off plt.axvline(92,linewidth=1,color='red') #Age upper cut-off plt.axvline(20,linewidth=1,color='red') #Age lower cut-off # Creating a subset of our dataset #df2= df1[(df1['YearLaunch'] >1929)& (df1['YearLaunch']<1981) ] df2 = df1[(df1['Age']<92) & (df1['Age']>20) & (df1['PlayedGames']> 114.0)] df2.head() # Let us go back to our candidates list and see if they pass the criteria set above # Check if candidates identified earlier meet the criteria df2[df2['Team'].isin(candidates)] # Only Team 4 meets the criteria and we can retain it and remove the rest candidates={'Team 4'} # Identifying top scoring teams & updating candidates df2.sort_values(by='Score',ascending=False).head() candidates.update(df2.sort_values(by='Score',ascending=False).head()['Team']) # + #Identifying highest Win_Percent, BasketDiff & Podium_Fin teams & updating candidates # - df2.sort_values(by='Win_Percent',ascending=False).head() candidates.update(df2.sort_values(by='Win_Percent',ascending=False).head()['Team']) df2.sort_values(by='BasketDiff',ascending=False).head() candidates.update(df2.sort_values(by='BasketDiff',ascending=False).head()['Team']) df2.sort_values(by='Podium_Fin',ascending=False).head() candidates.update(df2.sort_values(by='Podium_Fin',ascending=False).head()['Team']) # Who are the candidaes at the moment? candidates # Now, let's check the highest position held by these teams df2.groupby(by='HighestPositionHeld').apply(display) # Let us look at the date once again for our candidate teams df2_temp=df2[df2['Team'].isin(candidates)] df2_temp We know that higher PlayedGames leads to greater Win_Percent # ### Observations on the datapoints collected to perform a better data analysis # **Quality**: # - We had to discard 216 entries due to unavailable data, resulting in a reduced usable data set. # - Pre-processed data will help save time for analysis (such as capturing Event location, Year, and Funds in separate columns and in the right format # - There are 6 event entries still missing which cannot be filled because the year or type of events are not deductible # - Hence, complete data sets would be beneficial to perform statistical analyses # **Quantity**: # - The overall usable data is very low. Hypothesis testing is effective with higher sample sizes. When we apply filtered cuts on the data, the sample size tends to go close to the 30 cut-off, thereby affecting our normality assumptions. Hence, we shoud try to collect more data amongst each cut that we want to analyse that is representative of the population # - In fact, if we want to test our hypothesis on individual Winner classes, it won't be possible since a few have < 30 samples # **Variety**: # - Data from a variety of sources such as blog aritcles, press releases, etc could be tracked to update our database # - Specifically data on P&L statements, Social Media activity/posts from the company, Press Releases and its contents could provide added information on the company's health and funding # **Velocity**: # - The data could be updated every 3 months to ensure the 'OperationsState' and 'Funding' attributes are mapped accurately # **Veracity**: # - The funding values are skewed and abnormal to another 60 outliers which could not be used for analysis. Hence, we should double-check the funding values to ensure the data is truthful and without error # **Value:** # - If we are able to implement the above successfully, we can then add value by being able to predict if a company was about to Close down. # - Basis their P&L statements and press releases we could also predict their performance in upcoming events # ## Part 3: Project Based # <b>Domain:</b> Startup Ecosystem <br> # # <b>Context:</b> Company X is a EU online publisher focusing on the startups industry. The company specifically reports on the business related to # technology news, analysis of emerging trends and profiling of new tech businesses and products. Their event i.e. Startup Battlefield is the # worldโ€™s pre-eminent startup competition. Startup Battlefield features 15-30 top early stage startups pitching top judges in front of a vast live # audience, present in person and online. # # <b>Data Description:</b> CompanyX_EU.csv - Each row in the dataset is a Start-up company and the columns describe the company. # # **Attribute Information:** # 1. **Startup:** Name of the company # 2. **Product:** Actual product # 3. **Funding:** Funds raised by the company in USD # 4. **Event:** The event the company participated in # 5. **Result:** Described by Contestant, Finalist, Audience choice, Winner or Runner up # 6. **OperatingState:** Current status of the company, Operating ,Closed, Acquired or IPO # # **Project Objective:** Analyse the data of the various companies from the given dataset and perform the tasks that are specified in the # below steps. Draw insights from the various attributes that are present in the dataset, plot distributions, state hypotheses and draw # conclusions from the dataset. # ### Data Warehouse # read the csv file and check the top entries startup = pd.read_csv("DS - Part3 - CompanyX_EU.csv") # ### Data Exploration startup.head(5) # check the number of entries in dataset startup.shape # Data type of each attribute startup.dtypes # All the attributs are of object datatypes. We will need to convert the Funding attribute to numeric value # Checking for missing values startup.isna().sum() # There are 6 entries missing under Product attribute and 214 entries missing under Funding # ### Data Preprocessing & Visualization # Dropping the rows which have no data startup1 = startup.dropna().copy(deep=True) startup1.shape # The entries in the Funding attribute are of 3 types - a) in \\$M b) in \\$K c) in \\$B. We need to convert these to a standard scale in \\$M with only numeric value stored in the column startup1['Funds_in_million'] = startup1['Funding'].apply(lambda x: float(x[1:-1])/1000 if x[-1] == 'K' else (float(x[1:-1])*1000 if x[-1] == 'B' else float(x[1:-1]))) startup1.head(5) # + # Boxplot for Funds in Mn #sns.set_theme(style ="whitegrid") #plt.figure(figsize=(12,6)) #sns.boxplot(x=startup1['Funds_in_million'],palette="Oranges") plot = plt.boxplot(startup1.Funds_in_million) plt.title('Boxplot of the funds') plt.ylabel("Funds raised (in Million)") plt.show() # - # The Lower Fence here is \\$0.005M. We can also obtain it through the below: lower_fence = plot['caps'][0].get_data()[1][1] # we can use the values from the box plot itself to get the lower fence lower_fence upper_fence = plot['caps'][1].get_data()[1][1] # we can use the values from the box plot itself to get the upper fence upper_fence # Finding the number of outliers beyond the upper fence print(f'Number of outliers = {len(startup1[startup1.Funds_in_million > upper_fence])}') # Dropping the entries where Funds_in_million is higher than upper_fence startup1.drop(startup1[startup1['Funds_in_million']>upper_fence].index, inplace=True) plot = plt.boxplot(startup1['Funds_in_million']) plt.title('Boxplot of funds without the original outliers') plt.ylabel("Funds raised (in Million)") plt.show() # Checking the frequency of OperatingState features startup1['OperatingState'].value_counts() # Plotting a distribution of Funds_in_million sns.distplot(startup1['Funds_in_million'],bins=30,kde=True) plt.title('Distribution of Funds_in_milion') plt.xlabel('Funds_in_million') plt.ylabel('Frequency') # ### Statistical Analysis startup1['Funds_in_million'].describe() # Although the range of values for Funds_in_million are from \\$0.005Mn to \\$22.0Mn, 75% of the startups have funding < \\$5.0Mn. The data remains skewed despite removing outliers # + fig,ax = plt.subplots(1,2) fig.set_figheight(10) fig.set_figwidth(20) sns.distplot(x=startup1[startup1['OperatingState']=='Operating']['Funds_in_million'],ax=ax[0]) sns.distplot(x=startup1[startup1['OperatingState']=='Closed']['Funds_in_million'],ax=ax[1]) ax[0].set_title("Funding for companies Operating") ax[1].set_title("Funding for companies Closed") plt.show() # - # The distributions look very similar on the plot. However, to test the statistical significance, we will do a significance test. We can perform z or t test here. Also, though the distributions are not normal, since our sample size > 30 we can perform the z-test or t-test. # <b>Ho = </b>Null Hypothesis = There is no difference between the two means <br> # <b>Ha = </b>Alternate Hypothesis = There is significant difference between the two means # Now, let us perform the z-test on this sample at 0.05 significance level # + from statsmodels.stats.weightstats import ztest alpha = 0.05 # defining the significance level operating = startup1[startup1['OperatingState']=='Operating']['Funds_in_million'] closed = startup1[startup1['OperatingState']=='Closed']['Funds_in_million'] z_stat, p_val = ztest(operating, closed) if p_val > alpha: print("Since p_val = %.3f is greater than the significance level (0.05), the difference between the means is not significant \nand we fail to reject Ho" %p_val) else: print("Since p_val = %.3f is less than the significance level (0.05), the difference between the means is significant \nand we reject reject Ho" %p_val) # - #make a copy of the dataframe startup2 = startup.copy(deep=True) startup2.head() #Check the frequency distribution of the Result variable startup2.Result.value_counts() # There are total 488 firms which were Contestants whie the rest were either Finalists, Audience Choice winners or podium finishers (Winner/Runner up) # + # Finding proportion of winners and contestants that are in 'Operating' state n_winners = startup2['Result'].value_counts()[1:].sum() # total number of winners n_contestants = startup2['Result'].value_counts()[0] # total number of contestants #startup2.value_counts(["Result", "OperatingState"]) n_w_o = startup2['OperatingState'][startup2['Result']!='Contestant'].value_counts()[0] # total number of winners that are operating n_c_o = startup2['OperatingState'][startup2['Result']=='Contestant'].value_counts()[0] # total number of contestants that are operating print ("Proportion of Winners that are Operating is %.3f" %(n_w_o/n_winners)) print ("Proporation of Contestants that are Operating is %.3f" %(n_c_o/n_contestants)) # - # We see that the proportions are different but to determine if they are statistically significantly different, we will do a test of proportions via the z-test. Again, we can perform this test as the sample size in each option is > 30 # <b>Ho =</b> Null Hypothesis = The proportion of companies that are operating is the same in both winners and contestants <br> # <b>Ha =</b> Alternate Hypothesis = The proportion of companies that are operating are statisticaly siginificantly different between winners and contestants # Now, let us perform the z-test on this sample at 0.05 significance level # + from statsmodels.stats.proportion import proportions_ztest z_stat, p_val = proportions_ztest([n_w_o,n_c_o],[n_winners,n_contestants]) if p_val > alpha: print("Since p_val = %.3f is greater than the significance level (0.05), the difference between the proportions is not significant \nand we fail to reject Ho" %p_val) else: print("Since p_val = %.3f is less than the significance level (0.05), the difference between the proportions is significant \nand we reject reject Ho" %p_val) # - # Checking Distribution of Event variable startup1['Event'].value_counts() # Picking only the entries with Disrupt keyword in Event and conducted from 2013 onwards events = startup1[startup1['Event'].apply( lambda x: 'Disrupt' in x and int(x[-4:]) > 2012)]['Event'] year = events.apply(lambda x: int(x[-4:])) NY_eve = startup1.loc[events[events.apply(lambda x: 'NY' in x)].index, 'Funds_in_million'] SF_eve = startup1.loc[events[events.apply(lambda x: 'SF' in x)].index, 'Funds_in_million'] EU_eve = startup1.loc[events[events.apply(lambda x: 'EU' in x or 'London' in x)].index, 'Funds_in_million'] #Assuming London is in EU since the events listed are from a period where UK was still in EU (last year in data is 2016) plt.figure(figsize =(15,6)) sns.distplot(NY_eve, color ='purple',label ='NY') sns.distplot(SF_eve, color ='orange',label ='SF') sns.distplot(EU_eve, color ='green',label ='EU') plt.legend() plt.show() # The distributions look quite similar. The mode occurs at pretty much the same spot for all 3 locations. The spread for NY is more than that of SF and EU print("NY events: %i SF events: %i EU events: %i" %(len(NY_eve),len(SF_eve),len(EU_eve))) # We see that there are > 30 samples in each set and hence we can meaningfully perform any statistical tests assuming normal distribution. # # **Ho =** Null Hypothesis = Mean of funds raised by companies is same across the 3 locations <br> # **Ha =** Aternate Hypothesis = Mean of funds raised by companies are different across the 3 locations (atleast one mean is different) # Now, let us perform a One-way ANOVA on this data at 0.05 significance level # + from scipy.stats import f_oneway F_Stat, p_val = f_oneway(NY_eve, SF_eve, EU_eve) if p_val > alpha: print("Since p_val = %.3f is greater than the significance level (0.05), the difference between the means is not significant \nand we fail to reject Ho" %p_val) else: print("Since p_val = %.3f is less than the significance level (0.05), the difference between the means is significant \nand we reject reject Ho" %p_val) # - # The distribution of funds raised by the companies across the three regions is the same. We found no evidence to say companies participating in certain regions have funds either significantly on the higher side or on the lower side. # ### Observations on the datapoints collected to perform a better data analysis # **Quality**: # - We had to discard 216 entries due to unavailable data, resulting in a reduced usable data set. # - Pre-processed data will help save time for analysis (such as capturing Event location, Year, and Funds in separate columns and in the right format # - There are 6 event entries still missing which cannot be filled because the year or type of events are not deductible # - Hence, complete data sets would be beneficial to perform statistical analyses # **Quantity**: # - The overall usable data is very low. Hypothesis testing is effective with higher sample sizes. When we apply filtered cuts on the data, the sample size tends to go close to the 30 cut-off, thereby affecting our normality assumptions. Hence, we shoud try to collect more data amongst each cut that we want to analyse that is representative of the population # - In fact, if we want to test our hypothesis on individual Winner classes, it won't be possible since a few have < 30 samples # **Variety**: # - Data from a variety of sources such as blog aritcles, press releases, etc could be tracked to update our database # - Specifically data on P&L statements, Social Media activity/posts from the company, Press Releases and its contents could provide added information on the company's health and funding # **Velocity**: # - The data could be updated every 3 months to ensure the 'OperationsState' and 'Funding' attributes are mapped accurately # **Veracity**: # - The funding values are skewed and abnormal to another 60 outliers which could not be used for analysis. Hence, we should double-check the funding values to ensure the data is truthful and without error # **Value:** # - If we are able to implement the above successfully, we can then add value by being able to predict if a company was about to Close down. # - Basis their P&L statements and press releases we could also predict their performance in upcoming events
01. Applied Statistics/.ipynb_checkpoints/Applied Statistics_Chandrasekaran_v1-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Introduction to the Interstellar Medium # ### <NAME> # ### Figure 11.4: zoom in on CO and Halpha images of a spiral arm in M51 # #### HST Halpha data from https://archive.stsci.edu/prepds/m51/ # #### IRAM CO 2-1 data from https://www2.mpia-hd.mpg.de/PAWS import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from astropy.nddata import Cutout2D from astropy.wcs import WCS from astropy import units as u from astropy.visualization import PercentileInterval from astropy.visualization import ImageNormalize from astropy.visualization import LinearStretch, SqrtStretch, LogStretch, AsinhStretch # %matplotlib inline # + # center chosen based on playing around with ds9 # 13:29:55.059 +47:10:56.470 # convert to decimal using astropy # from astropy import units as u # from astropy.coordinates import SkyCoord # c = SkyCoord('13:29:55.059','+47:10:56.470', unit=(u.hourangle, u.deg)) xcen, ycen = 202.4794125, 47.18435278 xbox, ybox = 0.04, 0.014 world = np.array([[xcen+xbox/2, ycen-ybox/2], [xcen-xbox/2, ycen+ybox/2]]) fitsfile1 = 'NGC5194_Halpha.fits' hdu1 = fits.open(fitsfile1, ignore_missing_end=True) wcs1 = WCS(hdu1[0].header) wcs1.sip = None im1 = hdu1[0].data hdu1.close() pix = np.rint(wcs1.wcs_world2pix(world, 1)).astype(int) position = (0.5*(pix[0,0]+pix[1,0]), 0.5*(pix[0,1]+pix[1,1])) size = (pix[1,1]-pix[0,1], pix[1,0]-pix[0,0]) crop1 = Cutout2D(im1, position=position, size=size, wcs=wcs1, mode='partial') norm1 = ImageNormalize(crop1.data, stretch=AsinhStretch(), interval=PercentileInterval(99)) fitsfile2 = 'NGC5194_IRAM_CO21_mom0.fits' hdu2 = fits.open(fitsfile2, ignore_missing_end=True) wcs2 = WCS(hdu2[0].header) im2 = hdu2[0].data hdu2.close() pix = np.rint(wcs2.wcs_world2pix(world, 1)).astype(int) position = (0.5*(pix[0,0]+pix[1,0]), 0.5*(pix[0,1]+pix[1,1])) size = (pix[1,1]-pix[0,1], pix[1,0]-pix[0,0]) crop2 = Cutout2D(im2, position=position, size=size, wcs=wcs2, mode='partial') norm2 = ImageNormalize(crop2.data, stretch=LinearStretch(), interval=PercentileInterval(99)) levs2 = [50, 100, 150, 200, 250, 300, 350, 400] fig = plt.figure(figsize=(8,4.4)) ax1 = fig.add_subplot(111, projection=crop1.wcs) ax1.imshow(crop1.data, cmap='gray_r', origin='lower', norm=norm1) ax1.contour(crop2.data, levels=levs2, colors='black', linewidths=1, transform=ax1.get_transform(crop2.wcs)) # plot a log spiral and rotation # this is purely an eyeball fit for illustrative purposes only pix0 = np.array([[300,-100]]) theta = np.linspace(1.08*np.pi,1.71*np.pi,100) r0 = 35 # two-armed logarithmic spiral # x ~ sin(theta) for trailing (cos for leading) b = 0.37 r = r0*np.exp(b*theta) _x = pix0[0,0] + r*np.sin(theta) _y = pix0[0,1] + r*np.cos(theta) # rotate phi = np.pi/3 x = _x*np.cos(phi) - _y*np.sin(phi) y = _x*np.sin(phi) + _y*np.cos(phi) ax1.plot(x,y, 'k-', lw=6, alpha=0.3, transform=ax1.get_transform(crop2.wcs)) # draw arrows for rotation # galaxy center 13 29 52.698 +47 11 42.93 x0, y0 = 202.469575, 47.19525833 pix0 = crop2.wcs.wcs_world2pix(np.array([[x0,y0]]),1) r0 = [130, 160, 190] theta0 = [1.5, 1.4, 1.3] for i in range(len(r0)): theta = np.linspace(1.13*np.pi,theta0[i]*np.pi,50) x = pix0[0,0] + r0[i]*np.cos(theta) y = pix0[0,1] + r0[i]*np.sin(theta) dx = x[-1] - x[-2] dy = y[-1] - y[-2] ax1.plot(x,y, 'k-', lw=4, alpha=0.9, transform=ax1.get_transform(crop2.wcs)) ax1.arrow(x[-2],y[-2], dx, dy, width=2, color='black', alpha=0.9, transform=ax1.get_transform(crop2.wcs)) # add a scale bar # 1 kpc at 8 Mpc = 0.0072 deg = 0.0105*cos(dec) along RA axis x0, y0 = 202.498, 47.1786 xbar = 0.0105/5 pix = crop2.wcs.wcs_world2pix(np.array([[x0,y0],[x0-xbar,y0+0.1*xbar],[x0-2*xbar,y0]]),1) dy = 2 ax1.plot([pix[0,0],pix[2,0]], [pix[0,1],pix[0,1]], 'k-', lw=3, transform=ax1.get_transform(crop2.wcs)) ax1.plot([pix[0,0],pix[0,0]], [pix[0,1]-dy,pix[0,1]+dy], 'k-', lw=3, transform=ax1.get_transform(crop2.wcs)) ax1.plot([pix[2,0],pix[2,0]], [pix[0,1]-dy,pix[0,1]+dy], 'k-', lw=3, transform=ax1.get_transform(crop2.wcs)) ax1.text(pix[1,0], pix[1,1], '200 pc', color='black', fontsize=12, fontweight='bold', ha='center', transform=ax1.get_transform(crop2.wcs)) for i in (0,1): ax1.coords[i].set_ticks_visible(False) ax1.coords[i].set_ticklabel_visible(False) ax1.coords[i].set_ticks_visible(False) ax1.coords[i].set_ticklabel_visible(False) ax1.coords[i].set_axislabel('') ax1.coords[i].set_axislabel('') plt.tight_layout() plt.savefig('M51_spiral_arm.pdf') # -
extragalactic/M51_spiral_arm.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- # + deletable=true editable=true # import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model import pandas as pd # + deletable=true editable=true def load_data(filename): cols=["N", "Time_in_us"] return pd.read_csv(filename, names=cols) df = load_data('dev0_h2d_stepsize4.csv') # df = load_data('dev1_h2d_stepsize4.csv') X = df["N"] y = df["Time_in_us"] X = np.array(X) y = np.array(y) X = X.reshape(-1,1) y = y.reshape(-1,1) # + deletable=true editable=true lr_model = linear_model.LinearRegression() lr_model.fit(X, y) # + deletable=true editable=true print lr_model.coef_ print lr_model.intercept_ # + deletable=true editable=true print "Mean squared error: %.6f" % np.mean((lr_model.predict(X) - y) ** 2) print('Variance score: %.6f' % lr_model.score(X, y)) # + [markdown] deletable=true editable=true # ### testing # + deletable=true editable=true lr_model.predict(500) # + deletable=true editable=true lr_model.predict(1000) # + deletable=true editable=true lr_model.predict(500000) # + deletable=true editable=true # 1m lr_model.predict(1000000) # + deletable=true editable=true # 10m lr_model.predict(10000000) # + deletable=true editable=true # 100m lr_model.predict(100000000) # + [markdown] deletable=true editable=true # ### contention # + deletable=true editable=true lr_model.predict(409600) # + deletable=true editable=true lr_model.predict(819200) # + [markdown] deletable=true editable=true # ### permutation # + deletable=true editable=true np.random.seed(42) sample = np.random.choice(df.index, size= int(len(df) * 0.9), replace=False) data, test_data = df.ix[sample], df.drop(sample) # + deletable=true editable=true X_train, y_train = data["N"], data["Time_in_us"] X_test, y_test = test_data["N"], test_data["Time_in_us"] X_train = X_train.reshape(-1,1) y_train = y_train.reshape(-1,1) X_test = X_train.reshape(-1,1) y_test = y_train.reshape(-1,1) lr_model.fit(X_train, y_train) print lr_model.coef_ print lr_model.intercept_ # + deletable=true editable=true print "Mean squared error: %.6f" % np.mean((lr_model.predict(X_test) - y_test) ** 2) print('Variance score: %.6f' % lr_model.score(X_test, y_test))
logGP_lr_ridge/linear_reg.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import matplotlib.pyplot as plt import matplotlib.image as mpimg from PIL import Image img = Image.new('RGB', (1278, 1024), color = 'black') imgplot = plt.imshow(img) x = 500 y = 600 r1 = 100 r2 = 200 circ = Circle((x,y),r2) ax.add_patch(circ) plt.show() # -
Python/Q59010.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/"} id="4ZXi5hsP47Nn" outputId="8a79e95d-c540-4afb-f1f5-7cc07f6a866d" # !pip install wandb # + id="jLcMklRj4-WE" import wandb # from wandb.keras import callback # + colab={"base_uri": "https://localhost:8080/", "height": 634} id="fHEw1vdh5PG_" outputId="36dc749c-4a7d-436e-d131-8830cad47869" wandb.login() wandb.init('RNN model') # + colab={"base_uri": "https://localhost:8080/"} id="75rYRQcpef41" outputId="57f7be8d-aa58-4d15-eddc-828aecfb0e3f" import pandas as pd import numpy as np import pandas as pd import numpy as np #for text pre-processing import re, string import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import SnowballStemmer from nltk.corpus import wordnet from nltk.stem import WordNetLemmatizer nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('wordnet') #for model-building from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report, f1_score, accuracy_score, confusion_matrix from sklearn.metrics import roc_curve, auc, roc_auc_score # bag of words from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer #for word embedding import gensim from gensim.models import Word2Vec from nltk.corpus import stopwords nltk.download('stopwords') from nltk.util import ngrams from spacy.lang.en import English nlp = English() import spacy from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() # + colab={"base_uri": "https://localhost:8080/", "height": 81} id="JzLBnsW7exsg" outputId="bb8cce19-8649-4ed8-899a-919655af2afe" df = pd.read_csv('/content/MentalHealth_orig (1).csv') df.head(1) # + id="D_kKSDUzfFaK" df.drop(['Unnamed: 0','tweet','location', 'hour'],axis=1,inplace=True) # + id="PZ6sRmTbfb4v" #removing url links def remove_URL(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'',text) df['clean_tweet']=df['clean_tweet'].apply(lambda x : remove_URL(x)) # + colab={"base_uri": "https://localhost:8080/", "height": 81} id="qXDUqLRsf6na" outputId="ab40c456-641b-45d8-c929-b570053d2d8f" df.head(1) # + id="lagDcD80f-Ee" df.to_csv('clean.csv') # + id="AXoZZDoggZrp" # !pip install keras # !pip install tensorflow # + id="SRwxkxD7glvo" import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import Sequential from tensorflow.keras.preprocessing import sequence from __future__ import absolute_import,division,print_function,unicode_literals import nltk from nltk.corpus import stopwords from numpy import array from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential #from tensorflow.keras.layers.core import Activation, Dropout, Dense from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import GlobalMaxPooling1D from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.text import Tokenizer # + id="NyItkvobgtmr" from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import Embedding from tensorflow.keras.preprocessing import sequence import tensorflow_hub as hub # + colab={"base_uri": "https://localhost:8080/"} id="t6YFMxzogv9P" outputId="d85d0b12-739e-4392-c204-62d2a7183df5" #Split between the test and train data X_train,X_test = train_test_split(df, test_size = 0.2, random_state = 1000) X_train.shape,X_test.shape # + colab={"base_uri": "https://localhost:8080/"} id="AC4K6bY_g1l2" outputId="a9bbee05-74f2-490a-f812-33c16c31a3b2" #Dealing with class imbalance using weights from sklearn.utils import class_weight class_weights = list(class_weight.compute_class_weight('balanced', np.unique(df['disorder']),df['disorder'])) class_weights # + colab={"base_uri": "https://localhost:8080/", "height": 81} id="MpzPcZ6ulFUr" outputId="a40e98f1-9c75-4108-dfe2-41e097dedc7b" clean = pd.read_csv('/content/clean.csv') clean.head(1) # + id="tmFhf9hVlUYW" from sklearn.feature_extraction.text import CountVectorizer # + colab={"base_uri": "https://localhost:8080/", "height": 147} id="gWqqXv9-lfQj" outputId="4bb7b6de-013a-41ce-91df-c685960f8964" cv = CountVectorizer(stop_words='english') rt = cv.fit_transform(clean['clean_tweet']) clean.drop('clean_tweet',axis=1,inplace=True) rt = pd.DataFrame(rt.toarray()) df = pd.concat([clean,rt],axis=1) df.head(1) # + colab={"base_uri": "https://localhost:8080/"} id="1ahN1de_nntT" outputId="4c8709e3-28fd-4258-8b22-4be3186455e7" df.columns # + colab={"base_uri": "https://localhost:8080/", "height": 130} id="azo-x5LRnTwK" outputId="d8bf787a-07e0-4e7a-a86f-b147ccf27742" df.drop("Unnamed: 0",axis=1,inplace=True) df.head(1) # + id="j5NNyDLDoA7Q" X = df.drop('disorder',axis=1) y = df['disorder'] # + id="oP0Ymj6zoGMD" X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=101) X_eval, X_test, y_eval, y_test = train_test_split(X_val, y_val, test_size=0.5, random_state=101) # + id="mRB2FuqYMCgg" # + id="Z-DXq4PIhNdC" #Turn the weights into a dictionary weights={} for index, weight in enumerate(class_weights): weights[index]=weight # + id="T0JJbVMchPVy" #Set the data as a tensor # + id="9Ha8uXJ6it12" #Create an embedding layer using a pretrained model embedding='https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1' hub_layer=hub.KerasLayer(embedding,output_shape=[128],input_shape=[], dtype=tf.string,trainable=True) # + id="6FS-FRmgi0zl" #Build a keras sequential model input_dim = len(df.columns) - 1 model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(4, input_dim = input_dim , activation = 'relu')) model.add(tf.keras.layers.Dense(4, activation = 'relu')) model.add(tf.keras.layers.Dense(4, activation = 'relu')) model.add(tf.keras.layers.Dense(4, activation = 'relu')) model.add(tf.keras.layers.Dense(8, activation = 'softmax')) # + id="OJv_76qQjAcI" colab={"base_uri": "https://localhost:8080/", "height": 623, "referenced_widgets": ["8aa8fedb64e441a5a189d92a9a78fb67", "ffdac14d4d9e4f1498149603c43adfec", "daa560b343fd47c9b10e19da95e62219", "<KEY>", "<KEY>", "e3fc919b96854bd5bce7a1005f0e1c45", "51f3f955fe414565a3a39e083ab98d14", "<KEY>"]} outputId="c53cbae3-d621-4c78-f72b-d66498b53e2f" # Initialize wandb with your project name run = wandb.init(project='RNN_model_Twitter_mentalHealth', config={ # and include hyperparameters and metadata "learning_rate": 0.005, "epochs": 10, "batch_size": 16, "loss_function": "sparse_categorical_crossentropy", "architecture": "&NN", "dataset": "TweetClassification" }) config = wandb.config # We'll use this to configure our experiment # Initialize model like you usually do. tf.keras.backend.clear_session() model.summary() # Compile model like you usually do. # Notice that we use config, so our metadata matches what gets executed optimizer = tf.keras.optimizers.Adam(config.learning_rate) model.compile(optimizer, config.loss_function, metrics=['accuracy']) # + colab={"base_uri": "https://localhost:8080/"} id="MlRyHe-VjIK7" outputId="04e1e0f5-418c-4796-d47f-41b91986fad1" #Model training from wandb.keras import WandbCallback history=model.fit(X_train, y_train, validation_data = (X_val, y_val), epochs = 10,batch_size=16, callbacks=[WandbCallback()]) # + colab={"base_uri": "https://localhost:8080/"} id="nYWOtk7VkuyP" outputId="ca2348b9-908f-420d-9da1-d1e61813282c" X_train.shape # + id="ARUeM9vMxIS5" import matplotlib.pyplot as plt # + colab={"base_uri": "https://localhost:8080/", "height": 655} id="4dE145LGvbbG" outputId="7203a663-6dbc-4719-e830-38ab7e292707" #plot of model perfomance history_dict = history.history print(history_dict.keys()) acc = history_dict['accuracy'] val_acc = history_dict['val_accuracy'] loss = history_dict['loss'] val_loss = history_dict['val_loss'] epochs = range(1, len(acc) + 1) fig = plt.figure(figsize=(10, 10)) fig.tight_layout() plt.subplot(2, 1, 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'r', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') # plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.subplot(2, 1, 2) plt.plot(epochs, acc, 'r', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend(loc='lower right') # + id="jkK6hrtz0beT" #Build a keras sequential model input_dim = len(df.columns) - 1 model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(8, input_dim = input_dim , activation = 'relu')) model.add(tf.keras.layers.Dense(8, activation = 'relu')) model.add(tf.keras.layers.Dense(8, activation = 'relu')) model.add(tf.keras.layers.Dense(8, activation = 'relu')) model.add(tf.keras.layers.Dense(8, activation = 'softmax')) # + id="gr0CnI6a7hhQ" # We compile using adam optimizer model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) # + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["86bcd53dbe6f47658bb0d1110ca06d83", "fe71b041cdc14baab9d4fd75818450a2", "6585291c3aa040c79bcc63961a4d0745", "9b9973bad56349d4b119974806cfdf0a", "f8ea9c71e0f94deb8740367cf43bfddc", "a1cf1e038dd84a5383a9ddfa3f4a61fd", "1eab0d5b7cda4a50bb8e5d27880a6711", "cac44ea7962d4c56a2c3d1891c76072a"]} id="ukGkMP4d7oYp" outputId="d55aa709-f4ed-429c-ead2-357f0c42f690" #Model training history=model.fit(X_train,y_train, validation_data = (X_val, y_val), epochs = 10,batch_size=5, callbacks=[WandbCallback()]) run.finish() # + id="lyTqXmuu8BPu" y_pred =model.predict(X_test) # + id="Nog-F0pb8xhh" from sklearn.model_selection import cross_val_score from sklearn.metrics import r2_score # + colab={"base_uri": "https://localhost:8080/", "height": 165} id="1UdOkUbJKK3S" outputId="d5953382-c2ad-4dba-85bd-82de8a4dab03" # model.metrics.r2_score(y_val, y_pred) # + id="XmRB4XlV9a_2" # y_pred.dtype, y_eval.shape, y_test.shape, y_val.shape y_pred # + id="Pcg3OdIK9uLS" # y_test.dtype # + id="EOwhVTRf9zOQ" # y_pred = y_pred.astype('int64') # + id="EaKYqnnI_NF2" # y_pred.dtype # + id="3NSN1UvK_rO2" import pandas as pd # + id="eQiXUb22_zOj" # y_pred.dtype # + id="uoHn-s2t_xbE" # + id="0Evhu44g95MH" # y_train.dtype # + id="yIrl72ZE8_lN" # + id="OoBCNLWcJ89p"
RNN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from joblib import dump, load import numpy as np import pandas as pd from sklearn.decomposition import NMF from sklearn.impute import KNNImputer from sqlalchemy import create_engine from credentials import PG_USER, PG_PASSWORD, PG_URL # - DATABASE_USER = PG_USER DATABASE_PASSWORD = <PASSWORD> DATABASE_HOST = PG_URL DATABASE_PORT = "5432" DATABASE_DB_NAME = "movielens" conn = f"postgres://{DATABASE_USER}:{DATABASE_PASSWORD}@{DATABASE_HOST}:{DATABASE_PORT}/{DATABASE_DB_NAME}" # get ratings for 2019 for each movie with ratings >= 5 (implemented as a view in database) filtered_ratings_2019 = pd.read_sql_table('filtered_ratings_2019', conn) filtered_ratings_2019 movies = pd.read_sql_table('movies', conn) movies.head() # ### Combine Data for NMF # Create input table for NMF rtrue = filtered_ratings_2019 rtrue = rtrue.pivot(index='user_id', columns='movie_id') rtrue.shape # Fill missing values n = 1000 # chunk row size list_df = [rtrue[i:i+n] for i in range(0,rtrue.shape[0],n)] # create chunks to make computation easier # + ### Alternative: fill na's with imputed values # from sklearn.impute import KNNImputer # imputer = KNNImputer(n_neighbors=5) # for i in range(len(list_df)): # list_df[i] = pd.DataFrame(imputer.fit_transform(list_df[i]), columns=list_df[i].columns, index=list_df[i].index) # - for i in range(len(list_df)): list_df[i] = list_df[i].fillna(2.5) rtrue_fill = pd.concat(list_df) rtrue_fill.shape # Remove unnecessary column index from Rtrue rtrue_fill.columns = rtrue_fill.columns.droplevel(0) # + # Save vector for faster execution in web app # dump(rtrue_fill, "../data/rtrue_fillna_25.joblib") # - movie_ids = filtered_ratings_2019.groupby('movie_id')['rating'].mean().index mean_rating_vector = filtered_ratings_2019.groupby('movie_id')[['rating']].mean() mean_rating_vector # + # Save vector for faster execution in web app # dump(mean_rating_vector, "../data/mean_rating_vector.joblib") # - mean_rating_vector = load("../data/mean_rating_vector.joblib") mean_rating_vector.transpose() # ### Train model m = NMF(n_components=20, max_iter=100) m.fit(rtrue_fill) # + # Save model for faster execution in web app # dump(m, "../data/nmf_model.joblib") # - # Get the two matrices P, Q out P = m.components_ Q = m.transform(rtrue_fill) P.shape, Q.shape # Reconstruct np.dot(Q, P).round(1) # ### Prediction new_user = [2.5] * len(movie_ids) # Take movie id's from landing page movies_seen = [ 858, # The Godfather 63992, # Twilight 58559, # The Dark Knight 1924, # Plan 9 from Outer Space 2324, # Life is Beautiful 171011, # Planet Earth II 177765, # Coco 296, # Pulp Fiction 5618, # Spirited Away 1136, # Monty Python and the Holy Grail ] # Get column indices from Rtrue indices = [] for movie_seen in movies_seen: indices.append(np.where(movie_ids == movie_seen)[0][0]) indices for i in indices: new_user[i] = 5 # Prepare ratings new_user_final = np.array([new_user]) user_profile = m.transform(new_user_final) user_profile.shape result = np.dot(user_profile[0], P) result.shape result new_result = pd.DataFrame(result) new_result = new_result.transpose().copy() new_result.columns = rtrue_fill.columns # Create dict with 20 highest scoring recommendations recommendations = new_result.iloc[0].sort_values(ascending=False)[:20].to_dict() # Remove already seen movies clean_recommendations = {} for key, value in recommendations.items(): if key not in movies_seen: clean_recommendations[key] = value # Print out recommendations for new user print('-' * 20 + '\nRECOMMENDATIONS FOR NEW USER\n' + '-' * 20) for index, score in clean_recommendations.items(): print(movies[movies.movie_id == index].title.values[0], f"- ({score:.2f})")
scripts/movielens_implement_nmf.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Import dependencies from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import requests # For Mac Users # !which chromedriver executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path, headless=False) # Use Splinter to visit the NASA website url= 'https://mars.nasa.gov/news/' browser.visit(url) # Iterate through x number of pages in website for x in range(1): html=browser.html soup=bs(html, 'html.parser') articles = soup.find('div', class_articles='grid_layout') article = articles.find('li', class_articles='slide') print(article)
.ipynb_checkpoints/web_scrape-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Introduction # <div class="alert alert-warning"> # <font color=black> # # **What?** Public, Private, Protected attributes # # </font> # </div> # # What is encapsulation? # <div class="alert alert-info"> # <font color=black>< # # - Encapsulation is seen as the bundling of data with the methods that operate on that data. # - It is often accomplished by providing two kinds of methods for attributes. # - The methods for retrieving or accessing the values of attributes are called **getter methods**. Getter methods do not change the values of attributes, they just return the values. # - The methods used for changing the values of attributes are called **setter methods**. # # </font> # </div> # ## Public, Private, Protected # <div class="alert alert-info"> # <font color=black> # # There are two ways to restrict the access to class attributes: # # 1. **protected**. First, we can prefix an attribute name with a leading underscore "_". It tells users of the class not to use this attribute unless, somebody writes a subclass. # 2. **private**. Second, we can prefix an attribute name with two leading underscores "__". The attribute is now inaccessible and invisible from outside. It's neither possible to read nor write to those attributes except inside of the class definition itself. # # </font> # </div> # + class A: def __init__(self): self.public = "I am public" self._protected = "I am protected" self.__private = "I am private" instantiationOfA = A() # - print(instantiationOfA.public) print(instantiationOfA._protected) print(instantiationOfA._A__private) # <div class="alert alert-info"> # <font color=black> # # - Whenever we assign or retrieve any object attribute Python searches it in the object's `__dict__` dictionary # - When the Python compiler sees a private attribute, it actually transforms the actual name to `_[Class name]__[private attribute name]`. # - **In practice** it is more common to use public and protected attribute, # # </font> # </div> print(instantiationOfA.__dict__) # ## Class Decorators # - `@property` The Pythonic way to introduce attributes is to make them public, and not introduce getters and setters to retrieve or change them. # - `@classmethod` To add additional constructor to the class. # - `@staticmethod` To attach functions to classes so people won't misuse them in wrong places. # ### @Property # Let's assume one day we decide to make a class that could store the temperature in degree Celsius. The temperature will be a private method, so our end-users won't have direct access to it. # # The class will also implement a method to convert the temperature into degree Fahrenheit. And we also want to implement a value constraint to the temperature, so that it cannot go below -273 degree Celsius. One way of doing this is to define a getter and setter interfaces to manipulate it. class Celsius: def __init__(self, temperature = 0): self.set_temperature(temperature) def to_fahrenheit(self): return (self.get_temperature() * 1.8) + 32 def get_temperature(self): return self._temperature def set_temperature(self, value): if value < -273: raise ValueError('Temperature below -273 is not possible') self._temperature = value # c = Celsius(-277) # this returns an error c = Celsius(37) c.get_temperature() # Instead of that, now the **property** way. Where we define the `@property` and the `@[attribute name].setter`. class Celsius: def __init__(self, temperature = 0): self._temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 # have access to the value like it is an attribute instead of a method @property def temperature(self): return self._temperature # like accessing the attribute with an extra layer of error checking @temperature.setter def temperature(self, value): if value < -273: raise ValueError('Temperature below -273 is not possible') print('Setting value') self._temperature = value # + c = Celsius(37) # much easier to access then the getter, setter way print(c.temperature) # note that you can still access the private attribute # and violate the temperature checking, # but then it's the users fault not yours c._temperature = -300 print(c._temperature) # accessing the attribute will return the ValueError error # c.temperature = -300 # - # ### @classmethod and @staticmethod # `@classmethods` create alternative constructors for the class. An example of this behavior is there are different ways to construct a dictionary. print(dict.fromkeys(['raymond', 'rachel', 'mathew'])) # + import time class Date: # Primary constructor def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Alternate constructor @classmethod def today(cls): t = time.localtime() return cls(t.tm_year, t.tm_mon, t.tm_mday) # Primary a = Date(2012, 12, 21) print(a.__dict__) # Alternate b = Date.today() print(b.__dict__) # - # The `cls` is critical, as it is an object that holds the class itself. This makes them work with inheritance. # + class NewDate(Date): pass # Creates an instance of Date (cls=Date) c = Date.today() print(c.__dict__) # Creates an instance of NewDate (cls=NewDate) d = NewDate.today() print(d.__dict__) # - # The purpose of **@staticmethod** is to attach functions to classes. We do this to improve the findability of the function and to make sure that people are using the function in the appropriate context. class Date: # Primary constructor def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Alternate constructor @classmethod def today(cls): t = time.localtime() return cls(t.tm_year, t.tm_mon, t.tm_mday) # the logic belongs with the date class @staticmethod def show_tomorrow_date(): t = time.localtime() return t.tm_year, t.tm_mon, t.tm_mday + 1 Date.show_tomorrow_date() # # References # <div class="alert alert-warning"> # <font color=black> # # - http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/python/class.ipynb # - [Python Tutorials: Python @property](http://www.programiz.com/python-programming/property) # - [Onlines Python Course Notes: Properties vs. Getters and Setters](http://www.python-course.eu/python3_properties.php) # # </font> # </div>
Public, Private, Protected attributes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Monte Carlo Methods: Computation of Pi # ## Basics: variables, values, printing Ntotal = 100 print(Ntotal) Nin = 55.0 print(Ntotal/Nin) # ## Random Numbers: Uniformly Distributed Random Numbers import random random.uniform(0.0,1.0) random.uniform(0.0,1.0) random.uniform(0.0,1.0) random.uniform(0.0,1.0) # ## Generating "dots" - random x, random y, and r # + import math import random Ntotal = 100 Nin = 0 x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) print(x) print(y) print(r) # - # ## The range() sequence type # # If you want to generate a series of numbers in a sequence, e.g. 1,2,3,4..., then you want the range() *immutable sequence type* (or its equivalent in some other Python library). See the example below. ```range()``` doesn't directly create a list of numbers; it is its own type in Python. To get a list from it, see below. # + list_of_numbers=list(range(1,5)) print(list_of_numbers) # Note that the list EXCLUDES the endpoint. If you want to get a list of 5 numbers, from 1-5, # then you need to extend the endpoint by 1: list_of_numbers=list(range(1,6)) print(list_of_numbers) # or this list_of_numbers=list(range(0,5)) print(list_of_numbers) # - # ## Putting things together: "looping" 100 times and printing r each time # # Let's put things together now. We can create a variable that stores the number of iterations ("loops") of the calculation we want to do. Let's call that ```Ntotal```. Let's then loop 100 times and each time make a random ```x```, random ```y```, and from that compute $r=\sqrt{x^2+y^2}$. # # Note that Python uses indentation to indicate a related block of code acting as a "subroutine" - a program within the program. import math Ntotal = 100 Nin = 0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) print("x=%f, y=%f, r=%f" % (x,y,r)) # ## Monte Carlo - Accept/Reject # # Now that we can make random "dots" in x,y and compute the radius (relative to 0,0) of each dot, let's employ "Accept/Reject" to see if something is in/on the circle or outside the circle. All we have to do is, for each $r$, test whether $r \le R$ or $r > R$. If the former, we have a dot in the circle - a hit! If the latter, then we have a dot out of the circle - a miss! We accept the hits and reject the misses. The total number of points define all the moves in the game, and the ratio of hits to the total will tell us about the area of the circle, and thus get us closer to $\pi$. # + Ntotal = 100 Nin = 0 R = 1.0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) if r <= R: Nin = Nin + 1 # alternatively, Nin += 1 (auto-increment by 1) print("Number of dots: %d" % Ntotal) print("Number of hits: %d" % Nin) print("Number of misses: %d" % (Ntotal-Nin)) my_pi = 4.0*float(Nin)/float(Ntotal) print("pi = %f" % (my_pi)) # - # ## Precision in Monte Carlo Simulation # # The number above is probably close to what you know as $\pi$, but likely not very precise. After all, we only threw 100 dots. We can increase precision by *increasing the number of dots*. In the code block below, feel free to play with ```Ntotal```, trying different values. Observe how the computed value of $\pi$ changes. Would you say it's "closing in" on the value you know, or not? Try ```Ntotal``` at 1000, 5000, 10000, 50000, and 100000. # # In the code block below, I have also added a computation of *statistical error*. The error should be a *binomial error*. Binomial errors occur when you have a bunch of things and you can classify them in two ways: as $A$ and $\bar{A}$ ("A" and "Not A"). In our case, they are hits or "not hits" (misses). So binomial errors apply. A binomial error is computed below. # + Ntotal = 100 Nin = 0 R = 1.0 for i in range(0,Ntotal): x = random.uniform(0.0,1.0) y = random.uniform(0.0,1.0) r = math.sqrt(x**2 + y**2) if r <= R: Nin = Nin + 1 # alternatively, Nin += 1 (auto-increment by 1) my_pi = 4.0*float(Nin)/float(Ntotal) my_pi_uncertainty = my_pi * math.sqrt(1.0/float(Nin) + 1.0/float(Ntotal)) print("pi = %.6f +/- %.6f (percent error= %.2f%%)" % (my_pi, my_pi_uncertainty, 100.0*my_pi_uncertainty/my_pi))
pi_monte_carlo/Monte Carlo Lecture Code.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Process Optimization - the `Main` code # # ### Fourth Batch of Bayesian Optimization based on Experimental Data produced on Nov 8, 2020 # - This notebook is to run Bayesian Optimization on initial sampling data, and provide the first batch suggestion on experiment conditions # - Experiments of perovskite devices are prepared by <NAME> and <NAME> (Stanfrod University) # - Jupyter Notebook is prepared by <NAME> (Massachusetts Insititute of Technology) import numpy as np import pandas as pd import emukit import GPy import sklearn import matplotlib.pyplot as plt import seaborn as sns df_all_device = pd.read_excel("../Experimental Data/All_device_data_processed_20210126.xlsx", sheet_name= "Sheet1") print(df_all_device.columns) df_all_device = df_all_device.iloc[:,2:13] df_all_device = df_all_device.dropna() df_all_device.columns = ['Temperature [\N{DEGREE SIGN}C]', 'Speed [mm/s]', 'Spray Flow [uL/min]', 'Plamsa Height [cm]', 'Plasma Gas Flow [L/min]', 'Plasma DC [%]', 'Jsc [mA/cm2]', 'Voc [V]', 'FF [-]', 'Efficiency [%]','Film Quality?'] df_all_device # + from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import r2_score from scipy.stats import spearmanr X=df_all_device.iloc[:,:6] y=df_all_device['Efficiency [%]'] X=X.to_numpy(dtype='float') y=y.to_numpy(dtype='float').reshape(-1,1) X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2) scaler = StandardScaler() scaler.fit(X) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) X = scaler.transform(X) scaler_y = StandardScaler() scaler_y.fit(y) y_train = scaler_y.transform(y_train) y_test = scaler_y.transform(y_test) y = scaler_y.transform(y) # - #print(gb_random.best_params_) best_params = {'subsample': 0.95, 'n_estimators': 105, 'min_samples_split': 2, 'min_samples_leaf': 2, 'max_features': 'sqrt', 'max_depth': 4, 'learning_rate': 0.075, 'alpha':0.99 } from sklearn.ensemble import GradientBoostingRegressor GBregressor_list = [] y_pred_list = [] y_train_pred_list = [] y_test_pred_list = [] for i in np.arange(100): GBregressor = GradientBoostingRegressor() GBregressor.set_params(**best_params) GBregressor.fit(X_train, y_train.ravel()) #GBregressor.fit(X, y.ravel()) GBregressor_list.append(GBregressor) y_train_pred=scaler_y.inverse_transform(GBregressor_list[i].predict(X_train).reshape(-1,1)) y_test_pred=scaler_y.inverse_transform(GBregressor_list[i].predict(X_test).reshape(-1,1)) y_pred=scaler_y.inverse_transform(GBregressor_list[i].predict(X).reshape(-1,1)) y_train_pred_list.append(y_train_pred) y_test_pred_list.append(y_test_pred) y_pred_list.append(y_pred) y_pred_mean = np.mean(y_pred_list, axis = 0) y_train_pred_mean = np.mean(y_train_pred_list, axis = 0) y_test_pred_mean = np.mean(y_test_pred_list, axis = 0) # + y_train_pred = y_train_pred_mean y_test_pred = y_test_pred_mean y_pred = y_pred_mean from sklearn.metrics import mean_squared_error mse = mean_squared_error mse_train = mse(y_train_pred,scaler_y.inverse_transform(y_train)) mse_test = mse(y_test_pred,scaler_y.inverse_transform(y_test)) mse_all = mse(y_pred,scaler_y.inverse_transform(y)) print ('train rmse: %.4f' % (np.sqrt(mse_train))) print ('test rmse: %.4f' % (np.sqrt(mse_test))) print ('all rmse: %.4f' % (np.sqrt(mse_all))) rsquared_train = r2_score(scaler_y.inverse_transform(y_train),y_train_pred) rsquared_test = r2_score(scaler_y.inverse_transform(y_test), y_test_pred) rsquared_all = r2_score(scaler_y.inverse_transform(y), y_pred) print ('train R^2: %.4f' % (rsquared_train)) print ('test R^2: %.4f' % (rsquared_test)) print ('all R^2: %.4f' % (rsquared_all)) sprman_train = spearmanr(y_train_pred,scaler_y.inverse_transform(y_train)) sprman_test = spearmanr(y_test_pred,scaler_y.inverse_transform(y_test)) sprman_all = spearmanr(y_pred,scaler_y.inverse_transform(y)) print ('train spearman: %.4f' % (sprman_train[0])) print ('test spearman: %.4f' % (sprman_test[0])) print ('all spearman: %.4f' % (sprman_all[0])) fs = 22 plt.figure(figsize=(6, 5)) plt.scatter(scaler_y.inverse_transform(y_train),y_train_pred, alpha =0.5) plt.scatter(scaler_y.inverse_transform(y_test),y_test_pred, alpha =0.5) #plt.scatter(y_scaled,y_pred, alpha =0.5) yref = np.arange(0, 20, 0.5) plt.plot(yref, yref, '--',color='black') plt.xlabel('Ground truth efficiency [%]', fontsize = fs) plt.ylabel('Prediction efficiency [%]', fontsize = fs) plt.xticks([0, 5, 10, 15, 20]) #plt.title("Gradient Boosting") plt.tick_params(direction='in', length=5, width=1, labelsize = fs*.8, grid_alpha = 0.5) #plt.savefig("Pervoskite Opt for Scale-up/Prelim_data_analysis/data_plots/RFR"+str(X1.name[:4])+".png",dpi=300) plt.show() # + Xc = df_all_device.iloc[:,:6] yc = [] for i in np.array(df_all_device.iloc[:,-1].values): if i == 'Yes': yc.append(1) elif i == 'No': yc.append(0) Xc=Xc.to_numpy(dtype='float') yc=np.array(yc).reshape(-1,1) Xc_train,Xc_test,yc_train,yc_test=train_test_split(Xc,yc,test_size=0.2) scaler_Xc = StandardScaler() scaler_Xc.fit(Xc) Xc_train = scaler.transform(Xc_train) Xc_test = scaler.transform(Xc_test) Xc = scaler.transform(Xc) # - best_params_ = {'subsample': 0.90, 'n_estimators': 70, 'min_samples_split': 2, 'min_samples_leaf': 1, 'max_features': 'sqrt', 'max_depth': 4, 'learning_rate': 0.125, #'alpha':0.0001 } from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier GBclassifier_Cons_list = [] yc_pred_list = [] yc_train_pred_list = [] yc_test_pred_list = [] for i in np.arange(100): GBclassifier_Cons = GradientBoostingClassifier() GBclassifier_Cons.set_params(**best_params_) GBclassifier_Cons.fit(Xc_train, yc_train.ravel()) GBclassifier_Cons.fit(Xc, yc.ravel()) GBclassifier_Cons_list.append(GBclassifier_Cons) yc_train_pred=GBclassifier_Cons_list[i].predict_proba(Xc_train)[:,1] yc_test_pred=GBclassifier_Cons_list[i].predict_proba(Xc_test)[:,1] yc_pred=GBclassifier_Cons_list[i].predict_proba(Xc)[:,1] yc_train_pred_list.append(yc_train_pred) yc_test_pred_list.append(yc_test_pred) yc_pred_list.append(yc_pred) yc_pred_mean = np.mean(yc_pred_list, axis = 0) yc_train_pred_mean = np.mean(yc_train_pred_list, axis = 0) yc_test_pred_mean = np.mean(yc_test_pred_list, axis = 0) # + yc_train_pred = yc_train_pred_mean yc_test_pred = yc_test_pred_mean yc_pred = yc_pred_mean from sklearn.metrics import mean_squared_error mse = mean_squared_error mse_train = mse(yc_train_pred,yc_train) mse_test = mse(yc_test_pred,yc_test) mse_all = mse(yc_pred, yc) print ('train rmse: %.4f' % (np.sqrt(mse_train))) print ('test rmse: %.4f' % (np.sqrt(mse_test))) print ('all rmse: %.4f' % (np.sqrt(mse_all))) rsquared_train = r2_score(yc_train,yc_train_pred) rsquared_test = r2_score(yc_test, yc_test_pred) rsquared_all = r2_score(yc, yc_pred) print ('train R^2: %.4f' % (rsquared_train)) print ('test R^2: %.4f' % (rsquared_test)) print ('all R^2: %.4f' % (rsquared_all)) sprman_train = spearmanr(yc_train_pred, yc_train) sprman_test = spearmanr(yc_test_pred,yc_test) sprman_all = spearmanr(yc_pred,yc) print ('train spearman: %.4f' % (sprman_train[0])) print ('test spearman: %.4f' % (sprman_test[0])) print ('all spearman: %.4f' % (sprman_all[0])) fs = 22 plt.figure(figsize=(6, 5)) plt.scatter(yc_train,yc_train_pred, alpha =0.5) plt.scatter(yc_test,yc_test_pred, alpha =0.5) #plt.scatter(y_scaled,y_pred, alpha =0.5) ycref = np.arange(0, 1.1, 0.1) plt.plot(ycref, ycref, '--',color='black') plt.xlabel('Ground truth efficiency [%]', fontsize = fs) plt.ylabel('Prediction efficiency [%]', fontsize = fs) plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1]) #plt.title("Gradient Boosting") plt.tick_params(direction='in', length=5, width=1, labelsize = fs*.8, grid_alpha = 0.5) #plt.savefig("Pervoskite Opt for Scale-up/Prelim_data_analysis/data_plots/RFR"+str(X1.name[:4])+".png",dpi=300) plt.show() # - # ### Load the previous experimental data df_previous = pd.read_excel("./new_plamsa_previous_selected_20200927.xlsx", sheet_name= "Sheet1") df_previous.iloc[:,2] = df_previous.iloc[:,2] /10 df_previous.iloc[:,3] = df_previous.iloc[:,3] /1000 df_previous = df_previous.iloc[:,:11] print(df_previous.columns) df_previous.columns = ['', 'Temperature [\N{DEGREE SIGN}C]', 'Speed [cm/s]', 'Spray Flow [mL/min]', 'Plamsa Height [cm]', 'Plasma Gas Flow [L/min]', 'Plasma DC [%]', 'Jsc [mA/cm2]', 'Voc [V]', 'FF [-]', 'Efficiency [%]'] df_previous = df_previous.sort_values(by=list(df_previous.iloc[:,[1,2,3,4,5,6,-1]].columns), ignore_index = True) # df_previous = df_previous.drop_duplicates(['Temperature [\N{DEGREE SIGN}C]', 'Speed [mm/s]', # 'Spray Flow [uL/min]', 'Plamsa Height [cm]', 'Plasma Gas Flow [L/min]', 'Plasma DC [%]'], keep = 'last', ignore_index = True) df_previous = df_previous.iloc[:,1:] df_previous # + ## Total process conditions: 11x9x7x5x4x3 = 41580 conditions temp_min, temp_max, temp_step = [125, 175, 5] ## Unit: degC ## 11 steps temp_var = np.arange(temp_min, temp_max+temp_step, temp_step) temp_num = len(temp_var) speed_min, speed_max, speed_step = [100, 300, 25] ## Unit: mm/s ## 9 steps speed_var = np.arange(speed_min, speed_max+speed_step, speed_step) speed_num = len(speed_var) sprayFL_min, sprayFL_max, sprayFL_step = [2000, 5000, 500] ## Unit: uL/min ## 7 steps sprayFL_var = np.arange(sprayFL_min, sprayFL_max+sprayFL_step, sprayFL_step) sprayFL_num = len(sprayFL_var) gasFL_min, gasFL_max, gasFL_step = [15, 35, 5] ## Unit: L/min ## 5 steps gasFL_var = np.arange(gasFL_min, gasFL_max+gasFL_step, gasFL_step) gasFL_num = len(gasFL_var) plasmaDC_min, plasmaDC_max, plasmaDC_step = [25, 100, 25] # Unit: [%] ## 4 steps plasmaDC_var = np.arange(plasmaDC_min, plasmaDC_max+plasmaDC_step, plasmaDC_step) plasmaDC_num = len(plasmaDC_var) plasmaH_min, plasmaH_max, plasmaH_step = [0.8, 1.2, 0.2] # Unit: cm ## 3 steps plasmaH_var = np.arange(plasmaH_min, plasmaH_max+plasmaH_step, plasmaH_step) plasmaH_num = len(plasmaH_var) var_array = [temp_var, speed_var, sprayFL_var, plasmaH_var, gasFL_var, plasmaDC_var] x_labels = ['Temperature [\N{DEGREE SIGN}C]', 'Speed [mm/s]', 'Spray Flow [uL/min]', 'Plamsa Height [cm]', 'Plasma Gas Flow [L/min]', 'Plasma DC [%]'] # + def x_normalizer(X): def max_min_scaler(x, x_max, x_min): return (x-x_min)/(x_max-x_min) x_norm = [] for x in (X): x_norm.append([max_min_scaler(x[i], max(var_array[i]), min(var_array[i])) for i in range(len(x))]) return np.array(x_norm) def x_denormalizer(x_norm): def max_min_rescaler(x, x_max, x_min): return x*(x_max-x_min)+x_min x_original = [] for x in (x_norm): x_original.append([max_min_rescaler(x[i], max(var_array[i]), min(var_array[i])) for i in range(len(x))]) return np.array(x_original) def get_closest_array(suggested_x): def get_closest_value(given_value, array_list): absolute_difference_function = lambda list_value : abs(list_value - given_value) closest_value = min(array_list, key=absolute_difference_function) return closest_value var_list = var_array modified_array = [] for x in suggested_x: modified_array.append([get_closest_value(x[i], var_list[i]) for i in range(len(x))]) return np.array(modified_array) # + from emukit.core import ParameterSpace, ContinuousParameter, DiscreteParameter from emukit.core.initial_designs.random_design import RandomDesign from emukit.core.initial_designs.latin_design import LatinDesign parameter_space = ParameterSpace([ContinuousParameter('temp', 0-1/(temp_num-1)/2, 1+1/(temp_num-1)/2), ContinuousParameter('speed', 0-1/(speed_num-1)/2, 1+1/(speed_num-1)/2), ContinuousParameter('sprayFL', 0-1/(sprayFL_num-1)/2, 1+1/(sprayFL_num-1)/2), ContinuousParameter('plamsaH', 0-1/(plasmaH_num-1)/2, 1+1/(plasmaH_num-1)/2), ContinuousParameter('gasFL', 0-1/(gasFL_num-1)/2, 1+1/(gasFL_num-1)/2), ContinuousParameter('plasmaDC', 0-1/(plasmaDC_num-1)/2, 1+1/(plasmaDC_num-1)/2) ]) # - df_thiswork = pd.read_excel("./Experimental Data/All_device_data_processed_20210126.xlsx", sheet_name= "Sheet1") df_thiswork = df_thiswork.iloc[:99,0:13] thiswork_device = df_thiswork['Film Success or not?'] == 'Yes' df_thiswork[thiswork_device].iloc[:,2:-1] def f_obj(x): y_hat_list = [] for i in np.arange(len(GBregressor_list)): y_hat = GBregressor_list[i].predict(scaler.transform(x)) y_hat_list.append(y_hat) y_hat_mean = np.mean(y_hat_list, axis = 0) y_pred = scaler_y.inverse_transform(y_hat_mean) return y_pred # + design = RandomDesign(parameter_space) x_sampled = design.get_samples(200) x_columns = df_thiswork.iloc[:,2:8].columns input_dim = len(x_columns) for i in range(input_dim): for j in range(input_dim-i-1): ## Generate a 2D grid for Contour plot ind1 = i ind2 = j+i+1 n_steps =21 x1x2y_pred, x1x2y_uncer =[[],[]] for x1 in np.linspace(0, 1, n_steps): for x2 in np.linspace(0, 1, n_steps): x_temp = np.copy(x_sampled) x_temp[:,ind1] = x1 x_temp[:,ind2] = x2 y_pred = f_obj(x_denormalizer(x_temp)) x1_org = x_denormalizer(x_temp)[0,ind1] x2_org = x_denormalizer(x_temp)[0,ind2] x1x2y_pred.append([x1_org, x2_org, np.max(y_pred), np.mean(y_pred), np.min(y_pred)]) x1 = np.array(x1x2y_pred, dtype=object)[:,0].reshape(n_steps, n_steps) x2 = np.array(x1x2y_pred, dtype=object)[:,1].reshape(n_steps, n_steps) y_pred_max = np.array(x1x2y_pred, dtype=object)[:,2].reshape(n_steps, n_steps) y_pred_mean = np.array(x1x2y_pred, dtype=object)[:,3].reshape(n_steps, n_steps) y_pred_min = np.array(x1x2y_pred, dtype=object)[:,4].reshape(n_steps, n_steps) fs = 20 title_pad = 16 ## Contour for Prediction Efficiency Mean fig,axes = plt.subplots(1, 3, figsize=(17, 4), sharey = False, sharex = False) colorbar_offset = [12.5, 7, 4] for ax, c_offset, y in zip(axes, colorbar_offset, [y_pred_max, y_pred_mean, y_pred_min]): c_plt1 = ax.contourf(x1, x2, y, levels = np.arange(19)*0.25+c_offset, cmap='plasma', extend = 'both') cbar = fig.colorbar(c_plt1, ax= ax) cbar.ax.tick_params(labelsize=fs*0.8) # ax.scatter(x_denormalizer(X)[:, ind1], # x_denormalizer(X)[:, ind2], # s = 55, facecolors='none', alpha = 0.9, edgecolor = 'green') # ax.scatter(x_denormalizer(Xc[Yc[:,-1]==0])[:, ind1], ## show the conditions with poor film quality # x_denormalizer(Xc[Yc[:,-1]==0])[:, ind2], # s = 55, facecolors='none', alpha = 0.9, edgecolor = 'red') ax.set_xlabel(str(x_columns[ind1]),fontsize = fs) ax.set_ylabel(str(x_columns[ind2]),fontsize = fs) x1_delta = (np.max(x1)-np.min(x1))*0.05 x2_delta = (np.max(x2)-np.min(x2))*0.05 ax.set_xlim(np.min(x1)-x1_delta, np.max(x1)+x1_delta) ax.set_ylim(np.min(x2)-x2_delta, np.max(x2)+x2_delta) ax.tick_params(direction='in', length=5, width=1, labelsize = fs*.8)#, grid_alpha = 0.5 if ind1==0:#Temp ax.set_xticks([130, 140, 150, 160, 170]) if ind1==1:#Speed ax.set_xticks([10, 15, 20, 25, 30]) if ind1==4:#PlasmaGasFL ax.set_xticks([15, 20, 25, 30, 35]) if ind2==5:#PlasmaDC ax.set_yticks([25, 50, 75, 100]) #ax.grid(True, linestyle='-.') axes[0].set_title('objective fcn max', pad = title_pad,fontsize = fs) axes[1].set_title('objective fcn mean', pad = title_pad,fontsize = fs) axes[2].set_title('objective fcn min', pad = title_pad,fontsize = fs) plt.subplots_adjust(wspace = 0.3) plt.show() # -
Benchmark Simulation/Teacher model results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import forge from puzzle.puzzlepedia import puzzlepedia puzzle = puzzlepedia.parse(""" model.disable_constraints() model.disable_inference() woman in {wA, wB, wC, wD, wE, wF, wG} concealer in {bigger, burning, bye, enthusiastic, makeup, married, shapely} (kinds, colors) in ({eye, lip}, {CA, ER, EU, FI, GR, HE, ID, LE, SH, SP, SE, TY, TH, VA}) eyes = [eyeCA, eyeER, eyeEU, eyeFI, eyeGR, eyeHE, eyeID, eyeLE, eyeSH, eyeSP, eyeSE, eyeVA] lips = [lipCA, lipER, lipEU, lipFI, lipGR, lipHE, lipID, lipLE, lipSH, lipSP, lipSE, lipVA, lipTY, lipTH] # Each woman has one of each. for w in woman: sum(w[c] for c in concealer) == 1 sum(w[e] for e in eyes) == 1 sum(w[l] for l in lips) == 1 # Each concealer is used once. for c in concealer: sum(c[w] for w in woman) == 1 # Each color is used once. for a, b in zip(eyes, lips): sum(w[a] + w[b] for w in woman) == 1 # 5: Someone has matching lipstick and eyeshadow first letter # 6: Number of S lipsticks == number of T lipsticks #12: None of the eyeshadows start with same letter # E E S S S T T # Lip: E E? S S T T # Eye: E? S # Conclusion: Lip has 2 Ss, 2 Ts. sum(any(w[c] for w in woman) for c in [lipSH, lipSP, lipSE]) == 2 sum(any(w[c] for w in woman) for c in [lipTY, lipTH]) == 2 for w in woman: w != eyeTY w != eyeTH #11: FI + ER combo exists # Conclusion: Matching letter is an S, not E. def color(dim, c): return dim['eye' + c] | dim['lip' + c] def color_vector(c): return sum(color(w, c) * i for i, w in zip(range(8), woman)) def matched_vector(dim): return sum(w[dim] * i for i, w in zip(range(8), woman)) def matching_color(w): return ( (color(w, 'ER') + color(w, 'EU') == 2) + ((color(w, 'SH') + color(w, 'SP') + color(w, 'SE')) == 2) + (color(w, 'TY') + color(w, 'TH') == 2) ) # NB: Matching color must be an S. See conclusion above. def matching_color(w): return (color(w, 'SH') + color(w, 'SP') + color(w, 'SE')) == 2 def concealer_vector(c): return sum(w[c] * i for i, w in zip(range(8), woman)) #1: LGTM. wC.lipEU or wC.lipSH #2: LGTM. wC != married wG != married #3: LGTM. #(color(wE, 'TY') and wE.enthusiastic) or (color(wF, 'TY') and wF.enthusiastic) # NB: Ts are lip colors; see above. (wE.lipTY and wE.enthusiastic) or (wF.lipTY and wF.enthusiastic) #4: LGTM. any(bigger[w] and (eyeSE[w] or eyeGR[w]) for w in woman) #5: LGTM. # Someone (not wC) wore first-letter-matching lip & eye #not matching_color(wC) matching_women = [wA, wB, wD, wE, wF, wG] # Duplicates: ER, EU; SH, SP, SE; TY, TH any(matching_color(w) for w in matching_women) #6: LGTM. # NB: Implemented via conclusions above. #7: LGTM. if any(lipSP[w] for w in woman): color(wD, 'CA') #8: LGTM. #8a: Find bbq eyeshadow, shapely lipstick and assign GR xor ID. # Eligible determined via GR | ID eligibility. # B excluded by definition. # C excluded because #1 says lip is either EU or SH (not GR). # G excluded due to #15. shapely_eligible = [wA, wD, wE, wF] shapely_ineligible = [wB, wC, wG] for w in shapely_eligible: if w.shapely: (w.lipGR and wB.eyeID) or (w.lipID and wb.eyeGR) #8b: (These two are different women.) for w in shapely_ineligible: w != shapely #9: LGTM. #9: TH first letter > EU first letter matched_vector(lipTH) > color_vector('EU') #10: TODO. # CA woman and VA woman have matching concealers. # Matching concealers: bigger, burning, bye; makeup, married b_concealers = [bigger, burning, bye] ca_is_b = any(color(w, 'CA') and any(w[c] for c in b_concealers) for w in woman) va_is_b = any(color(w, 'VA') and any(w[c] for c in b_concealers) for w in woman) ca_is_b == va_is_b m_concealers = [makeup, married] ca_is_m = any(color(w, 'CA') and any(w[c] for c in m_concealers) for w in woman) va_is_m = any(color(w, 'VA') and any(w[c] for c in m_concealers) for w in woman) ca_is_m == va_is_m #11: LGTM. #11: FI/ER woman exists any((w.eyeFI and w.lipER) or (w.eyeER and w.lipFI) for w in woman) #12: LGTM. #12: None of the eyeshadows start with the same letter. eye_letters = [ [eyeER, eyeEU], [eyeSH, eyeSP, eyeSE], ] # None of the eyeshadow colors use T; see deduction above. # [eyeTY, eyeTH], # Duplicates: eyeER, eyeEU; eyeSH, eyeSP, eyeSE; eyeTY, eyeTH for eye_group in eye_letters: sum(any(e[w] for e in eye_group) for w in woman) <= 1 #13: Exactly two women used eyeshadow, concealer, or lipstick that started with same name. # wA: None # wB: bigger, burning, bye # wC: eyeCA, lipCA # wD: None # wE: enthusiastic, eyeER, lipER, eyeEU, lipEU # wF: eyeFI, lipFI # wG: eyeGR, lipGR sum([ any([wB.bigger, wB.burning, wB.bye]), any([wC.eyeCA, wC.lipCA]), any([wE.enthusiastic, wE.eyeER, wE.lipER, wE.eyeEU, wE.lipEU]), any([wF.eyeFI, wF.lipFI]), any([wG.eyeGR, wF.lipGR]), ]) == 2 #14: LGTM. wF != eyeHE wF != lipHE wF != eyeER wF != lipER #15: LGTM. wG == lipLE #16: LGTM. # wX.makeup's name is 2+ before burning matched_vector(burning) - matched_vector(makeup) > 1 model.grid() #with init: # debug(str(model)) """) # - colors = 'CA, ER, EU, FI, GR, HE, ID, LE, SH, SP, SE, TY, TH, VA'.split(', ') print(', lip'.join(colors))
src/puzzle/examples/puzzle_boat/4_bonus/makup_kit.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Tutorial: Energy Densities of the Photon Targets # # In this tutorial we will examine the integrated energy densities, $u [{\rm erg}\,{\rm cm}^{-3}]$, produced by the different photon fields that can be subject to inverse Compton scattering. import numpy as np import astropy.units as u from astropy.constants import M_sun from astropy.coordinates import Distance import matplotlib.pyplot as plt # + from agnpy.targets import SSDisk, SphericalShellBLR, RingDustTorus, PointSourceBehindJet from agnpy.emission_regions import Blob from agnpy.utils.plot import load_mpl_rc # matplotlib adjustments load_mpl_rc() u_label = r"$u\,/\,{\rm erg}\,{\rm cm}^{-3}$" u_prime_label = r"$u'\,/\,{\rm erg}\,{\rm cm}^{-3}$" r_label = r"$r\,/\,{\rm cm}$" # - # ## Shakura Sunyeav Disk M_BH = 1e9 * M_sun L_disk = 1e46 * u.Unit("erg s-1") eta = 1 / 12 R_tilde_in = 6 R_tilde_out = 200 disk = SSDisk(M_BH, L_disk, eta, R_tilde_in, R_tilde_out, R_g_units=True) print(disk) # Let us define an array of distances over which we will calculate the integrated energy density $u$, using the `u` class function. Note that by default the energy density is computed in a stationary frame centred in the galaxy. r = np.logspace(15, 21) * u.cm u_disk = disk.u(r) plt.loglog(r, u_disk) plt.ylabel(u_label) plt.xlabel(r_label) plt.show() # Now let us simulate a point source behind the jet with the same luminosity as the disk. In the limit of large # distances the disk energy density should tend to the one of the point source. The point source behind the jet is monochromatic, we assume it has the same dimensionless energy of the photons emitted at the innermost disk radius. ps = PointSourceBehindJet(L_disk, disk.epsilon(disk.R_in)) u_ps = ps.u(r) plt.loglog(r, u_disk, label="SS Disk") plt.loglog(r, u_ps, ls="--", label="point source behind jet") plt.ylabel(u_label) plt.xlabel(r_label) plt.legend() plt.show() print(u_ps / u_disk) # Let us see if also in the frame comoving with the blob the two energy densities overlap in the case of large distances. To compute the energy density in such a frame we just have to pass a `Blob` instance to the `u` function # set the spectrum normalisation (total energy in electrons in this case) spectrum_norm = 1e48 * u.Unit("erg") # define the spectral function through a dictionary spectrum_dict = { "type": "PowerLaw", "parameters": {"p": 2.8, "gamma_min": 1e2, "gamma_max": 1e7}, } R_b = 1e16 * u.cm B = 1 * u.G z = Distance(1e27, unit=u.cm).z delta_D = 10 Gamma = 10 blob = Blob(R_b, z, delta_D, Gamma, B, spectrum_norm, spectrum_dict) u_prime_disk = disk.u(r, blob) u_prime_ps = ps.u(r, blob) plt.loglog(r, u_prime_disk, label="SS Disk") plt.loglog(r, u_prime_ps, ls="--", label="point source behind jet") plt.ylabel(u_prime_label) plt.xlabel(r_label) plt.legend() plt.show() print(u_prime_ps / u_prime_disk) # **Note** I think that the fact that the energy density ratio does not converge to 1 is due to the expression for the energy density of the Disk not being properly normalised with respect to the radius variable $R$. One in fact can see how, given the same luminosity, changing the external and internal radiuses of the disk will alter the value of $u$ at large distances. This should not be the case as, no matter how geometrically distributed is the luminosity, it should always reduce to the case of a point source at very large distances. # ## Spherical Shell Broad Line Region # Let us compute the energy density of the BLR in the two reference frame (stationary in the galaxy and comoving with the blob) and compare it with a monochromatic point source with the same properties of the BLR. # + blr = SphericalShellBLR(L_disk, 0.1, "Lyalpha", 1e17 * u.cm) # point source with the same luminosity as the BLR ps = PointSourceBehindJet(blr.xi_line * L_disk, blr.epsilon_line) # compute the energy densities in the stationary frame u_blr = blr.u(r) u_ps = ps.u(r) # - plt.loglog(r, u_blr, label="spherical shell BLR") plt.loglog(r, u_ps, ls="--", label="point source behind jet") plt.legend() plt.ylabel(u_label, fontsize=12) plt.xlabel(r_label, fontsize=12) plt.show() print(u_ps / u_blr) # compute the energy densities in teh frame comoving with the blob u_prime_blr = blr.u(r, blob) u_prime_ps = ps.u(r, blob) plt.loglog(r, u_prime_blr, label="spherical shell BLR") plt.loglog(r, u_prime_ps, ls="--", label="point source behind jet") plt.ylabel(u_prime_label, fontsize=12) plt.xlabel(r_label, fontsize=12) plt.legend() plt.show() print(u_prime_ps / u_prime_blr) # as we can see in both reference frames the energy density of the BLR tends to the one of a point source behind the jet for large enough distances. # ## Ring Dust Torus # Finally let us repeat the same exercise for the Torus # + dt = RingDustTorus(L_disk, 0.2, 1000 * u.K) # point source approximating the torus ps = PointSourceBehindJet(dt.xi_dt * L_disk, dt.epsilon_dt) u_dt = dt.u(r) u_ps = ps.u(r) # - plt.loglog(r, u_dt, label="ring dust torus") plt.loglog(r, u_ps, ls="--", label="point source behind jet") plt.ylabel(u_label) plt.xlabel(r_label) plt.legend() plt.show() print(u_ps / u_dt) # compute the energy density in the comoving frame u_prime_dt = dt.u(r, blob) u_prime_ps = ps.u(r, blob) plt.loglog(r, u_prime_dt, label="ring dust torus") plt.loglog(r, u_prime_ps, ls="--", label="point source behind jet") plt.ylabel(u_prime_label) plt.xlabel(r_label) plt.legend() plt.show() print(u_prime_ps / u_prime_dt) # again in both reference frames the energy density of the dust torus tends to the one of a point source behind the jet with its same luminosity.
docs/tutorials/energy_densities.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Iam very sorry because I had to copy the problems given below directly from the textbook, because it is a redundant process. # Moreover the concept of numpy library is a never ending process, because there are a ton of different methods and functions. # I think this is more than enough to learn about numpy. import numpy as np x = np.arange(4) print("x =", x) print("x + 5 =", x + 5) print("x - 5 =", x - 5) print("x * 2 =", x * 2) print("x / 2 =", x / 2) print("x // 2 =", x // 2) # floor division print("-x = ", -x) print("x ** 2 = ", x ** 2) print("x % 2 = ", x % 2) print(np.add(x, 2)) # Absolute value x = np.array([-2, -1, 0, 1, 2]) print(abs(x)) print("---------------------------") x = np.array([3 - 4j, 4 - 3j, 2 + 0j, 0 + 1j]) print(np.abs(x)) # + # Trigonometric functions theta = np.linspace(0, np.pi, 3) print("---------------------------") print("theta = ", theta) print("sin(theta) = ", np.sin(theta)) print("cos(theta) = ", np.cos(theta)) print("tan(theta) = ", np.tan(theta)) print("---------------------------") x = [-1, 0, 1] print("x = ", x) print("arcsin(x) = ", np.arcsin(x)) print("arccos(x) = ", np.arccos(x)) print("arctan(x) = ", np.arctan(x)) # + # Exponents and logarithms x = [1, 2, 3] print("x =", x) print("e^x =", np.exp(x)) print("2^x =", np.exp2(x)) print("3^x =", np.power(3, x)) print("---------------------------") x = [1, 2, 4, 10] print("x =", x) print("ln(x) =", np.log(x)) print("log2(x) =", np.log2(x)) print("log10(x) =", np.log10(x)) print("---------------------------") x = [0, 0.001, 0.01, 0.1] print("exp(x) - 1 =", np.expm1(x)) print("log(1 + x) =", np.log1p(x)) # + # Another excellent source for more specialized and obscure ufuncs is the submodule # scipy.special. If you want to compute some obscure mathematical function on # your data, chances are it is implemented in scipy.special. from scipy import special x = [1, 5, 10] print("gamma(x) =", special.gamma(x)) print("ln|gamma(x)| =", special.gammaln(x)) print("beta(x, 2) =", special.beta(x, 2)) print("---------------------------") # Error function (integral of Gaussian) # its complement, and its inverse x = np.array([0, 0.3, 0.7, 1.0]) print("erf(x) =", special.erf(x)) print("erfc(x) =", special.erfc(x)) print("erfinv(x) =", special.erfinv(x)) # + # Advanced Ufunc Features # Specifying output x = np.arange(5) y = np.empty(5) np.multiply(x, 10, out=y) print(y) print("---------------------------") y = np.zeros(10) np.power(2, x, out=y[::2]) print(y) # + # Aggregates x = np.arange(1, 6) print(np.add.reduce(x)) print("---------------------------") print(np.multiply.reduce(x)) print("---------------------------") print(np.add.accumulate(x)) print("---------------------------") print(np.multiply.accumulate(x))
Numpy/Numpy_Examples3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from rule_learner import * # + data_file = "../data_sets/titanic.csv" data = pd.read_csv(data_file) # take a subset of attributes data = data[['Pclass', 'Sex', 'Age', 'Survived']] # drop all columns and rows with missing values data = data.dropna(how="any") print("Total rows", len(data)) column_list = data.columns.to_numpy().tolist() print("Columns:", column_list) # we can set different accuracy thresholds # here we can reorder class labels - to first learn the rules with class label "survived". rules = learn_rules(column_list, data, [1, 0], 30, 0.6) from operator import attrgetter # sort rules by accuracy descending rules.sort(key=attrgetter('accuracy', 'coverage'), reverse=True) for rule in rules[:10]: print(rule)
classification_rules_titanic.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="BbvE_VQw-3wp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 104} outputId="b05d00d7-9324-49b5-a671-c9d6cbb50a8f" import pandas as pd import re import numpy as np from nltk.tokenize import word_tokenize from nltk import PorterStemmer from nltk import WordNetLemmatizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import torch from torch import nn, optim import torch.nn.functional as F import nltk nltk.download('punkt') nltk.download('wordnet') # + id="H8BicaMd_Zks" colab_type="code" colab={} class Network(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10000, 512) self.fc2 = nn.Linear(512, 64) self.fc3 = nn.Linear(64, 2) self.drop = nn.Dropout(p=0.2) def forward(self, x): x = self.drop(F.relu(self.fc1(x))) x = self.drop(F.relu(self.fc2(x))) x = self.fc3(x) return x # + id="stpJKTK3_dtz" colab_type="code" colab={} def preprocess(df): df = df.apply(lambda s: re.sub(r'[^a-zA-Z]', ' ', s)) df = df.apply(lambda s: word_tokenize(s)) ps = PorterStemmer() df = df.apply(lambda s: [ps.stem(word) for word in s]) lm = WordNetLemmatizer() df = df.apply(lambda s: [lm.lemmatize(word) for word in s]) df = df.apply(lambda s: ' '.join(s)) return df # + id="O0vwYCrh_gEA" colab_type="code" colab={} def train(model, criterion, optimizer, X_train, Y_train, X_test, Y_test, epochs): train_loss, val_loss = [], [] for e in range(epochs): model.train() x, y = X_train.float(), Y_train.long() optimizer.zero_grad() output = model.forward(x) loss = criterion(output, y) loss.backward() optimizer.step() t_loss = (loss.item() * x.size(0)) / len(x) model.eval() x, y = X_test.float(), Y_test.long() output = model.forward(x) loss = criterion(output, y) v_loss = (loss.item() * x.size(0)) / len(x) train_loss.append(t_loss) val_loss.append(v_loss) print(f"Epoch: {e+1} | Training Loss: {t_loss} | Validation Loss: {v_loss}") if train_loss[-1] < val_loss[-1] and e >= 10: break plt.plot(range(1, len(train_loss)+1), train_loss, 'b-', label='Training Loss') plt.plot(range(1, len(val_loss)+1), val_loss, 'r-', label='Validation Loss') plt.xticks(range(0, 20, 2)) plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend(loc='best') plt.show() # + id="ijUxLVZt_lDp" colab_type="code" colab={} def test(model, X_val, Y_val): model.eval() x, y = X_val.float(), Y_val.long() output = model.forward(x) _, pred = torch.max(output, dim=1) correct = pred.eq(y.view_as(pred)).sum() print(f"Test Accuracy: {100. * correct / len(X_val):.2f}%") # + id="Nz87CIRj_vmD" colab_type="code" colab={} def main(): df = pd.read_csv('/content/drive/My Drive/emails.csv') df['text'] = preprocess(df['text']) cv = CountVectorizer(max_features=10000, stop_words='english') sparse_mat = cv.fit_transform(df['text']).toarray() l = np.concatenate((sparse_mat, np.array(df['spam']).reshape(len(sparse_mat), 1)), axis=1) np.random.shuffle(l) X, Y = l[:, :-1], l[:, -1] X_train, X_val, Y_train, Y_val = train_test_split(X, Y, train_size=0.6) X_val, X_test, Y_val, Y_test = train_test_split(X_val, Y_val, train_size=0.2) X_train, Y_train = torch.from_numpy(X_train), torch.from_numpy(Y_train) X_val, Y_val = torch.from_numpy(X_val), torch.from_numpy(Y_val) X_test, Y_test = torch.from_numpy(X_test), torch.from_numpy(Y_test) model = Network() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.01) train(model, criterion, optimizer, X_train, Y_train, X_val, Y_val, epochs=30) test(model, X_test, Y_test) # + id="MiPucgl3_2UD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 505} outputId="d0484057-7786-4cd7-9291-d4c3cfb00275" if __name__ == '__main__': main() # + id="1NKwR8_HDT4E" colab_type="code" colab={}
Assignment2/Spam_Classification.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .scala // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: Apache Toree - Scala // language: scala // name: apache_toree_scala // --- // ## Overview of Sub Queries // // Let us recap about Sub Queries. // + tags=["remove-cell"] // %%HTML <iframe width="560" height="315" src="https://www.youtube.com/embed/6AOlttTRG48?rel=0&amp;controls=1&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> // - // Let us start spark context for this Notebook so that we can execute the code provided. You can sign up for our [10 node state of the art cluster/labs](https://labs.itversity.com/plans) to learn Spark SQL using our unique integrated LMS. val username = System.getProperty("user.name") // + import org.apache.spark.sql.SparkSession val username = System.getProperty("user.name") val spark = SparkSession. builder. config("spark.ui.port", "0"). config("spark.sql.warehouse.dir", s"/user/${username}/warehouse"). enableHiveSupport. appName(s"${username} | Spark SQL - Windowing Functions"). master("yarn"). getOrCreate // - // If you are going to use CLIs, you can use Spark SQL using one of the 3 approaches. // // **Using Spark SQL** // // ``` // spark2-sql \ // --master yarn \ // --conf spark.ui.port=0 \ // --conf spark.sql.warehouse.dir=/user/${USER}/warehouse // ``` // // **Using Scala** // // ``` // spark2-shell \ // --master yarn \ // --conf spark.ui.port=0 \ // --conf spark.sql.warehouse.dir=/user/${USER}/warehouse // ``` // // **Using Pyspark** // // ``` // pyspark2 \ // --master yarn \ // --conf spark.ui.port=0 \ // --conf spark.sql.warehouse.dir=/user/${USER}/warehouse // ``` // * We typically have Sub Queries in **FROM** Clause. // * We need not provide alias to the Sub Queries in **FROM** Clause in Spark SQL. In earlier versions, you might have to provide alias for the Sub Query. // * We use Sub Queries quite often over queries using Analytics/Windowing Functions // + language="sql" // // SELECT * FROM (SELECT current_date) // + language="sql" // // SELECT * FROM (SELECT current_date) AS q // - // Let us see few more examples with respect to Sub Queries. // + language="sql" // // USE itversity_retail // + language="sql" // // SELECT * FROM ( // SELECT order_date, count(1) AS order_count // FROM orders // GROUP BY order_date // ) q // LIMIT 10 // - // ```{note} // Here is an example of how we can filter based up on the derived columns using sub query. However, this can be achieved with direct query as well using `HAVING`. // ``` // + language="sql" // // SELECT * FROM ( // SELECT order_date, count(1) AS order_count // FROM orders // GROUP BY order_date // ) q // WHERE q.order_count > 10 // + language="sql" // // SELECT order_date, count(1) AS order_count // FROM orders // GROUP BY order_date // HAVING count(1) > 10
07_windowing_functions/09_overview_of_sub_queries.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## 5.4 ่ฐƒๆ•ด่กจๆ ผๆ ทๅผ # # ้€š่ฟ‡่ฐƒ็”จไธ€ไบ›ๅฎๅŒ…ๅŠๅ‘ฝไปคๅฏไปฅๅฎšๅˆถ่กจๆ ผๆ ทๅผ๏ผŒไปŽ่€Œๅˆ›ๅปบๆ›ด็ฌฆๅˆ่ฆๆฑ‚็š„่กจๆ ผใ€‚ๅฏน่กจๆ ผๆ ทๅผ็š„่ฐƒๆ•ดๅฏไปฅๅˆ†ไธบไปฅไธ‹7ไธชๆ–น้ข๏ผš่กจๆ ผๅฐบๅฏธใ€ๅ•ๅ…ƒๆ ผ่‡ชๅŠจๅฏน้ฝไธŽๆข่กŒใ€ๅฐๆ•ฐ็‚นๅฏน้ฝใ€่กŒ้ซ˜ใ€ๅˆ—ๅฎฝใ€็บฟๅฎฝใ€ไปฅๅŠ่กจๆ ผๅญ—ไฝ“ๅคงๅฐใ€‚ # # ### 5.4.1 ่กจๆ ผๅฐบๅฏธ # # ๅฆ‚ๆžœๆƒณ่ฆไฟฎๆ”น่กจๆ ผๅฐบๅฏธ๏ผŒ้ฆ–ๅ…ˆไฝฟ็”จ`\usepackage{graphicx}`่ฏญๅฅ่ฐƒ็”จ`graphicx`ๅฎๅŒ…๏ผŒๅนถไฝฟ็”จ`\resizebox{ๅฎฝๅบฆ}{้ซ˜ๅบฆ}{ๅ†…ๅฎน}`ๅ‘ฝไปค๏ผŒ่ฏฅๅ‘ฝไปคไปฅ`tabular`็Žฏๅขƒๆž„ๅปบ็š„่กจๆ ผไฝœไธบๅ†…ๅฎนใ€‚ไธบไบ†้ฟๅ…ไบง็”Ÿไธๅ่ฐƒ็š„ๅฐบๅฏธ๏ผŒๅœจ่ฎพ็ฝฎๅ‚ๆ•ฐๆ—ถๅช้œ€่ฆ่ฎพ็ฝฎ`{ๅฎฝๅบฆ}`ๅ’Œ`{้ซ˜ๅบฆ}`ไธญ็š„ๅ…ถไธญไธ€ไธชๅณๅฏ๏ผŒๅฆไธ€ไธชไปฅ`!`ไฝœไธบๅ‚ๆ•ฐ๏ผŒ่กจ็คบๆ นๆฎๅฎฝ้ซ˜ๆฏ”่ฟ›่กŒ่‡ชๅŠจ่ฐƒๆ•ดใ€‚ # # ใ€**ไพ‹5-9**ใ€‘ไฝฟ็”จ`\resizebox`ๅ‘ฝไปค่ฐƒๆ•ด่กจๆ ผๅฐบๅฏธใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{graphicx} # \begin{document} # # This is the description for the following table. This is the description for the following table. This is the description for the following table. This is the description for the following table. # # \begin{table}[h] # \centering # \caption{Title of a table.} # \label{first label} # \resizebox{0.8\textwidth}{!}{ # \begin{tabular}{|l|l|l|l|} # \hline # Column1 & Column2 & Column3 & Column4 \\ # \hline # A1 & A2 & A3 & A4 \\ # \hline # B1 & B2 & B3 & B4 \\ # \hline # C1 & C2 & C3 & C4 \\ # \hline # \end{tabular}} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.1ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_6.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.1</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.2 ๅ•ๅ…ƒๆ ผ่‡ชๅŠจๅฏน้ฝไธŽๆข่กŒ # # ไฝฟ็”จๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐ`l`ใ€`c`ๆˆ–`r`ๅฏไปฅๅฏนๆฏๅˆ—็š„ๅ•ๅ…ƒๆ ผ่ฎพ็ฝฎๅทฆๅฏน้ฝใ€ๆจชๅ‘ๅฑ…ไธญๅฏน้ฝๅ’Œๅณๅฏน้ฝ๏ผŒไฝ†็”ฑๆญคๅˆ›ๅปบ็š„ๅ•ๅ…ƒๆ ผไธไป…ๆ— ๆณ•่ฎพ็ฝฎ้กถ้ƒจๅฏน้ฝใ€็บตๅ‘ๅฑ…ไธญๅฏน้ฝใ€ไปฅๅŠๅบ•้ƒจๅฏน้ฝๆ–นๅผ๏ผŒ่€Œไธ”ๅ•ๅ…ƒๆ ผๅ†…ๅฎนไธ่ฎบ้•ฟ็Ÿญ้ƒฝ่ขซๆ‹‰้•ฟไธบไธ€่กŒ๏ผŒๆ˜พๅพ—ไธๅคŸ็ตๆดปใ€‚ไธ‹้ขไป‹็ปๅ‡ ็งๆ–นๅผ็”จไบŽๅฎž็Žฐๅ•ๅ…ƒๆ ผ่‡ชๅŠจๅฏน้ฝไธŽๆข่กŒใ€‚ # # #### ๏ผˆ1๏ผ‰ไฝฟ็”จ`array`ๅฎๅŒ…ๅฎž็Žฐๅ•ๅ…ƒๆ ผ่‡ชๅŠจๅฏน้ฝไธŽๆข่กŒ # # ้ฆ–ๅ…ˆๅœจๅฏผ่จ€ๅŒบไฝฟ็”จ`\usepackage{array}`่ฏญๅฅๅฃฐๆ˜Ž่ฐƒ็”จ`array`ๅฎๅŒ…๏ผŒ่ฏฅๅฎๅŒ…ๆไพ›ไบ†ไปฅไธ‹6ไธชๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐๅˆ†ๅˆซๅฏนๅบ”ไธๅŒ็š„ๅฏน้ฝๆ–นๅผ๏ผš # # - `p{ๅˆ—ๅฎฝ}`๏ผšๅ•ๅ…ƒๆ ผๅ†…ๅฎนๅฐ†ๆ นๆฎ่ฎพ็ฝฎ็š„ๅˆ—ๅฎฝ่‡ชๅŠจๆข่กŒ๏ผŒๅนถไธ”ๅฏน้ฝๆ–นๅผไธบ้กถ้ƒจๅฏน้ฝ๏ผ› # # - `m{ๅˆ—ๅฎฝ}`๏ผšๅ•ๅ…ƒๆ ผๅ†…ๅฎนๅฐ†ๆ นๆฎ่ฎพ็ฝฎ็š„ๅˆ—ๅฎฝ่‡ชๅŠจๆข่กŒ๏ผŒๅนถไธ”ๅฏน้ฝๆ–นๅผไธบ็บตๅ‘ๅฑ…ไธญๅฏน้ฝ๏ผ› # # - `b{ๅˆ—ๅฎฝ}`๏ผšๅ•ๅ…ƒๆ ผๅ†…ๅฎนๅฐ†ๆ นๆฎ่ฎพ็ฝฎ็š„ๅˆ—ๅฎฝ่‡ชๅŠจๆข่กŒ๏ผŒๅนถไธ”ๅฏน้ฝๆ–นๅผไธบๅบ•้ƒจๅฏน้ฝ๏ผ› # # - `>{\raggedright\arraybackslash}`๏ผšๅฐ†ไธ€ๅˆ—็š„ๅ•ๅ…ƒๆ ผๅ†…ๅฎน่ฎพ็ฝฎไธบๅทฆๅฏน้ฝ๏ผ› # # - `>{\centering\arraybackslash}`๏ผšๅฐ†ไธ€ๅˆ—็š„ๅ•ๅ…ƒๆ ผๅ†…ๅฎน่ฎพ็ฝฎไธบๆจชๅ‘ๅฑ…ไธญๅฏน้ฝ๏ผ› # # - `>{\raggedleft\arraybackslash}`๏ผšๅฐ†ไธ€ๅˆ—็š„ๅ•ๅ…ƒๆ ผๅ†…ๅฎน่ฎพ็ฝฎไธบๅณๅฏน้ฝใ€‚ # # ้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒๅฆ‚ๆžœๅ•็‹ฌไฝฟ็”จ`p`ใ€`m`ๆˆ–`b`ๅ‚ๆ•ฐ๏ผŒ้ป˜่ฎคไธบๅทฆๅฏน้ฝใ€‚ๆˆ‘ไปฌๅฏไปฅๅฏนไธŠ่ฟฐๅ‚ๆ•ฐ่ฟ›่กŒ็ป„ๅˆไฝฟ็”จ๏ผŒไปŽ่€Œ่Žทๅพ—ไธๅŒ็š„ๅฏน้ฝๆ•ˆๆžœใ€‚้œ€่ฆๆณจๆ„็š„ๆ˜ฏ๏ผŒๆญคๆ—ถๅบ”ไฝฟ็”จ`\tabularnewline`ๅ–ไปฃ`\\`็ฌฆๅทไฝœไธบ่กจๆ ผไธ€่กŒ็š„็ป“ๆŸใ€‚ # # ใ€**ไพ‹5-10**ใ€‘่ฐƒ็”จ`array`ๅฎๅŒ…ๅŠๅ…ถๆไพ›็š„ๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐๅฎž็Žฐๅ•ๅ…ƒๆ ผ่‡ชๅŠจๅฏน้ฝไธŽๅˆ†่กŒใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{array} # \begin{document} # # \begin{table}[h] # \centering # \caption{Title of a table.} # \label{first label} # \begin{tabular}{|>{\raggedright\arraybackslash}m{2.3cm}|>{\centering\arraybackslash}m{2.3cm}|>{\centering}m{2.3cm}|>{\raggedleft\arraybackslash}m{2.3cm}|} # \hline # Column1 & Column2 Column2 & Column3 Column3 Column3 & Column4 Column4 Column4 Column4 \tabularnewline # \hline # Value1 & Value2 Value2 & Value3 Value3 Value3 & Value4 Value4 Value4 Value4 \tabularnewline # \hline # Value1 & Value2 Value2 & Value3 Value3 Value3 & Value4 Value4 Value4 Value4 \tabularnewline # \hline # \end{tabular} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.2ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_7.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.2</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ้€š่ฟ‡่ฐƒ็”จ`array`ๅฎๅŒ…็š„ๆ–นๅผ่™ฝ็„ถๅฏไปฅๅฎž็Žฐ่‡ชๅŠจๆข่กŒ๏ผŒไฝ†ๅธธๅธธ้œ€่ฆ็ป่ฟ‡ๅๅค่ฏ•้ชŒๆ‰่ƒฝ่Žทๅพ—ๆƒณ่ฆ็š„ๅฎฝๅบฆ๏ผŒๆ›ดๆ–นไพฟ็š„ๆ–นๅผๆ˜ฏไฝฟ็”จ`tabularx`ๅฎๅŒ…ๆˆ–`tabulary`ๅฎๅŒ…ๅŠๅ…ถ็›ธๅ…ณๅ‘ฝไปค่‡ชๅŠจ่ฎก็ฎ—ๅˆ—ๅฎฝใ€‚ๅฏนไบŽๆถ‰ๅŠๆ–‡ๆœฌ็š„่กจๆ ผ๏ผŒๆ›ดๆŽจ่ไฝฟ็”จ`tabulary`ๅฎๅŒ…ใ€‚ไธ‹้ขๅˆ†ๅˆซไป‹็ป้€š่ฟ‡่ฟ™ไธคไธชๅฎๅŒ…ๅŠๅ…ถๅ‘ฝไปคๅฆ‚ไฝ•ๅฎž็Žฐ่‡ชๅŠจๆข่กŒใ€‚ # # #### ๏ผˆ2๏ผ‰ไฝฟ็”จ`tabularx`ๅฎๅŒ…ๅฎž็Žฐ่‡ชๅŠจๆข่กŒ # # ้ฆ–ๅ…ˆๅœจๅฏผ่จ€ๅŒบๅฃฐๆ˜Ž่ฐƒ็”จ`tabularx`ๅฎๅŒ…๏ผŒ็„ถๅŽไฝฟ็”จ`\begin{tabularx} \end{tabularx}`็Žฏๅขƒๅ–ไปฃ`\begin{tabular} \end{tabular}`็Žฏๅขƒๅˆ›ๅปบ่กจๆ ผๅ†…ๅฎน๏ผŒ`tabularx`็Žฏๅขƒ็š„ไฝฟ็”จๆ–นๅผไธŽ`tabular`็ฑปไผผ๏ผŒไธๅŒไน‹ๅค„ไธป่ฆๅœจไบŽ๏ผš`\begin{tabularx}{่กจๆ ผๅฎฝๅบฆ}{ๅˆ—็ฑปๅž‹}`ไธญๅบ”่ฎพ็ฝฎ่กจๆ ผๅฎฝๅบฆ๏ผ›ๅœจ`tabularx`็Žฏๅขƒไธญ๏ผŒๅฏนไบŽ้œ€่ฆ่‡ชๅŠจๆข่กŒ็š„ๅˆ—๏ผŒๅ…ถๅˆ—็ฑปๅž‹ๅบ”่ฎพ็ฝฎไธบๅคงๅ†™็š„`X`ใ€‚`X`ๅ‚ๆ•ฐๅฏไปฅไธŽ`>{\raggedright\arraybackslash}`ใ€`>{\centering\arraybackslash}`ๆˆ–`>{\raggedleft\arraybackslash}`่ฟ›่กŒ็ป„ๅˆไฝฟ็”จ๏ผŒไปŽ่€Œไฟฎๆ”นๅ•ๅ…ƒๆ ผ็š„ๅฏน้ฝๆ–นๅผใ€‚ # # ใ€**ไพ‹5-11**ใ€‘่ฐƒ็”จ`tabularx`ๅฎๅŒ…ๅนถ่ฎพ็ฝฎๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐ`X`ไปŽ่€Œๅฎž็Žฐๅ•ๅ…ƒๆ ผๅ†…ๅฎน่‡ชๅŠจๆข่กŒใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{array} # \usepackage{tabularx} % ่ฐƒ็”จtabularxๅฎๅŒ… # \begin{document} # # \begin{table}[h] # \centering # \caption{Title of a table.} # \label{first label} # \begin{tabularx}{\linewidth}{|X|X|X|>{\centering\arraybackslash}X|} % ๅฐ†้œ€่ฆ่‡ชๅŠจๆข่กŒ็š„ๅˆ—็š„ๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐ่ฎพไธบX # \hline # Column1 & Column2 & Column3 & Column4 \\ # \hline # This is Value1. This is Value1. & This is Value2. This is Value2. & This is Value3. This is Value3. & This is Value4. This is Value4. \\ # \hline # This is Value1. This is Value1. This is Value1. & This is Value2. This is Value2. This is Value2. & This is Value3. This is Value3. This is Value3. & This is Value4. This is Value4. This is Value4. \\ # \hline # \end{tabularx} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.3ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_8.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.3</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # #### ๏ผˆ3๏ผ‰ไฝฟ็”จ`tabulary`ๅฎๅŒ…ๅฎž็Žฐ่‡ชๅŠจๆข่กŒ # # ็ฑปไผผๅœฐ๏ผŒ่ฐƒ็”จ`tabulary`ๅฎๅŒ…ๅนถไฝฟ็”จ`\begin{tabulary}{่กจๆ ผๅฎฝๅบฆ}{ๅˆ—็ฑปๅž‹} \end{tabulary}`็Žฏๅขƒๅˆ›ๅปบ่กจๆ ผใ€‚ๅฏนไบŽ้œ€่ฆ่‡ชๅŠจๆข่กŒ็š„ๅˆ—๏ผŒๅช้œ€ๅฐ†ๅˆ—็ฑปๅž‹ๆ”นไธบๅคงๅ†™ๅญ—ๆฏๅณๅฏ๏ผŒๅณ๏ผŒๅคงๅ†™`L`่กจ็คบๅทฆๅฏน้ฝๅนถ่‡ชๅŠจๆข่กŒใ€ๅคงๅ†™`C`่กจ็คบๅฑ…ไธญๅฏน้ฝๅนถ่‡ชๅŠจๆข่กŒใ€ๅคงๅ†™`R`่กจ็คบๅณๅฏน้ฝๅนถ่‡ชๅŠจๆข่กŒใ€‚ # # ใ€**ไพ‹5-12**ใ€‘่ฐƒ็”จ`tabulary`ๅฎๅŒ…ๅนถ่ฎพ็ฝฎๅคงๅ†™ๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐ๏ผˆ`L`ใ€`C`ๅ’Œ`R`๏ผ‰ไปŽ่€Œๅฎž็Žฐๅ•ๅ…ƒๆ ผๅ†…ๅฎน่‡ชๅŠจๆข่กŒใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{array} # \usepackage{tabulary} % ่ฐƒ็”จtabularyๅฎๅŒ… # \begin{document} # # \begin{table}[h] # \centering # \caption{Title of a table.} # \label{first label} # \begin{tabulary}{\linewidth}{|L|C|C|R|} % ๅฐ†้œ€่ฆ่‡ชๅŠจๆข่กŒ็š„ๅˆ—็š„ๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐๆ”นไธบๅคงๅ†™ # \hline # Column1 & Column2 & Column3 & Column4 \\ # \hline # This is Value1. This is Value1. & This is Value2. This is Value2. & This is Value3. This is Value3. & This is Value4. This is Value4. \\ # \hline # This is Value1. This is Value1. This is Value1. & This is Value2. This is Value2. This is Value2. & This is Value3. This is Value3. This is Value3. & This is Value4. This is Value4. This is Value4. \\ # \hline # \end{tabulary} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.4ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_9.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.4</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # #### ๏ผˆ4๏ผ‰ไฝฟ็”จ`\parbox`ๅ‘ฝไปคๅฎž็Žฐไบบๅทฅๆข่กŒ # # ๆˆ‘ไปฌไนŸๅฏไปฅ้€š่ฟ‡ไฝฟ็”จ`\parbox`ๅ‘ฝไปคๅฏน่กจๆ ผๅ†…ๅฎน่ฟ›่กŒๅผบๅˆถๆข่กŒ๏ผš # # ใ€**ไพ‹5-13**ใ€‘็”จ`\parbox`ๅ‘ฝไปคๆฅๅฎž็Žฐๅ•ๅ…ƒๆ ผไธญๆ–‡ๆœฌๅผบๅˆถๆข่กŒใ€‚ # # ```tex # \documentclass{article} # \begin{document} # \begin{center} # \begin{tabular}{|c|c|c|c|} # \hline # a & b & c & d \\ # \hline # a & b & c & \parbox[t]{5cm}{In probability theory and statistics, the continuous uniform distribution\\ or rectangular distribution is a family of symmetric probability distributions.} \\ # \hline # \end{tabular} # \end{center} # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.5ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/example_sec2_6.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.5</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.3 ๅฐๆ•ฐ็‚นๅฏน้ฝ # # ไธบไบ†ๆ›ดๅฅฝๅœฐๆ่ฟฐๆ•ฐๆฎ๏ผŒๅœจ่กจๆ ผไธญๅธธๅธธๅฐ†ๆ•ฐๆฎๅœจๅฐๆ•ฐ็‚นๅค„่ฟ›่กŒๅฏน้ฝ๏ผŒๅœจLaTeXไธญๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ไฝฟ็”จ`dcolumn`ๅŒ…ๅฎž็Žฐ่ฟ™ไธ€็›ฎ็š„ใ€‚่ฟ™ไธชๅŒ…ๆไพ›ไบ†ไธ€ไธชๅไธบ`D`็š„ๅˆ—็ฑปๅž‹๏ผŒๅฏไปฅๆ–นไพฟๅฎž็ŽฐๅŸบไบŽๅฐๆ•ฐ็‚น็š„ๆ•ฐๅญ—ๅฏน้ฝไปฅๅŠๅŸบไบŽๅ…ถๅฎƒ็ฌฆๅท็š„ๅฏน้ฝ๏ผŒไฝฟ็”จๆ–นๅผไธบ`D{่พ“ๅ…ฅ็ฌฆๅท}{่พ“ๅ‡บ็ฌฆๅท}{็ฌฆๅทๅŽ็š„ๆ•ฐๅญ—ไฝๆ•ฐ}`ใ€‚ๅฏนไบŽๅŸบไบŽๅฐๆ•ฐ็‚น็š„ๆ•ฐๅญ—ๅฏน้ฝ๏ผŒ่พ“ๅ…ฅ็ฌฆๅทไธ€่ˆฌไธบโ€œ.โ€๏ผ›ๆœ‰ๆ—ถ้œ€่ฆๆ นๆฎ็‰นๅฎš็ฌฆๅท่ฟ›่กŒๆ•ฐๅญ—ๅฏน้ฝ๏ผŒๆฏ”ๅฆ‚ๅƒๅˆ†ไฝ้€—ๅท๏ผŒ่ฟ™ๆ—ถ่พ“ๅ…ฅ็ฌฆๅทๅณไธบโ€œ,โ€ใ€‚ไพ‹ๅฆ‚๏ผŒ`D{.}{\cdot}{2}`่กจ็คบๅฐ†ๆŸๅˆ—็š„ๆ•ฐๆฎๆ นๆฎโ€œ.โ€็ฌฆๅทๅฏน้ฝ๏ผŒ่พ“ๅ‡บๆ—ถๅฐ†่ฏฅ็ฌฆๅทๆ˜พ็คบไธบ็‚นไน˜็ฌฆๅท๏ผŒๅนถไธ”ๆ˜พ็คบ2ไธชๅฐๆ•ฐไฝๆ•ฐใ€‚ # # ๅˆ—็ฑปๅž‹`D`ๅฏไปฅๅƒๅ…ถๅฎƒๅˆ—็ฑปๅž‹ไธ€ๆ ทๅœจ่กจๆ ผ็Žฏๅขƒ็š„ๅผ€ๅง‹ๅ‘ฝไปคๅค„็›ดๆŽฅ่ฟ›่กŒ่ฎพ็ฝฎ๏ผŒไฝ†ไผšๅฏผ่‡ด่ฏญๅฅ่ฟ‡้•ฟ๏ผŒๆ‰€ไปฅไธ€่ˆฌไฝฟ็”จ`array`ๅฎๅŒ…็š„`\newcolumntype`ๅ‘ฝไปคๅฎšไน‰ไธ€ไธชๆ–ฐ็š„ๅˆ—็ฑปๅž‹๏ผŒๅนถไธบ่ฟ™ไธชๅˆ—็ฑปๅž‹่ต‹ไบˆไธ€ไธชๆฏ”่พƒ็Ÿญ็š„ๅ็งฐไปฅๆ–นไพฟ่ฐƒ็”จใ€‚ๅฎšไน‰ๆ–ฐ็š„ๅˆ—็ฑปๅž‹็š„่ฏญๅฅไธบ`\newcolumntype{ๆ–ฐๅˆ—็ฑปๅž‹ๅ็งฐ}[ๆ–ฐๅˆ—็ฑปๅž‹็š„ๅ‚ๆ•ฐไธชๆ•ฐ]{ๅฎšไน‰ๆ–ฐๅˆ—็ฑปๅž‹}`๏ผŒไพ‹ๅฆ‚๏ผš`\newcolumntype{d}[1]{D{.}{\cdot}{#1}}`่กจ็คบๅˆ›ๅปบไธ€ไธชๅไธบ`d`็š„ๆ–ฐๅˆ—็ฑปๅž‹๏ผŒ่ฏฅๅˆ—็ฑปๅž‹็š„ๅ†…ๅฎนไธบ`D{.}{\cdot}{็ฌฆๅทๅŽ็š„ๆ•ฐๅญ—ไฝๆ•ฐ}`๏ผŒๅ…ถไธญๆ•ฐๅญ—ไฝๆ•ฐๆ˜ฏไผ ็ป™`d`็š„ๅ‚ๆ•ฐใ€‚ # # ใ€**ไพ‹5-14**ใ€‘่ฐƒ็”จ`dcolumn`ๅฎๅŒ…ๅ’Œๅˆ—็ฑปๅž‹`D`ๆฅๅฎž็Žฐ่กจๆ ผๆ•ฐๆฎ็š„ๅฐๆ•ฐ็‚นๅฏน้ฝใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{dcolumn} # \newcolumntype{d}[1]{D{.}{\cdot}{#1}} # \begin{document} # \begin{tabular}{|l|c|r|d{3}|} # \hline # Left & Center & Right & \mathrm{Decimal}\\ # \hline # 1.1 & 1.1 & 1.1 & 1.1\\ # \hline # 33.3 & 33.3 & 33.3 & 33.3\\ # \hline # 3.333 & 3.333 & 3.333 & 3.333\\ # \hline # \end{tabular} # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.6ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/eg5_10.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.6</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.4 ่กŒ้ซ˜ # # ๅฆ‚ๆžœ้œ€่ฆ่ฐƒๆ•ด่กจๆ ผๆ•ดไฝ“่กŒ้ซ˜๏ผŒๅฏไปฅๅœจๅฏผ่จ€ๅŒบไฝฟ็”จ`\renewcommand{\arraystretch}{่กŒ้ซ˜ๅ€ๆ•ฐ}`ๅ‘ฝไปค๏ผŒไปŽ่€Œๆ นๆฎ่ฎพ็ฝฎ็š„่กŒ้ซ˜ๅ€ๆ•ฐๅœจ้ป˜่ฎคๅ€ผ็š„ๅŸบ็ก€ไธŠๅฏน่กŒ้ซ˜่ฟ›่กŒๆ‰ฉๅคงๆˆ–็ผฉๅฐใ€‚ # # ใ€**ไพ‹5-15**ใ€‘ไฝฟ็”จ`\renewcommand{\arraystretch}{2}`ๅ‘ฝไปคๅฐ†่กจๆ ผๆ•ดไฝ“่กŒ้ซ˜่ฎพไธบไธคๅ€่กŒ่ทใ€‚ # # ```tex # \documentclass[12pt]{article} # \renewcommand{\arraystretch}{2} # \begin{document} # # \begin{tabular}{|c|c|c|c|} # \hline # Column1 & Column2 & Column3 & Column4\\ # \hline # A1 & A2 & A3 & A4\\ # \hline # B1 & B2 & B3 & B4\\ # \hline # C1 & C2 & C3 & C4\\ # \hline # \end{tabular} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.7ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/eg5_15new.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.7</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ๅฆไธ€็ง่ฐƒๆ•ด่กŒ้ซ˜็š„ๆ–นๅผๆ˜ฏ้€š่ฟ‡ๅœจๆฏ่กŒ็š„็ป“ๆŸๆ ‡ๅฟ—`\\`ๅŽๅŠ ไธŠ่กŒ้ซ˜ๅขžๅ‡้‡้€‰้กน๏ผŒๅณ`\\[่กŒ้ซ˜ๅขžๅ‡้‡]`๏ผŒไปŽ่€Œๅœจ้ป˜่ฎคๅ€ผ็š„ๅŸบ็ก€ไธŠๅฏนๅ„่กŒ่กŒ้ซ˜่ฟ›่กŒๅขžๅ‡ใ€‚ # # ใ€**ไพ‹5-16**ใ€‘ไฝฟ็”จ`\\[่กŒ้ซ˜ๅขžๅ‡้‡]`ๅ‘ฝไปคไธบ่กจๆ ผๅ„่กŒ่ฎพ็ฝฎไธๅŒ็š„่กŒ้ซ˜ใ€‚ # # ```tex # \documentclass[12pt]{article} # \begin{document} # # \begin{tabular}{|c|c|c|c|} # \hline # Column1 & Column2 & Column3 & Column4\\[0cm] # \hline # A1 & A2 & A3 & A4\\[0.2cm] # \hline # B1 & B2 & B3 & B4\\[0.4cm] # \hline # C1 & C2 & C3 & C4\\[0.6cm] # \hline # \end{tabular} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.8ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/eg5_16new.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.8</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.5 ๅˆ—ๅฎฝ # # ๅœจ5.4.2่Š‚ไธญ๏ผŒๆˆ‘ไปฌไป‹็ปไบ†ไฝฟ็”จ`array`ๅฎๅŒ…ๆไพ›็š„ๅˆ—็ฑปๅž‹ๅ‚ๆ•ฐๅฏไปฅๅœจ่ฎพ็ฝฎๅ•ๅ…ƒๆ ผๅฏน้ฝๆ–นๅผ็š„ๅŒๆ—ถๅฏนๅˆ—ๅฎฝ่ฟ›่กŒ่ฐƒๆ•ดใ€‚ๆญคๅค–๏ผŒไนŸๅฏไปฅๅœจๅฏผ่จ€ๅŒบไฝฟ็”จ`\setlength{\tabcolsep}{ๆ–‡ๆœฌๅ’Œๅˆ—ๅˆ†้š”็บฟ็š„้—ด่ท}`ๅ‘ฝไปคไฟฎๆ”น่กจๆ ผๅˆ—ๅฎฝ๏ผŒ้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒๅ•ๅ…ƒๆ ผๅ†…ๅฎนไธŽๅˆ—ๅˆ†้š”็บฟ็š„้—ด่ทไธบ6ptใ€‚ # # ใ€**ไพ‹5-17**ใ€‘ไฝฟ็”จ`\setlength{\tabcolsep}{12pt}`ๅ‘ฝไปคๅฐ†่กจๆ ผๅ•ๅ…ƒๆ ผๆ–‡ๆœฌๅ’Œๅˆ—ๅˆ†้š”็บฟ็š„้—ด่ท่ฎพไธบ12ptใ€‚ # # ```tex # \documentclass[12pt]{article} # \setlength{\tabcolsep}{12pt} # \begin{document} # # \begin{tabular}{|c|c|c|c|} # \hline # Column1 & Column2 & Column3 & Column4\\ # \hline # A1 & A2 & A3 & A4\\ # \hline # B1 & B2 & B3 & B4\\ # \hline # C1 & C2 & C3 & C4\\ # \hline # \end{tabular} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.9ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/eg5_17.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.9</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # # ```tex # \documentclass[12pt]{article} # \usepackage{tabularx} # \begin{document} # # \begin{table} # \centering # \begin{tabularx}{\textwidth}{|p{3cm}|p{3cm}|p{3cm}|p{3cm}|} # \hline # Column1 & Column2 & Column3 & Column4\\ # \hline # A1 & A2 & A3 & A4\\ # \hline # B1 & B2 & B3 & B4\\ # \hline # C1 & C2 & C3 & C4\\ # \hline # \end{tabularx} # \label{table1} # \end{table} # # \end{document} # ``` # # # ### 5.4.6 ็บฟๅฎฝ # # ้€š่ฟ‡ๅœจๅฏผ่จ€ๅŒบไฝฟ็”จ`\setlength{\arrayrulewidth}{็บฟๅฎฝ}`ๅ‘ฝไปค๏ผŒๅฏไปฅไฟฎๆ”น่กจๆ ผ็บฟๅฎฝ๏ผŒ้ป˜่ฎคไธบ0.4ptใ€‚็„ถ่€Œๅฝ“็บฟๅฎฝ่ฎพ็ฝฎ่ฟ‡ๅคงๆ—ถ๏ผŒๅฏ่ƒฝๅฏผ่‡ด่กจๆ ผ็บฟไบคๅ‰ๅค„ไธ่ฟž็ปญ็š„ๆƒ…ๅ†ตใ€‚ๅฏนๆญค๏ผŒๅœจๅฏผ่จ€ๅŒบ่ฐƒ็”จ`xcolor`ๅฎๅŒ…ใ€ๅนถ่ฎพ็ฝฎ`table`้€‰้กนๅฏไปฅ่งฃๅ†ณใ€‚ # # ใ€**ไพ‹5-18**ใ€‘ๅœจๅฏผ่จ€ๅŒบไฝฟ็”จ`\usepackage[table]{xcolor}`ๅ‘ฝไปค่ฐƒ็”จ่ฎพ็ฝฎไบ†`table`้€‰้กน็š„`xcolor`ๅฎๅŒ…๏ผŒๅนถไฝฟ็”จ`\setlength{\arrayrulewidth}{็บฟๅฎฝ}`ๅ‘ฝไปค่ฎพ็ฝฎ่กจๆ ผ็บฟๅฎฝใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage[table]{xcolor} % ่ฐƒ็”จ่ฎพ็ฝฎไบ†table้€‰้กน็š„xcolorๅฎๅŒ… # \setlength{\arrayrulewidth}{2pt} % ไฟฎๆ”น่กจๆ ผ็บฟๅฎฝ # \begin{document} # # \begin{tabular}{|l|l|l|l|} # \hline # Column1 & Column2 & Column3 & Column4\\ # \hline # A1 & A2 & A3 & A4\\ # \hline # B1 & B2 & B3 & B4\\ # \hline # C1 & C2 & C3 & C4\\ # \hline # \end{tabular} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.10ๆ‰€็คบใ€‚ # <p align="center"> # <img align="middle" src="graphics/eg5_11.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.10</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.7 ่กจๆ ผๅญ—ไฝ“ๅคงๅฐ # # ๅœจๆ–‡ๆœฌ็ผ–่พ‘ไธญๆˆ‘ไปฌ็Ÿฅ้“๏ผŒ่ฐƒๆ•ดๅญ—ไฝ“ๅคงๅฐ็š„ๆ–นๅผๆ—ขๆœ‰ๅ…จๅฑ€ๆ–นๅผไนŸๆœ‰ๅฑ€้ƒจๆ–นๅผ๏ผŒๅ…ถไธญ๏ผŒๅ…จๅฑ€ๆ–นๅผๆ˜ฏ้€š่ฟ‡ๅœจๆ–‡ๆกฃ็ฑปๅž‹ไธญๆŒ‡ๅฎšๅญ—ไฝ“ๅคงๅฐ๏ผŒไพ‹ๅฆ‚`\documentclass[12pt]{article}`๏ผŒ่€Œๅฑ€้ƒจๆ–นๅผๅˆ™ๆ˜ฏ้€š่ฟ‡ไธ€็ณปๅˆ—่ฎพ็ฝฎๅญ—ไฝ“ๅคงๅฐ็š„ๅ‘ฝไปค๏ผŒไพ‹ๅฆ‚`\large`ใ€`Large`ใ€`huge`ใ€`\fontsize`็ญ‰๏ผŒๅœจๅ…จๅฑ€ๅญ—ไฝ“ๅคงๅฐ็š„ๅŸบ็ก€ไธŠไฝœ่ฟ›ไธ€ๆญฅ็š„่ฐƒๆ•ดใ€‚็ฑปไผผๅœฐ๏ผŒๅœจไฝฟ็”จLaTeXๅˆ›ๅปบ่กจๆ ผๆ—ถ๏ผŒๆˆ‘ไปฌไนŸๅฏไปฅๅฏน่กจๆ ผๅญ—ไฝ“ๅคงๅฐๅšๅ…จๅฑ€ๆˆ–ๅฑ€้ƒจ่ฐƒๆ•ดใ€‚ # # ใ€**ไพ‹5-19**ใ€‘ไฝฟ็”จ`\Large`ๅ‘ฝไปค่ฐƒๆ•ด่กจๆ ผๅฑ€้ƒจๅญ—ไฝ“ๅคงๅฐใ€‚ # # ```tex # \documentclass[12pt]{article} # \begin{document} # # % ๆญฃๅธธๅญ—ไฝ“ๅคงๅฐ # \begin{table}[htp] # \centering # \begin{tabular}{l|cccr} # \hline # & $x=1$ & $x=2$ & $x=3$ & $x=4$ \\ # \hline # $y=x$ & 1 & 2 & 3 & 4 \\ # $y=x^{2}$ & 1 & 4 & 9 & 16 \\ # $y=x^{3}$ & 1 & 8 & 27 & 64 \\ # \hline # \end{tabular} # \end{table} # # % Largeๅญ—ไฝ“ๅคงๅฐ # \begin{table}[htp] # \Large # \centering # \begin{tabular}{l|cccr} # \hline # & $x=1$ & $x=2$ & $x=3$ & $x=4$ \\ # \hline # $y=x$ & 1 & 2 & 3 & 4 \\ # $y=x^{2}$ & 1 & 4 & 9 & 16 \\ # $y=x^{3}$ & 1 & 8 & 27 & 64 \\ # \hline # \end{tabular} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.11ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_28.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.11</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ใ€**ไพ‹5-20**ใ€‘ไฝฟ็”จ`\fontsize`ๅ‘ฝไปค้€š่ฟ‡ๅ…ทไฝ“่ฎพ็ฝฎๆฅ่ฐƒๆ•ด่กจๆ ผๅฑ€้ƒจๅญ—ไฝ“ๅคงๅฐใ€‚ # # ```tex # \documentclass[12pt]{article} # \begin{document} # # % ๆญฃๅธธๅญ—ไฝ“ๅคงๅฐ # \begin{table}[htp] # \centering # \begin{tabular}{l|cccr} # \hline # & $x=1$ & $x=2$ & $x=3$ & $x=4$ \\ # \hline # $y=x$ & 1 & 2 & 3 & 4 \\ # $y=x^{2}$ & 1 & 4 & 9 & 16 \\ # $y=x^{3}$ & 1 & 8 & 27 & 64 \\ # \hline # \end{tabular} # \end{table} # # % ๅฐ†ๅญ—ไฝ“ๅคงๅฐ่ฎพไธบ18ptใ€่กŒ่ท่ฎพไธบ24pt # \begin{table}[htp] # \fontsize{18pt}{24pt}\selectfont # \centering # \begin{tabular}{l|cccr} # \hline # & $x=1$ & $x=2$ & $x=3$ & $x=4$ \\ # \hline # $y=x$ & 1 & 2 & 3 & 4 \\ # $y=x^{2}$ & 1 & 4 & 9 & 16 \\ # $y=x^{3}$ & 1 & 8 & 27 & 64 \\ # \hline # \end{tabular} # \end{table} # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.12ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_29.png" width="350" /> # </p> # # <center><b>ๅ›พ5.4.12</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ### 5.4.8 ๆ–‡ๅญ—็Žฏ็ป•่กจๆ ผ # # ๅฆ‚ๆžœๆƒณ่ฆๅฎž็Žฐๆ–‡ๅญ—็Žฏ็ป•่กจๆ ผๆ•ˆๆžœ๏ผŒๅฏไปฅไฝฟ็”จ`wrapfig`ๅฎๅŒ…๏ผŒๅนถไฝฟ็”จๅ…ถๆไพ›็š„`wraptable`็ŽฏๅขƒๅตŒๅฅ—`tabular`็Žฏๅขƒๅˆ›ๅปบ่กจๆ ผ๏ผŒไปŽ่€Œ่พพๅˆฐๆ–‡ๅญ—็Žฏ็ป•่กจๆ ผ็š„ๆ•ˆๆžœใ€‚ # # ใ€**ไพ‹5-21**ใ€‘ไฝฟ็”จ`wraptable`็ŽฏๅขƒๅตŒๅฅ—`tabular`็Žฏๅขƒๅˆ›ๅปบ่กจๆ ผ๏ผŒๅฎž็Žฐๆ–‡ๅญ—็Žฏ็ป•่กจๆ ผ๏ผ›ๅนถไฝฟ็”จ`\begin{wraptable}{r}{8cm}`ๅฐ†่กจๆ ผ็ฝฎไบŽๆ–‡ๅญ—ๅณไพง๏ผŒๅŒๆ—ถๅฐ†่กจๆ ผๅ’Œๆ–‡ๅญ—็š„่ท็ฆป่ฎพไธบ8cmใ€‚ # # ```tex # \documentclass[12pt]{article} # \usepackage{wrapfig} # \begin{document} # # In descriptive statistics, a box plot or boxplot is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending from the boxes (whiskers) indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot and box-and-whisker diagram. Outliers may be plotted as individual points. Box plots are non-parametric: they display variation in samples of a statistical population without making any assumptions of the underlying statistical distribution (though Tukey's boxplot assumes symmetry for the whiskers and normality for their length). # # \begin{wraptable}{r}{8cm} # \centering # # \begin{tabular}{lcccc} # \hline # & $x=1$ & $x=2$ & $x=3$ & $x=4$ \\ # \hline # $y=x$ &\multicolumn{1}{c}{1} & 2 & 3 & 4 \\ # $y=x^{2}$ & 1 & \multicolumn{1}{c}{4} & 9 & 16 \\ # $y=x^{3}$ & 1 & 8 & \multicolumn{1}{c}{27} & 64 \\ # \hline # \end{tabular} # # \end{wraptable} # The spacings between the different parts of the box indicate the degree of dispersion (spread) and skewness in the data, and show outliers. In addition to the points themselves, they allow one to visually estimate various L-estimators, notably the interquartile range, midhinge, range, mid-range, and trimean. Box plots can be drawn either horizontally or vertically. Box plots received their name from the box in the middle, and from the plot that they are. # # \end{document} # ``` # # ็ผ–่ฏ‘ไธŠ่ฟฐไปฃ็ ๏ผŒๅพ—ๅˆฐ่กจๆ ผๅฆ‚ๅ›พ5.4.13ๆ‰€็คบใ€‚ # # <p align="center"> # <img align="middle" src="graphics/eg5_30.png" width="550" /> # </p> # # <center><b>ๅ›พ5.4.13</b> ็ผ–่ฏ‘ๅŽ็š„ๆ–‡ๆกฃๅ†…ๅฎน</center> # # ใ€ๅ›žๆ”พใ€‘[**5.3 ๆ’ๅ…ฅๆ–œ็บฟไธŽ่กจๆณจ**](https://nbviewer.jupyter.org/github/xinychen/latex-cookbook/blob/main/chapter-5/section3.ipynb) # # ใ€็ปง็ปญใ€‘[**5.5 ๅˆ›ๅปบๅฝฉ่‰ฒ่กจๆ ผ**](https://nbviewer.jupyter.org/github/xinychen/latex-cookbook/blob/main/chapter-5/section5.ipynb) # ### License # # <div class="alert alert-block alert-danger"> # <b>This work is released under the MIT license.</b> # </div>
chapter-5/section4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline # + [markdown] lang="es" # # *Hubble y los orรญgenes de DESI* # + [markdown] lang="es" # ยกEl aรฑo 1929 nos trajo los Oscar, la primera radio de coche y la inesperada observaciรณn de <NAME> de que todas las galaxias se estรกn alejando de nosotros! # - # ![title](images/edwin-hubble.jpg) # + [markdown] lang="es" # Echemos un vistazo rรกpido a algunas de las galaxias que estaba viendo, Triรกngulo y la Gran Nube de Magallanes. # - # ![title](images/Triangulum.jpg) # ![title](images/LMC.jpg) # + [markdown] lang="es" # En total, Edwin estudiรณ la distancia de nosotros a 24 galaxias, y sus 'desplazamientos al rojo' observados. ยฟQuรฉ significa eso? # + [markdown] lang="es" # Tal vez ya sepas que los niveles de energรญa del hidrรณgeno estรกn __cuantificados__, con electrones que habitan una serie de capas con __energรญas__ discretas. Cuando un electrรณn transita de un nivel de mayor energรญa a otro de menor, se emite luz con una longitud de onda dada especรญficamente por la fรณrmula de "Rydberg": # # $$\lambda_{\rm vac} = 1.096 \times 10^{7} \left ( \frac{1}{n^2} - \frac{1}{m^2} \right ) $$ # # donde $n$ y $m$ (cualquiera de $[0, 1, 2, ... \infty]$) etiquetan los dos niveles de energรญa. # + # Primero, importemos algunos paquetes รบtiles : import astropy import pylab as pl import pandas as pd import numpy as np from matplotlib import pyplot as plt from scipy import stats from IPython.display import Image from tools.wave2rgb import wavelength_to_rgb # - def Rydberg(n, m): # Longitud de onda [nanometros] result = 1.096e-2 * (1. / n / n - 1. / m / m) return 1. / result # + [markdown] lang="es" # Veamos quรฉ longitudes de onda de la luz que puede emitir el hidrรณgeno: # + waves = [] print('n \t m \t Wavelength [nm]') for n in np.arange(1, 10, 1): for m in np.arange(n+1, 10, 1): wave = Rydberg(n, m) waves.append(wave) print('{:d} \t {:d} \t {:.3f}'.format(n, m, wave)) # + [markdown] lang="es" # Ahora grafiquemos las longitudes de onda y veamos el color de estas lรญneas. Si tuviรฉramos que mirar un รกtomo de hidrรณgeno emisor, verรญamos esto: # + for wave in waves: # color = [r, g, b] color = wavelength_to_rgb(wave) pl.axvline(x=wave, c=color) pl.xlabel('Vacuum wavelength [nanometers]') pl.xlim(380., 780.) # + [markdown] lang="es" # Si existe hidrรณgeno en una galaxia que se estรก moviendo, vemos que las lรญneas se desplazan por efecto Doppler. Digamos que la galaxia se mueve al 1% de la velocidad de la luz. # - def redshift(v): # v [speed of light]. result = (1. + v) / (1. - v) result = np.sqrt(result) - 1. return result # + zz = redshift(0.01) for restwave in waves: obswave = (1. + zz) * restwave color = wavelength_to_rgb(restwave) pl.axvline(x=restwave, c=color, alpha=0.25) color = wavelength_to_rgb(obswave) pl.axvline(x=obswave, c=color) pl.xlabel('Vacuum wavelength [nanometers]') pl.xlim(380., 780.) # + [markdown] lang="es" # Aquรญ puedes ver la lรญnea original (tenue) y la lรญnea desplazada debido a que la galaxia con el hidrรณgeno emisor se estรก moviendo. https://es.wikipedia.org/wiki/Efecto_Doppler te darรก todos los detalles. # + [markdown] lang="es" # Hubble conocรญa las lรญneas del hidrรณgeno y muchos otros elementos. Al invertir lo anterior, pudo calcular la velocidad de muchas galaxias. Descubriรณ quรฉ tan lejos estaban (usando la informaciรณn de quรฉ tan brillantes eran algunas estrellas especiales en la galaxia - https://es.wikipedia.org/wiki/Estrella_variable_Cefeida) y quรฉ tan rรกpido se estaban moviendo (a partir de su desplazamiento al rojo, ver arriba): # - dat = pd.read_csv('dat/hubble.dat', sep='\s+', comment='#', names=['Galaxy name', 'Distance [Mpc]', 'Velocity [km/s]']) dat # + [markdown] lang="es" # Vamos a graficarlas. # - fig = plt.figure(figsize=(10, 7.5)) ax = fig.add_subplot(1, 1, 1) plt.close() label_style = {'fontname': 'Georgia', 'fontsize': 16} # + ax.plot(dat['Distance [Mpc]'], dat['Velocity [km/s]'], '-', c='k', marker='*', lw=0) ax.set_xlabel('Distancia desde Nosotros [Megaparsecs]', **label_style) ax.set_ylabel('Velocida de Recesiรณn [km/s]', **label_style) plt.tight_layout() # - fig # + [markdown] lang="es" # Edwin vio una tendencia clara, pero las mediciones parecรญan bastante ruidosas. Intentemos hacer nuestra mejor suposiciรณn sobre la verdadera relaciรณn entre los dos. Construiremos una relaciรณn lineal (regresiรณn) usando el paquete scipy stats: # - slope, intercept, r_value, p_value, std_err = stats.linregress(dat['Distance [Mpc]'],dat['Velocity [km/s]']) print('La pendiente de esta tendencia (slope) es conocida como la constante de Hubble: {:.3f} [km/s/Mpc]'.format(slope)) # + [markdown] lang="es" # ยฟCรณmo se ve esto?. # + distances = np.linspace(-0.5, 2.5, 10) velocities = slope * distances ax.plot(distances, velocities, lw=0.25, c='k') ax.set_xlim(0.0, 2.5) # - fig # + [markdown] lang="es" # ยกParece un ajuste bastante bueno! # + [markdown] lang="es" # Ahora es tu turno, ยฟpuedes hacer una buena estimaciรณn del error en esta mediciรณn de la constante del Hubble? ยฟCon quรฉ precisiรณn podemos predecir la recesiรณn de una galaxia a una distancia determinada, es decir, quรฉ tan rรกpido o lento podrรญa moverse? # + [markdown] lang="es" # Entonces, en conclusiรณn, ยกes probable que todas las galaxias se alejen de nosotros! Descubrimos que esto es cierto para todas las galaxias: no estamos en el centro ni somos especiales de ninguna manera. Cada galaxia se aleja de las demรกs. El hecho de que el Universo se estuviera expandiendo fue un shock para muchos en 1929, pero les esperaba una sorpresa aรบn mayor. # + [markdown] lang="es" # # *Energรญa oscura* # + [markdown] lang="es" # En 1998, el mundo cambiarรญa para siempre. <NAME> y <NAME> fundaron Google, el nodo American Unity y el mรณdulo ruso Zarya se unirรญan para formar la [Estaciรณn Espacial Internacional] (https://es.wikipedia.org/wiki/Estaciรณn_Espacial_Internacional ) y <NAME> (del laboratorio Lawrence Berkeley), <NAME> y <NAME>, confirmaron irrefutablemente la existencia de la _Energรญa Oscura_ (_Dark Energy_). Aquรญ estรก Saul impresionando a algunos jรณvenes investigadores de Berkeley con estos resultados en ese momento: # - # ![title](images/perlmutter.png) # + [markdown] lang="es" # Entonces, ยฟquรฉ estaban mirando todos? Analicemos los datos. # - dat = pd.read_csv('dat/perlmutter.txt', names=['z', 'Effective magnitude'], comment='#', sep='\s+') toprint = dat[:10] toprint # + [markdown] lang="es" # Un grรกfico mostrarรญa esto mucho mรกs claramente: # + pl.plot(dat['z'], dat['Effective magnitude'], marker='.', lw=0.0) pl.xlabel('z') pl.ylabel('Effective magnitude') # + [markdown] lang="es" # Saul tuvo buenas razones para creer (en realidad, primero tuvo que modificarlas un poco) que todas las [supernovas de tipo Ia] (https://es.wikipedia.org/wiki/Supernova_de_tipo_Ia) que se muestran aquรญ eran igualmente brillantes intrรญnsecamente, pero aquellas con alto desplazamiento al rojo parecรญan relativamente dรฉbiles en comparaciรณn con aquellas con bajo desplazamiento al rojo, ya que simplemente estaban mรกs lejos. Esto explica la tendencia mostrada, dado que la 'magnitud efectiva' es la forma rara en la que los astrรณnomos suelen expresar cuรกn brillante parece algo. # + [markdown] lang="es" # Lo รบtil de esta mediciรณn es que la distancia a la que se encuentra una supernova o galaxia para un desplazamiento al rojo determinado depende de algunos parรกmetros, uno de los cuales es la cantidad de energรญa oscura que podrรญa haber en el Universo. Casi todos esperaban que estos datos demostraran que no habรญa _ninguna_ _Energรญa Oscura_ cuando Saul lo hizo, pero algunos adivinaron lo contrario. # # Cuando Hubble descubriรณ la expansiรณn, una consecuencia natural fue que la cantidad de energรญa (masa en reposo) contenida en un metro cรบbico se diluirรญa con el tiempo. La _Energรญa Oscura_ serรญa especial, ya que la cantidad de energรญa por metro cรบbico serรญa constante con el tiempo y sugerirรญa que algunos efectos espeluznantes de la [mecรกnica cuรกntica] (https://es.wikipedia.org/wiki/Mecรกnica_cuรกntica) estarรญan causando que las galaxias se separaran. # + [markdown] lang="es" # Asรญ que, usemos los datos de Saul para averiguar cuรกnta energรญa oscura hay en el universo. Primero, necesitamos un modelo para la distancia (luminosidad) de una supernova con un desplazamiento al rojo dado, dada cierta cantidad de Energรญa Oscura. Usamos $\Omega_\Lambda$ para denotar la _fracciรณn_ de toda la materia que se comporta como Energรญa Oscura. # + from astropy.cosmology import FlatLambdaCDM def lumdist(z, olambda): cosmo = FlatLambdaCDM(H0=70, Om0=1. - olambda, Tcmb0=2.725) return cosmo.luminosity_distance(z) # + [markdown] lang="es" # Luego, necesitamos convertir esta distancia en la forma en que los astrรณnomos miden el brillo: # - def effmag(z, olambda, MB): DL = lumdist(z, olambda) return MB + 5. * np.log10(DL.value) # + zs = np.arange(0.01, 0.85, 0.01) pl.plot(dat['z'], dat['Effective magnitude'], marker='.', lw=0.0) pl.plot(zs, effmag(zs, 0.0, 6.), c='k', label='No Dark Energy', alpha=0.5) pl.plot(zs, effmag(zs, 0.5, 6.), c='k', label='Dark Energy!') pl.xlabel('z') pl.ylabel('Magnitud Efectiva') pl.legend(loc=4, frameon=False) # + [markdown] lang="es" # Incluso a simple vista, los datos parecen preferir algo de energรญa oscura. Pero no hay una gran cantidad de รฉsta. Averigรผemos quรฉ prefieren exactamente los datos. Para hacer esto, asumimos que minimizar la distancia entre cada punto y la lรญnea es la mejor medida de quรฉ tan bien se ajusta la teorรญa a los datos (consulte https://es.wikipedia.org/wiki/M%C3%ADnimos_cuadrados). Ademรกs de la fracciรณn de energรญa oscura, tampoco sabemos quรฉ tan brillante es intrรญnsecamente cada supernova, por lo que ajustaremos ambas simultรกneamente. # - from scipy.optimize import minimize def chi2(x): olambda = x[0] MB = x[1] model = effmag(dat['z'], olambda, MB) return np.sum((dat['Effective magnitude'] - model)**2.) res = minimize(chi2, x0=[0.5, 5.0], options={'disp': True}) res.x # + zs = np.arange(0.01, 0.85, 0.01) pl.plot(dat['z'], dat['Effective magnitude'], marker='.', lw=0.0) pl.plot(zs, effmag(zs, 0.0, 6.), c='k', label='No Dark Energy', alpha=0.5) pl.plot(zs, effmag(zs, 0.7, 6.), c='k', label='50% Dark Energy!') pl.plot(zs, effmag(zs, 0.751, 6.), c='c', label='75% Dark Energy!') pl.xlabel('z') pl.ylabel('Magnitud efectiva') pl.legend(loc=4, frameon=False) # + [markdown] lang="es" # ยกAsรญ que hay algo asรญ como 75% de energรญa oscura en el Universo! Siendo las primeras personas en realizar esta mediciรณn, Saul, junto con <NAME> y <NAME>, recibirรญan el Premio Nobel 2011 por su trabajo. # - # ![title](images/perlmutter_nobel.jpg) # + [markdown] lang="es" # Puedes encontrar todos los detalles aquรญ: https://arxiv.org/pdf/astro-ph/9812133.pdf. Advertencia, esto es para los profesionales, asรญ que no te preocupes si no comprendes mucho. # + [markdown] lang="es" # La principal motivaciรณn para DESI es repetir mediciones similares de desplazamientos al rojo de galaxias distantes, con mucha mรกs precisiรณn y aprender mucho mรกs sobre esta espeluznante Energรญa Oscura. # -
Espanol/Intro_es.ipynb
# ##### Copyright 2021 Google LLC. # 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. # # # nqueens3 # <table align="left"> # <td> # <a href="https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/contrib/nqueens3.ipynb"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png"/>Run in Google Colab</a> # </td> # <td> # <a href="https://github.com/google/or-tools/blob/master/examples/contrib/nqueens3.py"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png"/>View source on GitHub</a> # </td> # </table> # First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab. # !pip install ortools # + # Copyright 2010 <NAME> <EMAIL> # # 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. """ n-queens problem in Google CP Solver. N queens problem. Faster than the previous versions: - http://www.hakank.org/gogle_cp_solver/nqueens.py - http://www.hakank.org/gogle_cp_solver/nqueens2.py This model was created by <NAME> (<EMAIL>) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp # Create the solver. solver = pywrapcp.Solver("n-queens") # # data # print("n:", n) print("num_sol:", num_sol) print("print_sol:", print_sol) # declare variables q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)] # # constraints # solver.Add(solver.AllDifferent(q)) solver.Add(solver.AllDifferent([q[i] + i for i in range(n)])) solver.Add(solver.AllDifferent([q[i] - i for i in range(n)])) # symmetry breaking # solver.Add(q[0] == 0) # # search # db = solver.Phase(q, solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_CENTER_VALUE) solver.NewSearch(db) num_solutions = 0 while solver.NextSolution(): if print_sol: qval = [q[i].Value() for i in range(n)] print("q:", qval) for i in range(n): for j in range(n): if qval[i] == j: print("Q", end=" ") else: print("_", end=" ") print() print() num_solutions += 1 if num_sol > 0 and num_solutions >= num_sol: break solver.EndSearch() print() print("num_solutions:", num_solutions) print("failures:", solver.Failures()) print("branches:", solver.Branches()) print("WallTime:", solver.WallTime(), "ms") n = 8 num_sol = 0 print_sol = 1
examples/notebook/contrib/nqueens3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Notebook for Running Calculations import xgcm import xarray as xr import pandas as pd import numpy as np import scipy import matplotlib as mpl from matplotlib import cm import matplotlib.colors as mcolors from matplotlib.patches import Patch from matplotlib.colors import ListedColormap, LinearSegmentedColormap from matplotlib import pyplot as plt from matplotlib import gridspec from cartopy import crs as ccrs import cartopy.feature as cfeature from xhistogram.xarray import histogram import seaborn as sns # %matplotlib inline # %reload_ext autoreload # %autoreload 2 from chazbpei2020.preprocessing import * # --- # ## Calculations (all steps for all ensemble members) # + # for index in range(0, 31): # if index < 10: # indexlabel = str(0)+str(index) # else: # indexlabel = str(index) # directory = '/local/ss23/GFDL_LEs/OCN/OMEGA_ARAG/RCP85/' # filename = 'omega_arag_k11_ens1'+indexlabel+'_1x1_1950_2100.nc' # oa_path = directory+filename # ds = xr.open_dataset(oa_path).rename({'XT_OCEAN': 'xt_ocean', # 'YT_OCEAN': 'yt_ocean', # 'TIME': 'time', # 'OMEGA_ARAG': 'omega_arag'}) # # ----------------------------------------------------------- # # Calculate the time-mean Omega Arag throughout the simulation # da_oa_annual = ds.omega_arag.groupby('time.year').mean(dim='time', skipna=True).squeeze() # startyear = 1950 # endyear = 2100 # interval = 10 # plot decadal contours # span = interval//2 # da_oa_mean = da_oa_annual.copy() # annual averages from 1950-2100 # # da_oa_mean moving averages span from 1955-2095 # # da_oa_mean = moving_avg(da_oa_annual, startyear, endyear, interval) # # ----------------------------------------------------------- # # Definte projection transformations and coordiantes # crs = ccrs.Robinson(central_longitude=180) # src = ccrs.PlateCarree() # lon = ds.xt_ocean.data # lat = ds.yt_ocean.data # # Create levels array to isolate undersaturation threshold # clevs=[1] # # Create list of colors and legend for plots # colors = ['hotpink','magenta','darkviolet','purple', # 'darkblue','blue','dodgerblue','turquoise', # 'limegreen','lime','gold','darkorange', # 'orangered','red','firebrick','maroon'] # # (for decadal mean) # # colors = ['magenta','darkviolet','purple', # # 'darkblue','blue','dodgerblue','turquoise', # # 'limegreen','lime','gold','darkorange', # # 'orangered','red','firebrick','maroon'] # num_contours = len(da_oa_mean) # num_colors = len(colors) # year=startyear+interval # start in 1950 # legend_years = [] # c = 0 # for i in range(span, num_contours, interval): # element = Patch(facecolor=colors[c], label=str(year)) # legend_years.append(element) # year+=interval # c+=1 # # ----------------------------------------------------------- # # Calculate Velocities at undersaturation border for every 2 years # fig, ax = plt.subplots(figsize=[16,10], # subplot_kw={'projection':crs}) # # Extract points from contour line segments for each year # list_xpoints = [] # list contianing lists of x points for each year # list_ypoints = [] # list contianing lists of y points for each year # for i in range(0, num_contours): # cs = ax.contour(lon,lat,da_oa_mean[i],levels=clevs, # colors=colors[i%num_colors],transform=src) # segments = cs.allsegs[0] # num_segs = len(segments) # xpoints = [] # to track multiple paths within each year # ypoints = [] # for j in range(num_segs): # x = segments[j][:,0].tolist() # convert to list to be easily concatenated # y = segments[j][:,1].tolist() # for p in x: # xpoints.append(p) # for p in y: # ypoints.append(p) # list_xpoints.append(xpoints) # add list of x points for each year # list_ypoints.append(ypoints) # add list of y points for each year # ax.set_title('RCP85 Ensemble Avg, k11 $\Omega$Arag Undersaturation Thresholds', # fontsize=22) # ax.add_feature(cfeature.LAND,zorder=10,facecolor='darkgray') # ax.set_global() # # ----------------------------------------------------------- # # For each contour, compute the minimum distance to the contour at # # the end of the interval # # Create parallel arrays of list to hold lists of directions and vectors for each decade # list_vector_dx = [] # change in x # list_vector_dy = [] # change in y # list_vector_magnitude = [] # distance to nearest points # for i in range(0, num_contours-interval): # vector_dx = [] # change in x for decade # vector_dy = [] # change in y for decade # vector_magnitude = [] # vector magnitude for year # xpoints = list_xpoints[i] # x coords for year # ypoints = list_ypoints[i] # y coords for year # # For each point, find min dist and closest point on contour # # at the end of the time interval (one decade later) # num_points = len(xpoints) # for p in range(num_points): # xp = xpoints[p] # x value along contour # yp = ypoints[p] # y value along contour # x,y,dx,dy,mindist = min_dist(xp,yp, # list_xpoints[i+interval], # list_ypoints[i+interval], # da_oa_mean[i].data) # # maintain lists of x and y vectors # # vector_dx.append(dx/1000) # # vector_dy.append(dy/1000) # vector_magnitude.append(mindist/1000) # dist magnitude # # list_vector_dx.append(vector_dx) # # list_vector_dy.append(vector_dy) # list_vector_magnitude.append(vector_magnitude) # # ----------------------------------------------------------- # # Clean list of vector magnitudes to eliminate NaN values # cleaned_vector_magnitude = [] # distances with NaN values filtered out # cleaned_list_xpoints = [] # cleaned_list_ypoints = [] # vel_data_range = num_contours-interval # max_len = 0 # for i in range(0, vel_data_range): # xpoints = list_xpoints[i] # get all x and y points to filter in parallel # ypoints = list_ypoints[i] # cleaned_magnitude = [] # cleaned_xpoints = [] # cleaned_ypoints = [] # vector_magnitude = list_vector_magnitude[i] # num_pts = len(list_vector_magnitude[i]) # for p in range(num_pts): # val = vector_magnitude[p] # # add finite values to cleaned list of magnitudes # if (val == val): # use trick that np.nan != np.nan # cleaned_magnitude.append(val) # cleaned_xpoints.append(xpoints[p]) # cleaned_ypoints.append(ypoints[p]) # cleaned_pts = len(cleaned_magnitude) # if cleaned_pts > max_len: # max_len = cleaned_pts # cleaned_vector_magnitude.append(cleaned_magnitude) # cleaned_list_xpoints.append(cleaned_xpoints) # cleaned_list_ypoints.append(cleaned_ypoints) # for i in range(0, vel_data_range): # cleaned_magnitude = cleaned_vector_magnitude[i] # cleaned_xpoints = cleaned_list_xpoints[i] # cleaned_ypoints = cleaned_list_ypoints[i] # for j in range(len(cleaned_magnitude),max_len): # cleaned_magnitude.append(np.nan) # cleaned_xpoints.append(np.nan) # cleaned_ypoints.append(np.nan) # # ----------------------------------------------------------- # # Save precalculated dataarrays and create 3D DataArray # ens_name = 'ens1'+indexlabel # years = np.arange(1950,2091) # val_idx = np.arange(0,max_len) # # save entire ensemble member in one dataset # da_velocity = xr.DataArray(np.array(cleaned_vector_magnitude), # dims=['year','val_idx'], coords=[years,val_idx], # name='velocity') # da_velocity.to_netcdf('./oa_ensemble_escvel/ens_values/'+ens_name) # da_xpoints = xr.DataArray(np.array(cleaned_list_xpoints), # dims=['year','val_idx'], coords=[years,val_idx], # name='xpoints') # da_xpoints.to_netcdf('./oa_ensemble_escvel/ens_xcoords/'+ens_name) # da_ypoints = xr.DataArray(np.array(cleaned_list_ypoints), # dims=['year','val_idx'], coords=[years,val_idx], # name='ypoints') # da_ypoints.to_netcdf('./oa_ensemble_escvel/ens_ycoords/'+ens_name) # - # --- # --- # --- # ## Calculations (separate steps) # ## Surface k11 RCP85 # + # k11 Omega Arag for ensemble average (preprocessed) # directory = '~/chazbpei2020/data/processed/Omega_Arag/RCP85/' # filename = 'omega_arag_k11_ensAvg_1950_2100.nc' directory = '/local/ss23/GFDL_LEs/OCN/OMEGA_ARAG/RCP85/' filename = 'omega_arag_k11_ens101_1x1_1950_2100.nc' oa_path = directory+filename ds = xr.open_dataset(oa_path).rename({'XT_OCEAN': 'xt_ocean', 'YT_OCEAN': 'yt_ocean', 'TIME': 'time', 'OMEGA_ARAG': 'omega_arag'}) # - # --- # ## Annual Mean Omega Arag # + # Calculate the time-mean Omega Arag throughout the simulation da_oa_annual = ds.omega_arag.groupby('time.year').mean(dim='time', skipna=True).squeeze() startyear = 1950 endyear = 2100 interval = 10 # plot decadal contours span = interval//2 da_oa_mean = da_oa_annual.copy() # annual averages from 1950-2100 # da_oa_mean moving averages span from 1955-2095 # da_oa_mean = moving_avg(da_oa_annual, startyear, endyear, interval) # - # --- # # Calculate Escape Vectors # + # Definte projection transformations and coordiantes crs = ccrs.Robinson(central_longitude=180) src=ccrs.PlateCarree() lon = ds.xt_ocean.data lat = ds.yt_ocean.data # Create levels array to isolate undersaturation threshold clevs=[1] # Create list of colors and legend for plots colors = ['hotpink','magenta','darkviolet','purple', 'darkblue','blue','dodgerblue','turquoise', 'limegreen','lime','gold','darkorange', 'orangered','red','firebrick','maroon'] # (for decadal mean) # colors = ['magenta','darkviolet','purple', # 'darkblue','blue','dodgerblue','turquoise', # 'limegreen','lime','gold','darkorange', # 'orangered','red','firebrick','maroon'] num_contours = len(da_oa_mean) num_colors = len(colors) year=startyear+interval # start in 1950 legend_years = [] c = 0 for i in range(span, num_contours, interval): element = Patch(facecolor=colors[c], label=str(year)) legend_years.append(element) year+=interval c+=1 # - # ## Plot undersaturation borders # + # Plot Velocities at undersaturation border for every 2 years fig, ax = plt.subplots(figsize=[16,10], subplot_kw={'projection':crs}) # Plot contours for each decade c = 0 for i in range(0, num_contours, interval): cs = ax.contour(lon,lat,da_oa_mean[i],levels=clevs, colors=colors[c],linewidths=1.7,transform=src) c += 1 ax.legend(handles=legend_years, loc='center',ncol=2) ax.add_feature(cfeature.LAND,zorder=10,facecolor='darkgray') ax.set_title('RCP85 Ensemble Avg, k11 $\Omega$Arag Undersaturation Thresholds', fontsize=22) ax.set_global() # - # ## Get points along contours # + # # Calculate Velocities at undersaturation border for every 2 years # fig, ax = plt.subplots(figsize=[16,10], # subplot_kw={'projection':crs}) # # Extract points from contour line segments for each year # list_xpoints = [] # list contianing lists of x points for each year # list_ypoints = [] # list contianing lists of y points for each year # for i in range(0, num_contours): # cs = ax.contour(lon,lat,da_oa_mean[i],levels=clevs, # colors=colors[i%num_colors],transform=src) # segments = cs.allsegs[0] # num_segs = len(segments) # xpoints = [] # to track multiple paths within each year # ypoints = [] # for j in range(num_segs): # x = segments[j][:,0].tolist() # convert to list to be easily concatenated # y = segments[j][:,1].tolist() # for p in x: # xpoints.append(p) # for p in y: # ypoints.append(p) # list_xpoints.append(xpoints) # add list of x points for each year # list_ypoints.append(ypoints) # add list of y points for each year # ax.set_title('RCP85 Ensemble Avg, k11 $\Omega$Arag Undersaturation Thresholds', # fontsize=22) # ax.add_feature(cfeature.LAND,zorder=10,facecolor='darkgray') # ax.set_global() # - # ## Minimum distance calculation # %reload_ext autoreload # %autoreload 2 from chazbpei2020.preprocessing import * # + # %%time # For each contour, compute the minimum distance to the contour at # the end of the interval # Create parallel arrays of list to hold lists of directions and vectors for each decade list_vector_dx = [] # change in x list_vector_dy = [] # change in y list_vector_magnitude = [] # distance to nearest points for i in range(0, num_contours-interval): vector_dx = [] # change in x for decade vector_dy = [] # change in y for decade vector_magnitude = [] # vector magnitude for year xpoints = list_xpoints[i] # x coords for year ypoints = list_ypoints[i] # y coords for year # For each point, find min dist and closest point on contour # at the end of the time interval (one decade later) num_points = len(xpoints) for p in range(num_points): xp = xpoints[p] # x value along contour yp = ypoints[p] # y value along contour x,y,dx,dy,mindist = min_dist(xp,yp, list_xpoints[i+interval], list_ypoints[i+interval], da_oa_mean[i].data) # maintain lists of x and y vectors # vector_dx.append(dx/1000) # vector_dy.append(dy/1000) vector_magnitude.append(mindist/1000) # dist magnitude # list_vector_dx.append(vector_dx) # list_vector_dy.append(vector_dy) list_vector_magnitude.append(vector_magnitude) # - # ## Clean list of escape velocities # + # Clean list of vector magnitudes to eliminate NaN values cleaned_vector_magnitude = [] # distances with NaN values filtered out cleaned_list_xpoints = [] cleaned_list_ypoints = [] vel_data_range = num_contours-interval max_len = 0 for i in range(0, vel_data_range): xpoints = list_xpoints[i] # get all x and y points to filter in parallel ypoints = list_ypoints[i] cleaned_magnitude = [] cleaned_xpoints = [] cleaned_ypoints = [] vector_magnitude = list_vector_magnitude[i] num_pts = len(list_vector_magnitude[i]) for p in range(num_pts): val = vector_magnitude[p] # add finite values to cleaned list of magnitudes if (val == val): # use trick that np.nan != np.nan cleaned_magnitude.append(val) cleaned_xpoints.append(xpoints[p]) cleaned_ypoints.append(ypoints[p]) cleaned_pts = len(cleaned_magnitude) if cleaned_pts > max_len: max_len = cleaned_pts cleaned_vector_magnitude.append(cleaned_magnitude) cleaned_list_xpoints.append(cleaned_xpoints) cleaned_list_ypoints.append(cleaned_ypoints) for i in range(0, vel_data_range): cleaned_magnitude = cleaned_vector_magnitude[i] cleaned_xpoints = cleaned_list_xpoints[i] cleaned_ypoints = cleaned_list_ypoints[i] for j in range(len(cleaned_magnitude),max_len): cleaned_magnitude.append(np.nan) cleaned_xpoints.append(np.nan) cleaned_ypoints.append(np.nan) # - # ## Save DataArray for future use # + # Sort out how to store arrays in parallel # run calculation for all of tomorrow # Save precalculated dataarrays and create 3D DataArray ens_name = 'ens101' years = np.arange(1950,2091) val_idx = np.arange(0,max_len) # save entire ensemble member in one dataset da_velocity = xr.DataArray(np.array(cleaned_vector_magnitude), dims=['year','val_idx'], coords=[years,val_idx], name='velocity') da_velocity.to_netcdf('./oa_ensemble_escvel/ens_values/'+ens_name) da_xpoints = xr.DataArray(np.array(cleaned_list_xpoints), dims=['year','val_idx'], coords=[years,val_idx], name='xpoints') da_xpoints.to_netcdf('./oa_ensemble_escvel/ens_xcoords/'+ens_name) da_ypoints = xr.DataArray(np.array(cleaned_list_ypoints), dims=['year','val_idx'], coords=[years,val_idx], name='ypoints') da_ypoints.to_netcdf('./oa_ensemble_escvel/ens_ycoords/'+ens_name) # - # --- # --- # --- # ## Read and parse DataArrays ensmbr_data = xr.open_dataset('./oa_ensemble_escvel/ens_values/ens101') da_xcoords = xr.open_dataset('./oa_ensemble_escvel/ens_xcoords/ens101') da_ycoords = xr.open_dataset('./oa_ensemble_escvel/ens_ycoords/ens101') # + # Read in DataArray for each Ensemble num_members = 30 list_ensmbrs_data = [] list_ensmbrs_xp = [] list_ensmbrs_yp = [] list_ensmbrs_data.append(None) # offset so indices match ensemble number list_ensmbrs_xp.append(None) list_ensmbrs_yp.append(None) for m in range(1,num_members+1): if m < 10: ens_name = 'ens10'+str(m) else: ens_name = 'ens1'+str(m) vel_path = './oa_ensemble_escvel/ens_values/'+ens_name x_path = './oa_ensemble_escvel/ens_xcoords/'+ens_name y_path = './oa_ensemble_escvel/ens_ycoords/'+ens_name da_velocity = xr.open_dataset(vel_path) da_xpoints = xr.open_dataset(x_path) da_ypoints = xr.open_dataset(y_path) list_ensmbrs_data.append(da_velocity) list_ensmbrs_xp.append(da_xpoints) list_ensmbrs_yp.append(da_ypoints) # + # Clean data (filter out filler np.nan values) list_ensmbrs_vel = [] list_ensmbrs_xpoints = [] list_ensmbrs_ypoints = [] list_ensmbrs_vel.append(None) # offset so indices match ensemble number list_ensmbrs_xpoints.append(None) list_ensmbrs_ypoints.append(None) vel_data_range = len(da_velocity.year) # For each Ensemble member, clean the dataset for m in range(1,num_members+1): cleaned_vel = [] cleaned_xpoints = [] cleaned_ypoints = [] ensmbr_data = list_ensmbrs_data[m] ensmbr_xpoints = list_ensmbrs_xp[m] ensmbr_ypoints = list_ensmbrs_yp[m] max_len = len(ensmbr_data.val_idx) # Clean escape velocity lists for each year for i in range(0, vel_data_range): escvel = ensmbr_data.isel(year=i).velocity.data.tolist() xpoints = ensmbr_xpoints.isel(year=i).xpoints.data.tolist() ypoints = ensmbr_ypoints.isel(year=i).ypoints.data.tolist() nan_idx = None for p in range(0,max_len): val = escvel[p] if val != val: nan_idx = p # track index where filler NaN values start break del escvel[p:] del xpoints[p:] del ypoints[p:] cleaned_vel.append(escvel) cleaned_xpoints.append(xpoints) cleaned_ypoints.append(ypoints) list_ensmbrs_vel.append(cleaned_vel) list_ensmbrs_xpoints.append(cleaned_xpoints) list_ensmbrs_ypoints.append(cleaned_ypoints) # + # # Read in and clean DataArray for annual ensemble average # vel_path = './oa_ensemble_escvel/ens_values/ensAvg1yr' # x_path = './oa_ensemble_escvel/ens_xcoords/ensAvg1yr' # y_path = './oa_ensemble_escvel/ens_ycoords/ensAvg1yr' # ens_annualAvg_data = xr.open_dataset(vel_path) # ens_annualAvg_xp = xr.open_dataset(x_path) # ens_annualAvg_yp = xr.open_dataset(y_path) # ens_annualAvg_vel = [] # ens_annualAvg_xpoints = [] # ens_annualAvg_ypoints = [] # max_len = len(ens_annualAvg_data.val_idx) # # Clean escape velocity lists for each year # for i in range(0, vel_data_range): # 141 years for annual avg # escvel = ens_annualAvg_data.isel(year=i).velocity.data.tolist() # xpoints = ens_annualAvg_xp.isel(year=i).xpoints.data.tolist() # ypoints = ens_annualAvg_yp.isel(year=i).ypoints.data.tolist() # nan_idx = None # for p in range(0,max_len): # val = escvel[p] # if val != val: # nan_idx = p # track index where filler NaN values start # break # del escvel[p:] # del xpoints[p:] # del ypoints[p:] # # append each year to list of entire simulation # ens_annualAvg_vel.append(escvel) # ens_annualAvg_xpoints.append(xpoints) # ens_annualAvg_ypoints.append(ypoints) # + # # Read in and clean DataArray for 10-yr moving ensemble average # vel_path = './oa_ensemble_escvel/ens_values/ensAvg10yr' # x_path = './oa_ensemble_escvel/ens_xcoords/ensAvg10yr' # y_path = './oa_ensemble_escvel/ens_ycoords/ensAvg10yr' # ens_movingAvg_data = xr.open_dataset(vel_path) # ens_movingAvg_xp = xr.open_dataset(x_path) # ens_movingAvg_yp = xr.open_dataset(y_path) # ens_movingAvg_vel = [] # ens_movingAvg_xpoints = [] # ens_movingAvg_ypoints = [] # # append 5 'None' years so indices match (1955 = index 5) # for y in range(5): # ens_movingAvg_vel.append(None) # ens_movingAvg_xpoints.append(None) # ens_movingAvg_ypoints.append(None) # max_len = len(ens_movingAvg_data.val_idx) # # Clean escape velocity lists for each year # for i in range(0, vel_data_range-10): # 131 years for 10yr moving avg # escvel = ens_movingAvg_data.isel(year=i).velocity.data.tolist() # xpoints = ens_movingAvg_xp.isel(year=i).xpoints.data.tolist() # ypoints = ens_movingAvg_yp.isel(year=i).ypoints.data.tolist() # nan_idx = None # for p in range(0,max_len): # val = escvel[p] # if val != val: # nan_idx = p # track index where filler NaN values start # break # del escvel[p:] # del ypoints[p:] # del xpoints[p:] # # append each year to list of entire simulation # ens_movingAvg_vel.append(escvel) # ens_movingAvg_xpoints.append(xpoints) # ens_movingAvg_ypoints.append(ypoints) # - # --- # # Calculate Regional Mean Velocities for Ensemble Members and Ensemble Averages # + # Calculate Natural component of variability for Ensemble Members list_ensmbrs_global = [] list_ensmbrs_north = [] list_ensmbrs_equ = [] list_ensmbrs_south = [] list_ensmbrs_global.append(None) # offset so indices match ensemble number list_ensmbrs_north.append(None) list_ensmbrs_equ.append(None) list_ensmbrs_south.append(None) # for each ensemble member for m in range(1,num_members+1): ensmbr_vel = list_ensmbrs_vel[m] # all years in simulation ensmbr_xpoints = list_ensmbrs_xpoints[m] ensmbr_ypoints = list_ensmbrs_ypoints[m] # annual escape velocity averages for one ensemble member ensmbr_global_avg = [] ensmbr_north_avg = [] ensmbr_equ_avg = [] ensmbr_south_avg = [] for i in range(0, vel_data_range): # Get escape velocity averages by latitudinal region values = ensmbr_vel[i].copy() # values for specific year north_avg = [] equ_avg = [] south_avg = [] ypoints = ensmbr_ypoints[i] # Get ypoints for specific year num_pts = len(ypoints) for n in range(num_pts): # Filter points by region p = ypoints[n] if 35 < p < 80: north_avg.append(values[n]) if -40 < p < 35: equ_avg.append(values[n]) if -90 < p < -40: south_avg.append(values[n]) # Get avg velocities for each year global_avg = np.sum(values) / len(values) north_avg = np.sum(north_avg) / len(north_avg) equ_avg = np.sum(equ_avg) / len(equ_avg) south_avg = np.sum(south_avg) / len(south_avg) ensmbr_global_avg.append(global_avg) ensmbr_north_avg.append(north_avg) ensmbr_equ_avg.append(equ_avg) ensmbr_south_avg.append(south_avg) list_ensmbrs_global.append(ensmbr_global_avg) list_ensmbrs_north.append(ensmbr_north_avg) list_ensmbrs_equ.append(ensmbr_equ_avg) list_ensmbrs_south.append(ensmbr_south_avg) # + # Calculate annual escape velocity regional averages for moving average movingAvg_global = [] movingAvg_north = [] movingAvg_equ = [] movingAvg_south = [] # append 5 'None' years so indices match (1955 = index 5) for y in range(5): movingAvg_global.append(None) movingAvg_north.append(None) movingAvg_equ.append(None) movingAvg_south.append(None) for i in range(5, vel_data_range-5): # Get escape velocity averages by latitudinal region values = ens_movingAvg_vel[i].copy() # movingAvg velocities for given year north_avg = [] equ_avg = [] south_avg = [] ypoints = ens_movingAvg_ypoints[i] # Get ypoints for specific year num_pts = len(ypoints) for n in range(num_pts): # Filter points by region p = ypoints[n] if 35 < p < 80: north_avg.append(values[n]) if -40 < p < 35: equ_avg.append(values[n]) if -90 < p < -40: south_avg.append(values[n]) global_avg = np.sum(values) / len(values) north_avg = np.sum(north_avg) / len(north_avg) equ_avg = np.sum(equ_avg) / len(equ_avg) south_avg = np.sum(south_avg) / len(south_avg) movingAvg_global.append(global_avg) movingAvg_north.append(north_avg) movingAvg_equ.append(equ_avg) movingAvg_south.append(south_avg) # - # # Calculate Natural Variability for Each Ensemble Member # + # Calculate natural component of cliamte velocity # Ens1_nat(yr) = Ens1(yr) - ( Ens_mean(yr-4: yr-5)) # Ens1_nat(yr) = Ens1(yr) - ( Ens_mean(1950: 1959)) list_ensmbrs_global_nat = [] list_ensmbrs_north_nat = [] list_ensmbrs_equ_nat = [] list_ensmbrs_south_nat = [] list_ensmbrs_global_nat.append(None) # offset so indices match ensemble number list_ensmbrs_north_nat.append(None) list_ensmbrs_equ_nat.append(None) list_ensmbrs_south_nat.append(None) # for each ensemble members for m in range(1,num_members+1): # single out each ensemble member by region ensmbr_global = list_ensmbrs_global[m] ensmbr_north = list_ensmbrs_north[m] ensmbr_equ = list_ensmbrs_equ[m] ensmbr_south = list_ensmbrs_south[m] ensmbr_global_nat = [] ensmbr_north_nat = [] ensmbr_equ_nat = [] ensmbr_south_nat = [] # append 5 'None' years so indices match (1955 = index 5) for y in range(5): ensmbr_global_nat.append(None) ensmbr_north_nat.append(None) ensmbr_equ_nat.append(None) ensmbr_south_nat.append(None) # for each year in simulation for i in range(5, vel_data_range-5): ensmbr_global_nat.append(abs(ensmbr_global[i] - movingAvg_global[i])) ensmbr_north_nat.append(abs(ensmbr_north[i] - movingAvg_north[i])) ensmbr_equ_nat.append(abs(ensmbr_equ[i] - movingAvg_equ[i])) ensmbr_south_nat.append(abs(ensmbr_south[i] - movingAvg_south[i])) list_ensmbrs_global_nat.append(ensmbr_global_nat) list_ensmbrs_north_nat.append(ensmbr_north_nat) list_ensmbrs_equ_nat.append(ensmbr_equ_nat) list_ensmbrs_south_nat.append(ensmbr_south_nat) # + # Get average natural variability over ensemble members list_global_nat_avg = [] list_north_nat_avg = [] list_equ_nat_avg = [] list_south_nat_avg = [] # append 5 'None' years so indices match (1955 = index 5) for y in range(5): list_global_nat_avg.append(None) list_north_nat_avg.append(None) list_equ_nat_avg.append(None) list_south_nat_avg.append(None) for i in range(5, vel_data_range-5): global_avg = [] north_avg = [] equ_avg = [] south_avg = [] for m in range(1,num_members+1): global_avg.append(abs(list_ensmbrs_global_nat[m][i])) north_avg.append(abs(list_ensmbrs_north_nat[m][i])) equ_avg.append(abs(list_ensmbrs_equ_nat[m][i])) south_avg.append(abs(list_ensmbrs_south_nat[m][i])) global_avg = np.sum(global_avg) / len(global_avg) north_avg = np.sum(north_avg) / len(north_avg) equ_avg = np.sum(equ_avg) / len(equ_avg) south_avg = np.sum(south_avg) / len(south_avg) list_global_nat_avg.append(global_avg) list_north_nat_avg.append(north_avg) list_equ_nat_avg.append(equ_avg) list_south_nat_avg.append(south_avg) # - # --- # ## Plot Anthropogenic vs Natural Change # Set context of plots sns.set() # context = {notebook, paper, talk, poster} # sns.set_context(context=None) # sns.set_style('white') # sns.reset_orig() # revert to matplotlib presets # + # Create discrete color map and legend bar_clrs = ['darkviolet','orange','limegreen'] regions = ['Northern Atlantic & Pacific', 'Equatorial', 'Southern'] legend_regions = [] for i in range(0, 3): element = Patch(facecolor=bar_clrs[i], label=regions[i]) legend_regions.append(element) # + # Get decadal regional escape velocity averages (natural and anthropogenic) north_nat = [] equ_nat = [] south_nat = [] north_anth = [] equ_anth = [] south_anth = [] for i in range(50,76,5): north_nat.append(list_north_nat_avg[i]) equ_nat.append(list_equ_nat_avg[i]) south_nat.append(list_south_nat_avg[i]) north_anth.append(movingAvg_north[i]) equ_anth.append(movingAvg_equ[i]) south_anth.append(movingAvg_south[i]) # + # Create Histograms for escape velocity distribution at each timestep fig, axs = plt.subplots(nrows=2,ncols=1,figsize=[12,10], gridspec_kw={'height_ratios': [3, 5]}) labels = [] for yr in range(2000,2026,5): labels.append(str(yr)) x = np.arange(len(labels)) # the label locations width = 0.2 # the width of the bars ax = axs[0] bars_north_nat = ax.bar(x - width, north_nat, width, color=bar_clrs[0], label=legend_regions[0]) bars_equ_nat = ax.bar(x, equ_nat, width, color=bar_clrs[1], label=legend_regions[1]) bars_south_nat = ax.bar(x + width, south_nat, width, color=bar_clrs[2], label=legend_regions[2]) ax.set_ylabel('Natural (km)',fontsize=16) ax.set_yticks(np.arange(0,151,50)) ax.set(xticks=[]) ax.legend(handles=legend_regions, loc='upper right',fontsize='large') ax = axs[1] bars_north_anth = ax.bar(x - width, north_anth, width, color=bar_clrs[0], label=legend_regions[0]) bars_equ_anth = ax.bar(x, equ_anth, width, color=bar_clrs[1], label=legend_regions[1]) bars_south_anth = ax.bar(x + width, south_anth, width, color=bar_clrs[2], label=legend_regions[2]) ax.set_ylabel('Anthropogenic (km)',fontsize=16) ax.set_yticks(np.arange(0,251,50)) # flip bars on anthropogenic graph ax.invert_yaxis() ax.set(xticks=x, xticklabels=labels) ax.xaxis.tick_top() fig.tight_layout() fig.subplots_adjust(hspace=0.08) fig.suptitle('$\Omega$ Arag Regional Escape Distance\nNatural Variability vs. Anthropogenic Forcing', y=1.11,fontsize=25) fig.savefig("./oa_escvel_stats/oa_k11_escvel_var_regional") # + # Get decadal global escape velocity averages (natural and anthropogenic) global_nat = [] global_anth = [] for i in range(50,76,5): global_nat.append(list_global_nat_avg[i]) global_anth.append(movingAvg_global[i]) # + # Create Histograms for escape velocity distribution at each timestep fig, axs = plt.subplots(nrows=2,ncols=1,figsize=[12,10], gridspec_kw={'height_ratios': [3, 4]}) labels = [] for yr in range(2000,2026,5): labels.append(str(yr)) x = np.arange(len(labels)) # the label locations width = 0.5 # the width of the bars ax = axs[0] bars_global_nat = ax.bar(x, global_nat, width, color='dodgerblue', label='Global') ax.set_ylabel('Natural (km)',fontsize=16) ax.set_yticks(np.arange(0,151,50)) ax.set(xticks=[]) ax = axs[1] bars_global_anth = ax.bar(x, global_anth, width, color='dodgerblue', label='Global') ax.set_ylabel('Anthropogenic (km)',fontsize=16) ax.set_yticks(np.arange(0,201,50)) # flip bars on anthropogenic graph ax.invert_yaxis() ax.set(xticks=x, xticklabels=labels) ax.xaxis.tick_top() y1 = range(200) y2 = range(200) # may need x fig.tight_layout() fig.subplots_adjust(hspace=0.08) fig.suptitle('$\Omega$ Arag Global Escape Distance\nNatural Variability vs. Anthropogenic Forcing', y=1.11,fontsize=25) fig.savefig("./oa_escvel_stats/oa_k11_escvel_var_global") # -
notebooks/Climate_Velocities/oa_escvel_calc.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # Simple testing of FBT in Warp. Just transform beam in a drift. No solenoid included and no inverse transform. # %matplotlib notebook import sys del sys.argv[1:] from warp import * from warp.data_dumping.openpmd_diag import particle_diag import numpy as np import os from copy import deepcopy import matplotlib.pyplot as plt # + diagDir = 'diags/test/hdf5' def cleanupPrevious(outputDirectory = diagDir): if os.path.exists(outputDirectory): files = os.listdir(outputDirectory) for file in files: if file.endswith('.h5'): os.remove(os.path.join(outputDirectory,file)) cleanupPrevious() def setup(): pass # + ########################################## ### Create Beam and Set its Parameters ### ########################################## top.lrelativ = True top.relativity = 1 beam = Species(type=Electron, name='Electron') beam.ekin = 55e6 #KE = 2.5 MeV derivqty() #Sets addition derived parameters (such as beam.vbeam) top.emitx = 4.0*800e-6 / top.gammabar # geometric emittance: emit_full = 4 * emit_rms top.emity = 4.0*1e-6 / top.gammabar beam.a0 = sqrt(top.emitx * 5.0) beam.b0 = sqrt(top.emity * 5.0) beam.ap0 = -1 * top.emitx * 0.0 / beam.a0 beam.bp0 = -1 * top.emity * 0.0 / beam.b0 beam.vthz = 0 #Sets the longitudinal thermal velocity (see iop_lin_002) beam.ibeam = 0 # beam.ibeam/(top.gammabar**2) #Set correct current for relativity (see iop_lin_002) top.npmax = 10000 w3d.distrbtn = "Gaussian0" w3d.cylinder = True #Set True if running without envelope solver # + ##################### ### Setup Lattice ### ##################### turnLength = 2.0e-3 #39.9682297148 steps = 2 #8000. top.zlatstrt = 0#0. # z of lattice start (added to element z's on generate). top.zlatperi = 10.0#turnLength # Lattice periodicity top.dt = turnLength / steps / beam.vbeam start = Marker() drift1 = Drft(l=1e-3) transform = Marker() drift2 = Drft(l=1e-3) end = Marker() transformLine = start + drift1 + transform + drift2 + end madtowarp(transformLine) # + def FRBT(beta=5.0, alpha=0.0): """ Transforms a matched flat beam to a round 'magnetized' beam. """ gamma = (1. - alpha**2) / beta R = np.zeros([6,6],dtype='float64') R[0,0] = 1. + alpha R[0,1] = beta R[0,2] = 1. - alpha R[0,3] = -beta R[1,0] = -gamma R[1,1] = 1. - alpha R[1,2] = gamma R[1,3] = 1. + alpha R[2,0] = 1. - alpha R[2,1] = -beta R[2,2] = 1. + alpha R[2,3] = beta R[3,0] = gamma R[3,1] = 1. + alpha R[3,2] = -gamma R[3,3] = 1. - alpha R[4,4] = 2. R[5,5] = 2. R = 0.5 * R x = {} norm = {} for i in range(6): for j in range(6): norm[i,j] = 1.0 norm[0,1] = norm[0,3] = norm[2,1] = norm[2,3] = 1./top.pgroup.uzp norm[1,0] = norm[1,2] = top.pgroup.uzp norm[3,0] = norm[3,2] = top.pgroup.uzp x = {} x[0] = np.copy(top.pgroup.xp) x[1] = np.copy(top.pgroup.uxp) x[2] = np.copy(top.pgroup.yp) x[3] = np.copy(top.pgroup.uyp) x[4] = np.copy(top.pgroup.zp) x[5] = np.copy(top.pgroup.uzp) print x[0].shape holding = [] for i in range(6): val = 0 for j in range(6): val += R[i,j] * x[j] * norm[i,j] holding.append(val) top.pgroup.xp = holding[0] top.pgroup.uxp = holding[1] top.pgroup.yp = holding[2] top.pgroup.uyp = holding[3] top.pgroup.zp = holding[4] top.pgroup.uzp = holding[5] # print "Transform!" # + ################################ ### 3D Simulation Parameters ### ################################ top.prwall = pr1 = 0.14 #Set cells w3d.nx = 128 w3d.ny = 128 w3d.nz = 1 #Set boundaries w3d.xmmin = -0.10 w3d.xmmax = 0.10 w3d.ymmin = -0.10 w3d.ymmax = 0.10 w3d.zmmin = -2e-3 w3d.zmmax = 2e-3 top.pboundxy = 0 # Absorbing Boundary for particles top.ibpush = 2 # set type of pusher to vXB push without tan corrections ## 0:off, 1:fast, 2:accurate top.fstype = -1 # + ############################ ### Particle Diagnostics ### ############################ diagP0 = particle_diag.ParticleDiagnostic( period=1, top=top, w3d=w3d, species= { species.name : species for species in listofallspecies }, comm_world=comm_world, lparallel_output=False, write_dir = diagDir[:-4] ) diagP = particle_diag.ParticleDiagnostic( period=1, top=top, w3d=w3d, species= { species.name : species for species in listofallspecies }, comm_world=comm_world, lparallel_output=False, write_dir = diagDir[:-4] ) installbeforestep( diagP0.write ) installafterstep( diagP.write ) # + ################################# ### Generate and Run PIC Code ### ################################# package("wxy") generate() fieldsolve() #installafterstep(thin_lens_lattice) #Execute First Step installbeforestep(FRBT) step(1) # + def readparticles(filename): """ Reads in openPMD compliant particle file generated by Warp's ParticleDiagnostic class. Parameters: filename (str): Path to a ParticleDiagnostic output file. Returns: particle_arrays (dict): Dictionary with entry for each species in the file that contains an array of the 6D particle coordinates. """ dims = ['momentum/x', 'position/y', 'momentum/y', 'position/z', 'momentum/z'] particle_arrays = {} f = h5.File(filename, 'r') if f.attrs.get('openPMD') is None: print "Warning!: Not an openPMD file. This may not work." step = f['data'].keys()[0] species_list = f['data/%s/particles' % step].keys() for species in species_list: parray = f['data/%s/particles/%s/position/x' % (step, species)] for dim in dims: parray = np.column_stack((parray, f['data/%s/particles/%s/' % (step, species) + dim])) particle_arrays[species] = parray return particle_arrays def convertunits(particlearray): """ Putting particle coordinate data in good ol'fashioned accelerator units: x: m x': ux/uz y: m y': uy/uz z: m p: MeV/c """ dat = deepcopy(particlearray) # Don't copy by reference dat[:, 1] = dat[:, 1] / dat[:, 5] dat[:, 3] = dat[:, 3] / dat[:, 5] dat[:, 5] = dat[:, 5] / 5.344286E-22 return dat # - def svecplot(array): fig = plt.figure(figsize = (8,8)) Q = plt.quiver(array[:,0],array[:,2],array[:,1],array[:,3]) plt.quiverkey(Q,0.0, 0.92, 0.002, r'$2', labelpos='W') xmax = np.max(array[:,0]) xmin = np.min(array[:,0]) plt.xlim(1.5*xmin,1.5*xmax) plt.ylim(1.5*xmin,1.5*xmax) plt.show() init = convertunits(readparticles('diags/test/hdf5/data00000000.h5')['Electron']) fin = convertunits(readparticles('diags/test/hdf5/data00000001.h5')['Electron']) svecplot(init) plt.title("Initial Flat Beam") plt.xlabel("x (m)") plt.ylabel("y (m)") svecplot(fin) plt.title("Magnetized Beam after FRBT") plt.xlabel("x (m)") plt.ylabel("y (m)") def vortex_check(init): beta = 5.0 alpha = 0 gamma = (1 - alpha**2) / beta x1 = ((1+alpha) * init[0,0] + (beta) * init[0,1] + (1-alpha) * init[0,2] + (-beta) * init[0,3]) * 0.5 x2 = ((-gamma) * init[0,0] + (1-alpha) * init[0,1] + (gamma) * init[0,2] + (1+alpha) * init[0,3]) * 0.5 y1 = ((1-alpha) * init[0,0] + (-beta) * init[0,1] + (1+alpha) * init[0,2] + (beta) * init[0,3]) * 0.5 y2 = ((gamma) * init[0,0] + (1+alpha) * init[0,1] + (-gamma) * init[0,2] + (1-alpha) * init[0,3]) * 0.5 print x1, fin[0,0] print x2, fin[0,1] print y1, fin[0,2] print y2, fin[0,3] def calc_emittance(array): xemit = np.sqrt(np.average(array[:,0]**2) * np.average(array[:,1]**2) - np.average(array[:,0] * array[:,1])**2 ) yemit = np.sqrt(np.average(array[:,2]**2) * np.average(array[:,3]**2) - np.average(array[:,2] * array[:,3])**2 ) return xemit,yemit epsx0,epsy0 = calc_emittance(init) epsxf,epsyf = calc_emittance(fin) print "Initial:\n x-emit: %s Initial y-emit: %s" % (epsx0,epsy0) print "After Transform:\n x-emit: %s y-emit: %s" % (epsxf,epsyf)
rscooler/FBT/warp/FRBT_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/SokichiFujita/PyTorch-for-Deep-Learning-and-Computer-Vision/blob/master/Chapter3_Gradient_with_PyTorch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="j5-Z1fDmXHNv" colab_type="code" colab={} import torch # + id="NPMM8LxShGDt" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="1c4a43f7-18fe-4ca2-deff-6ba2bc953608" x = torch.tensor(2.0, requires_grad=True) y = 9*x**4 + 2*x**3 + 3*x**2 + 6*x + 1 print(x) print(y) a = y.backward() print(a) b = x.grad print(b) # + id="MVLkHjQMiPu5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="339ba742-86ba-4aaa-99bc-c4c0946f6f65" x = torch.tensor(1.0, requires_grad=True) z = torch.tensor(2.0, requires_grad=True) y = x**2 + z**3 y.backward() xx = x.grad yy = z.grad print(xx) print(yy)
Chapter3_Gradient_with_PyTorch.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Common part # + _uuid="afeeb70a91a7c1349f7f15a5040aabd6a06d5a79" import numpy as np import pandas as pd # + _uuid="3c5aefd81c129744e5d2f480520b256633e90b57" train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') # + _uuid="79ed76585d1030f95111c5d78e09d51afd4d32ed" #check the first rows of train data set (to check if the import was Ok) train.tail() # + _uuid="cb1b1b8ecc807c8a6e426bcc17106c681c640993" #check the first rows of test data set (to check if the import was Ok) test.tail() # + [markdown] _uuid="40f5c60fb2950a4b9ae4f41da6ce6a6b4eb77333" # Reclassify all the literal data (except Name; NaN - is not literal, it is Null-value) to numeric to use it in regression models: # + _uuid="7fef40822a01eb023897e1cd5633a7e3f44258b8" # Train data set train.loc[train['Sex'] == 'male', 'Sex'] = 1 train.loc[train['Sex'] == 'female', 'Sex'] = 0 train.loc[train['Embarked'] == 'S', 'Embarked'] = 0 train.loc[train['Embarked'] == 'C', 'Embarked'] = 0 train.loc[train['Embarked'] == 'Q', 'Embarked'] = 0 # Test data set test.loc[test['Sex'] == 'male', 'Sex'] = 1 test.loc[test['Sex'] == 'female', 'Sex'] = 0 test.loc[test['Embarked'] == 'S', 'Embarked'] = 0 test.loc[test['Embarked'] == 'C', 'Embarked'] = 0 test.loc[test['Embarked'] == 'Q', 'Embarked'] = 0 # + [markdown] _uuid="b9015b8627d6244e4ea4061b59eca5ced6a484d9" # Fill the missing values with our assumptions # + _uuid="6d2c53ce54ff06445eda285aa23396774a871f98" # Train data set train['Age'] = train['Age'].fillna(train['Age'].median()) train['Embarked'] = train['Embarked'].fillna(1) train['Fare'] = train['Fare'].fillna(train['Fare'].mean()) # Test data set test['Age'] = test['Age'].fillna(train['Age'].median()) test['Embarked'] = test['Embarked'].fillna(1) test['Fare'] = test['Fare'].fillna(test['Fare'].mean()) # + [markdown] _uuid="3f8a1a5194ba057ae7bfcba1534a2df4fb754197" # *** # + [markdown] _uuid="81745dfdcaf20f58c68737a64006d0b24a768695" # # Modeling # # ### Decision Tree Regressor modeling # # Based on Kaggle # https://www.kaggle.com/dansbecker/your-first-machine-learning-model # + _uuid="d87c99b87487c0b48f76d1131df603aae662b8d5" predictors = ["Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"] # + [markdown] _uuid="2e9a77b923b0841c809bfee32f1d6b679e430efe" # *** # + from sklearn.tree import DecisionTreeRegressor # Define model. Specify a number for random_state to ensure same results each run dtree = DecisionTreeRegressor(random_state=1) # Fit model dtree.fit(train[predictors], train['Survived']) predictions = dtree.predict(test[predictors]) # convert results to binary n = 0 for i in predictions: if(i > 0.5): predictions[n] = 1 else: predictions[n] = 0 n += 1 # change type of the predictions array to integer predictions = predictions.astype(int) predictions.dtype # + [markdown] _uuid="3f8a1a5194ba057ae7bfcba1534a2df4fb754197" # *** # + [markdown] _uuid="ed4f314f278490622612f1e01428d4d6622f6539" # # Submission # + [markdown] _uuid="1008fe3ad091e1ebdd058adb160b986a608a21c7" # We need to put our csv-file with the results into Kaggle /input directory like so: # # (LB score: 0.69377) # + _uuid="7151936789a2541afc044411acaa7aa54e1fe87c" submission = pd.DataFrame({ "PassengerId": test["PassengerId"], "Survived": predictions }) submission.to_csv("dtree_submit2.csv", index=False) # - # ## Kaggle API to submit # # API: https://github.com/Kaggle/kaggle-api # # Check submissions: # # `kaggle competitions submissions` # # Submit to competition: # # `kaggle competitions submit titanic -f Git\kaggle-titanic\src\dtree_submit2.csv -m "decision tree"`
src/decision-tree-regressor.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # GMODuck # A genetically modified yellow quantum duck who is competing in QHack 2021 Open Hackathon. This ๐Ÿฆ† is capable of building QML circuits using genetic programming without having any idea why his model works but he assures it's the best. # In a QML application, knowing what's the best Quantum circuit is a field of research. With this demo, ๐Ÿฆ† wants to jump that process and build a quantum circuit that successfully is the best one for its problem. At the moment, is problem is: properly classify a point in a 2D grid as either <span style="color:blue">blue</span> or <span style="color:orange">orange</span> based on a given dataset. # # To to so, ๐Ÿฆ† is going to use genetic programming. Where the idea is to encode a quantum circuit in a string of zeros and ones that will represent the genome we want to evolve. So... # # 1. Create a genome that translates into a quantum circuit - different genes, encode different gates/templates # 2. Randomly generate agents (agents are quantum circuits) # 3. Train all agents and use area under ROC as fitness # 4. Do "natural selection", cross between agents to create offspring and randomly mutate agents # 5. Repeat for some generations until ๐Ÿฆ† has a satisfying classifier # First things first: let's install and import everything we need... # + # %%capture # !pip install pennylane # !pip install matplotlib # !pip install sklearn # Imports import random import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn import metrics as metrics np.random.seed(42) dev = qml.device('default.qubit', wires=2) # - # Before looking into the code, let's vizualise what this _encode a quantum circuit in a string of zeros and ones_ really means. # # We want to have a bit in the string that represents the **encoding** of data, another one or the **circuit** we are trainning and a last one for the **measurment**. So, something like this: genome = "101" encoding_gene = genome[0] circuit_gene = genome[1] measurment_gene = genome[2] print("Encoding:", encoding_gene, "\nCircuit:", circuit_gene, "\nMeasurement:", measurment_gene) # Now that we have the idea of what each gene in the genome represents, we can attribute functions to them. So, we want to look at a string, the genome, and transform it into a quantum circuit. Let's build that function! def genome_to_circuit(genome, x, w): @qml.qnode(dev) def circuit(x,w): # Genes from genome encoding_gene = genome[0] circuit_gene = genome[1] measurment_gene = genome[2] # From gene, to quantum gate ## Encode data if encoding_gene == "0": qml.templates.AngleEmbedding(x, wires=[0, 1]) elif encoding_gene == "1": qml.templates.IQPEmbedding(x, wires=[0, 1]) ## Choose between basic entanglement and a more "complex" circuit with qubit Z, X rotationsa and CNOT operator if circuit_gene == "0": qml.templates.BasicEntanglerLayers(w, wires=[0, 1]) elif circuit_gene == "1": qml.RZ(w[0][0],wires=0) qml.RX(w[0][1],wires=1) qml.CNOT(wires=[0,1]) qml.RZ(-1*w[0][0],wires=1) qml.RX(-1*w[0][1],wires=0) ## Measurement if measurment_gene == "0": measure = qml.PauliZ(wires=0) elif measurment_gene == "1": measure = qml.PauliY(wires=0) return qml.expval(measure) circuit(x,w) print(circuit.draw()) return circuit(x,w) # + # Some intial parameters to test quantum model x = np.array([0.1, 0.2], requires_grad=False) w = np.array([[-2.1, 1.2]]) genome_to_circuit(genome, x, w) # - # You can now test different genomes! genome = "010" genome_to_circuit(genome, x, w) # Now that we understood the core idea, we want to build quantum models from different _strings of zeros and ones_ (genome), evaluate the performance of each one and take advantage of genetic algorithms to cross between them, mutate , apply natural selection and hopefully, after some generations have our best model to solve our classification problem. # ## Data # Let's see what's our dataset... Oh! It's <span style="color:blue">blue</span> and <span style="color:orange">orange</span> points as promised! # + # This Data example is copied from the CERN workshop: https://indico.cern.ch/event/893116/ # You can change this parameters n_samples = 100 X0 = np.array([[np.random.normal(loc=-1, scale=1), np.random.normal(loc=1, scale=1)] for i in range(n_samples//2)]) X1 = np.array([[np.random.normal(loc=1, scale=1), np.random.normal(loc=-1, scale=1)] for i in range(n_samples//2)]) X = np.concatenate([X0, X1], axis=0) Y = np.concatenate([-np.ones(int(n_samples/2)), np.ones(int(n_samples/2))], axis=0) data = list(zip(X, Y)) plt.scatter(X0[:,0], X0[:,1]) plt.scatter(X1[:,0], X1[:,1]) plt.show() # Split Data in train and test X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=1) data_train = list(zip(X_train, y_train)) data_test = list(zip(X_test, y_test)) # - # ## Genetic Algorithm: Agents to evolve # Now we build our Genetics part # + # Init conditions genome_type = '0101101101' in_str_len = len(genome_type) # You can tune this parameters population = 6 generations = 9 threshold = 0.97 # - # Let's create a class for the agents we want to evolve. We need 2 things in our agent: **genome** and **fitness**. The genome is going to be randomly generated each time an agent is created. class Agent: def __init__(self, length): self.string = ''.join(str(random.randint(0,1)) for _ in range(length)) self.fitness = -1 def __str__(self): return ' String: ' + str(self.string) + ' Fitness: ' + str(self.fitness) # 1. Create a population of agents # 2. Evaluate the fitness of each one # 3. Select between the best agents # 4. Breed between them # 5. Random mutate genes of the genome of the agent def ga(): agents = init_agents(population, in_str_len) for generation in range(generations): print("Generation: ", str(generation)) agents = fitness(agents) agents = selection(agents) agents = crossover(agents) agents = mutation(agents) if any(agent.fitness >= threshold for agent in agents): print("\U0001F986 Thereshold has been met! Winning genome: ", agents[0].string) x = np.array([0.1, 0.2], requires_grad=False) w = np.array([[1.1, -2], [2, -1], [-2, 1]]) a_more_complicated_genome_to_circuit(agents[0].string, x, w, True) break # ## Create a population of agents def init_agents(population, length): return [Agent(length) for _ in range(population)] # ## Fitness and definition of Quantum Model # This is the part where we build our quantum model from a gene, train it and evaluate it based on the area under the ROC. This value is going to correspond to the fitness of the agent. def a_more_complicated_genome_to_circuit(genome, x, w, verbose): @qml.qnode(dev) def circuit(x,w): # Encoding encode_gene = genome[:2] if encode_gene == "00": qml.templates.AngleEmbedding(x, wires=[0, 1]) elif encode_gene == "01": qml.templates.AmplitudeEmbedding(x, wires=[0, 1],pad=1,normalize=True) elif encode_gene == "10" or "11": qml.templates.IQPEmbedding(x, wires=[0, 1]) RZ_gene = genome[2:4] if RZ_gene == "01": qml.RZ(0.1,wires=0) elif RZ_gene == "10": qml.RZ(0.1,wires=1) elif RZ_gene == "11": qml.RZ(0.1,wires=0) qml.RZ(0.1,wires=1) Entanglement_gene = genome[4:5] if Entanglement_gene == "0": qml.templates.BasicEntanglerLayers(w, wires=[0, 1]) elif Entanglement_gene == "1": qml.RZ(w[0][0],wires=0) qml.RX(w[0][1],wires=1) qml.CNOT(wires=[0,1]) qml.RZ(-1*w[1][0],wires=1) qml.RX(-1*w[1][1],wires=0) qml.CNOT(wires=[0,1]) qml.RY(w[2][0],wires=0) qml.RX(-1*w[2][1],wires=1) T_gene = genome[5:7] if T_gene == "01": qml.T(wires=0) elif T_gene == "10": qml.T(wires=1) elif T_gene == "11": qml.T(wires=0) qml.T(wires=1) CNOT_gene = genome[7:8] if CNOT_gene == "1": qml.CNOT(wires=[0,1]) measurment_gene = genome[8:10] if measurment_gene == "00" or "11": measure = qml.PauliZ(wires=0) elif measurment_gene == "01": measure = qml.PauliY(wires=0) elif measurment_gene == "10": measure = qml.PauliX(wires=0) return qml.expval(measure) circuit(x,w) if verbose: print(circuit.draw()) else: return circuit(x,w) # To better understand the training part with plots and validation, check the `one_quantum_model.ipynb` jupyter notebook in the same repo. def fitness(agents): for agent in agents: global genome genome = agent.string # Cost function def loss(a, b): return (a - b)**2 def average_loss(w, data): c = 0 for x, y in data: #prediction = quantum_model(x, w) prediction = a_more_complicated_genome_to_circuit(genome, x, w, False) c += loss(prediction, y) return c/len(data) # Gradient gradient_fn = qml.grad(average_loss, argnum=0) # Trainning w_init = np.array([[1.1, -2], [2, -1], [-2, 1]]) w = np.array(w_init) history = [] # You can tune this parameter for i in range(5): w_new = w - 0.3*gradient_fn(w, data_train) avg_loss = average_loss(w_new, data_train) history.append(w_new) w = w_new def pred(w,X): y_pred = [] for x in X: #prediction = quantum_model(x, w) prediction = a_more_complicated_genome_to_circuit(genome, x, w, False) y_pred.append(prediction) return y_pred y_pred_train = pred(w,X_train) y_pred_test = pred(w,X_test) fpr_train, tpr_train, thresholds_train = metrics.roc_curve(y_train, y_pred_train) fpr, tpr, thresholds = metrics.roc_curve(y_test, y_pred_test) roc_auc_train = metrics.auc(fpr_train,tpr_train) roc_auc = metrics.auc(fpr,tpr) agent.fitness = roc_auc return agents # ## Selection def selection(agents): agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True) print('\n'.join(map(str, agents))) # Natural selection kill_param = 0.2 # take the top 20% of the individuals agents = agents[:int(kill_param * len(agents))] return agents # ## Cross over def crossover(agents): offspring = [] for _ in range( int((population - len(agents))/2)): # TODO: don't breed parents that are the same parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(in_str_len) child2 = Agent(in_str_len) split = random.randint(0,in_str_len) child1.string = parent1.string[0:split] + parent2.string[split:in_str_len] child2.string = parent2.string[0:split] + parent1.string[split:in_str_len] offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents # ## Mutation def mutation(agents): chance_of_mutation = 0.20 for agent in agents: for idx, param in enumerate(agent.string): if random.uniform(0.0,1.0) <= chance_of_mutation: agent.string = agent.string[0:idx] + str(random.randint(0,1)) + agent.string[idx+1:in_str_len] return agents # ## Run the genetic algorithm ga() print("\U0001F986 Qhack Qhack")
talking_duck.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd from keras.utils import to_categorical from sklearn.metrics import brier_score_loss from IPython.display import SVG import os VG_DIR = '~/vg' # probably you want to change this RSCRIPTS_FOLDER = os.path.join(VG_DIR, 'scripts') def encodePhred(x): out = -10 * np.log10(1.00000000001-x) out = out.astype(np.int64) out[out > 60] = 60 out[out <= 0] = 1 return out # - def bow_model2(): input_layer = 263 output_layer = 2 h_layer1 = 512 dropout1 = 0.25 h_layer2 = 256 dropout2 = 0.5 h_layer3 = 128 dropout3 = 0.5 model = Sequential() model.add(Dense(h_layer1, activation='relu', input_shape=(input_layer, ))) model.add(BatchNormalization()) model.add(Dropout(dropout1)) model.add(Dense(h_layer2, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(dropout2)) model.add(Dense(h_layer3, activation='relu', )) model.add(BatchNormalization()) model.add(Dense(output_layer, activation='softmax')) return model train_df = pd.read_csv("../data/train_gamcompare/csv/compared_mapped100_sim100..csv") train_df.head() y = to_categorical(train_df['correct'], 2) X = train_df.drop(columns=['correct', 'read', 'aligner']) X.shape model = bow_model2() model.summary() model.compile(loss='categorical_crossentropy', optimizer='SGD', metrics=['accuracy']) model.fit(X, y, batch_size=128, epochs=1, verbose=1, shuffle=True) test_df = pd.read_csv("../data/test_gamcompare/csv/tcompared_tmapped100_tsim100..csv") y_train_pred = model.predict(X) brier_score_loss(train_df['correct'].values, y_train_pred[:, 1]) brier_score_loss(train_df['correct'].values, train_df['mqp'].values) X_test = test_df.drop(columns=['correct', 'read', 'aligner']) y_test_pred = model.predict(X_test) brier_score_loss(test_df['correct'].values, y_test_pred[:, 1]) def output_tsv(df, pred): out_df = df.loc[:, ['correct', 'mq', 'aligner', 'read']] recal_df = out_df.copy() recal_df.loc[:, 'aligner'] = 'recal' recal_df.loc[:, 'mq'] = pred return out_df.append(recal_df, ignore_index=True) test_tsv = output_tsv(test_df, encodePhred(y_test_pred[:, 1])) test_tsv[test_tsv.aligner == "recal"].mq.hist(log=True) test_tsv.to_csv("bow_test.tsv", index=False, sep='\t') # !Rscript {RSCRIPTS_FOLDER}/plot-qq.R bow_test.tsv bow_test.svg # !Rscript {RSCRIPTS_FOLDER}/plot-roc.R bow_test.tsv roc-bow_test.svg SVG("bow_test.svg") SVG("roc-bow_test.svg")
notebooks/bow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Load the tensorboard notebook extension # %load_ext tensorboard # %reload_ext tensorboard # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 840, "status": "ok", "timestamp": 1562072276551, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15284233239426922637"}, "user_tz": 300} id="NqSTZm5UR9NS" outputId="5afa5e70-35ca-48cf-b255-fa6d12694551" # cd data/gpt-2/ # + colab={"base_uri": "https://localhost:8080/", "height": 561} colab_type="code" executionInfo={"elapsed": 19101, "status": "ok", "timestamp": 1562072297626, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15284233239426922637"}, "user_tz": 300} id="_wONoY04SGgL" outputId="eccda4fe-0849-4d91-879f-edc5ceac48a9" # !pip3 install -r requirements.txt # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 2219, "status": "ok", "timestamp": 1562072364186, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15284233239426922637"}, "user_tz": 300} id="v-FFfIovWj1P" outputId="9e48829f-e15d-4adb-96d8-0d91a34c4fd6" import fire import json import os import numpy as np import tensorflow as tf import regex as re from functools import lru_cache from statistics import median import argparse import time import tqdm from tensorflow.core.protobuf import rewriter_config_pb2 import glob tf.__version__ # + [markdown] colab_type="text" id="bQ3d7jgiXVFR" # # Encoding # + colab={} colab_type="code" id="aO819gXNXG9-" """Byte pair encoding utilities""" @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(model_name, models_dir): with open(os.path.join(models_dir, model_name, 'encoder.json'), 'r') as f: encoder = json.load(f) with open(os.path.join(models_dir, model_name, '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, ) # + [markdown] colab_type="text" id="y_aIf7Q7XHTy" # # Model # + colab={} colab_type="code" id="61cFgIMfamTx" class HParams(): n_vocab=50257 n_ctx=1024 n_embd=768 n_head=12 n_layer=12 def __init__(self, n_vocab, n_ctx, n_embd, n_head, n_layer): self.n_vocab = n_vocab self.n_ctx = n_ctx self.n_embd = n_embd self.n_head = n_head self.n_layer = n_layer # + colab={} colab_type="code" id="jpBqRQiuQRd4" def default_hparams(): return HParams( n_vocab=50257, n_ctx=1024, n_embd=768, n_head=12, n_layer=12, ) def shape_list(x): """Deal with dynamic shape in tensorflow cleanly.""" static = x.shape.as_list() dynamic = tf.shape(input=x) return [dynamic[i] if s is None else s for i, s in enumerate(static)] def gelu(x): return 0.5 * x * (1 + tf.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))) def norm(x, scope, *, axis=-1, epsilon=1e-5): """Normalize to mean = 0, std = 1, then do a diagonal affine transform.""" with tf.compat.v1.variable_scope(scope): n_state = x.shape[-1] g = tf.compat.v1.get_variable('g', [n_state], initializer=tf.compat.v1.constant_initializer(1), use_resource=False) b = tf.compat.v1.get_variable('b', [n_state], initializer=tf.compat.v1.constant_initializer(0), use_resource=False) u = tf.reduce_mean(input_tensor=x, axis=axis, keepdims=True) s = tf.reduce_mean(input_tensor=tf.square(x-u), axis=axis, keepdims=True) x = (x - u) * tf.math.rsqrt(s + epsilon) x = x*g + b return x def split_states(x, n): """Reshape the last dimension of x into [n, x.shape[-1]/n].""" *start, m = shape_list(x) return tf.reshape(x, start + [n, m//n]) def merge_states(x): """Smash the last two dimensions of x into a single dimension.""" *start, a, b = shape_list(x) return tf.reshape(x, start + [a*b]) def conv1d(x, scope, nf, *, w_init_stdev=0.02): with tf.compat.v1.variable_scope(scope): *start, nx = shape_list(x) w = tf.compat.v1.get_variable('w', [1, nx, nf], initializer=tf.compat.v1.random_normal_initializer(stddev=w_init_stdev), use_resource=False) b = tf.compat.v1.get_variable('b', [nf], initializer=tf.compat.v1.constant_initializer(0), use_resource=False) c = tf.reshape(tf.matmul(tf.reshape(x, [-1, nx]), tf.reshape(w, [-1, nf]))+b, start+[nf]) return c def attention_mask(nd, ns, *, dtype): """1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd), but doesn't produce garbage on TPUs. """ i = tf.range(nd)[:,None] j = tf.range(ns) m = i >= j - ns + nd return tf.cast(m, dtype) def attn(x, scope, n_state, *, past, hparams): assert x.shape.ndims == 3 # Should be [batch, sequence, features] assert n_state % hparams.n_head == 0 if past is not None: assert past.shape.ndims == 5 # Should be [batch, 2, heads, sequence, features], where 2 is [k, v] def split_heads(x): # From [batch, sequence, features] to [batch, heads, sequence, features] return tf.transpose(a=split_states(x, hparams.n_head), perm=[0, 2, 1, 3]) def merge_heads(x): # Reverse of split_heads return merge_states(tf.transpose(a=x, perm=[0, 2, 1, 3])) def mask_attn_weights(w): # w has shape [batch, heads, dst_sequence, src_sequence], where information flows from src to dst. _, _, nd, ns = shape_list(w) b = attention_mask(nd, ns, dtype=w.dtype) b = tf.reshape(b, [1, 1, nd, ns]) w = w*b - tf.cast(1e10, w.dtype)*(1-b) return w def multihead_attn(q, k, v): # q, k, v have shape [batch, heads, sequence, features] w = tf.matmul(q, k, transpose_b=True) w = w * tf.math.rsqrt(tf.cast(v.shape[-1], w.dtype)) w = mask_attn_weights(w) w = tf.nn.softmax(w, axis=-1) a = tf.matmul(w, v) return a with tf.compat.v1.variable_scope(scope): c = conv1d(x, 'c_attn', n_state*3) q, k, v = map(split_heads, tf.split(c, 3, axis=2)) present = tf.stack([k, v], axis=1) if past is not None: pk, pv = tf.unstack(past, axis=1) k = tf.concat([pk, k], axis=-2) v = tf.concat([pv, v], axis=-2) a = multihead_attn(q, k, v) a = merge_heads(a) a = conv1d(a, 'c_proj', n_state) return a, present def mlp(x, scope, n_state, *, hparams): with tf.compat.v1.variable_scope(scope): nx = x.shape[-1] h = gelu(conv1d(x, 'c_fc', n_state)) h2 = conv1d(h, 'c_proj', nx) return h2 def block(x, scope, *, past, hparams): with tf.compat.v1.variable_scope(scope): nx = x.shape[-1] a, present = attn(norm(x, 'ln_1'), 'attn', nx, past=past, hparams=hparams) x = x + a m = mlp(norm(x, 'ln_2'), 'mlp', nx*4, hparams=hparams) x = x + m return x, present def past_shape(*, hparams, batch_size=None, sequence=None): return [batch_size, hparams.n_layer, 2, hparams.n_head, sequence, hparams.n_embd // hparams.n_head] def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims) def positions_for(tokens, past_length): batch_size = tf.shape(input=tokens)[0] nsteps = tf.shape(input=tokens)[1] return expand_tile(past_length + tf.range(nsteps), batch_size) def model(hparams, X, past=None, scope='model', reuse=tf.compat.v1.AUTO_REUSE): with tf.compat.v1.variable_scope(scope, reuse=reuse): results = {} batch, sequence = shape_list(X) wpe = tf.compat.v1.get_variable('wpe', [hparams.n_ctx, hparams.n_embd], initializer=tf.compat.v1.random_normal_initializer(stddev=0.01), use_resource=False) wte = tf.compat.v1.get_variable('wte', [hparams.n_vocab, hparams.n_embd], initializer=tf.compat.v1.random_normal_initializer(stddev=0.02), use_resource=False) past_length = 0 if past is None else tf.shape(input=past)[-2] h = tf.gather(wte, X) + tf.gather(wpe, positions_for(X, past_length)) # Transformer presents = [] pasts = tf.unstack(past, axis=1) if past is not None else [None] * hparams.n_layer assert len(pasts) == hparams.n_layer for layer, past in enumerate(pasts): h, present = block(h, 'h%d' % layer, past=past, hparams=hparams) presents.append(present) results['present'] = tf.stack(presents, axis=1) h = norm(h, 'ln_f') # Language model loss. Do tokens <n predict token n? h_flat = tf.reshape(h, [batch*sequence, hparams.n_embd]) logits = tf.matmul(h_flat, wte, transpose_b=True) logits = tf.reshape(logits, [batch, sequence, hparams.n_vocab]) results['logits'] = logits return results # + [markdown] colab_type="text" id="A_rmLotVXbbw" # # Sample from Model # + colab={} colab_type="code" id="45t7syAbXaPb" def top_k_logits(logits, k): if k == 0: # no truncation return logits def _top_k(): values, _ = tf.nn.top_k(logits, k=k) min_values = values[:, -1, tf.newaxis] return tf.compat.v1.where( logits < min_values, tf.ones_like(logits, dtype=logits.dtype) * -1e10, logits, ) return tf.cond( pred=tf.equal(k, 0), true_fn=lambda: logits, false_fn=lambda: _top_k(), ) def sample_sequence(*, hparams, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0): if start_token is None: assert context is not None, 'Specify exactly one of start_token and context!' else: assert context is None, 'Specify exactly one of start_token and context!' context = tf.fill([batch_size, 1], start_token) def step(hparams, tokens, past=None): lm_output = model(hparams=hparams, X=tokens, past=past, reuse=tf.compat.v1.AUTO_REUSE) logits = lm_output['logits'][:, :, :hparams.n_vocab] presents = lm_output['present'] presents.set_shape(past_shape(hparams=hparams, batch_size=batch_size)) return { 'logits': logits, 'presents': presents, } def body(past, prev, output): next_outputs = step(hparams, prev, past=past) logits = next_outputs['logits'][:, -1, :] / tf.cast(temperature, dtype=tf.float32) logits = top_k_logits(logits, k=top_k) samples = tf.random.categorical(logits=logits, num_samples=1, dtype=tf.int32) return [ next_outputs['presents'] if past is None else tf.concat([past, next_outputs['presents']], axis=-2), samples, tf.concat([output, samples], axis=1) ] past, prev, output = body(None, context, context) def cond(*args): return True _, _, tokens = tf.while_loop( cond=cond, body=body, maximum_iterations=length - 1, loop_vars=[ past, prev, output ], shape_invariants=[ tf.TensorShape(past_shape(hparams=hparams, batch_size=batch_size)), tf.TensorShape([batch_size, None]), tf.TensorShape([batch_size, None]), ], back_prop=False, ) return tokens # + colab={} colab_type="code" id="j2FqjqTMksna" from pathlib import Path def load_dataset(enc, path, combine): paths = [] if os.path.isfile(path): # Simple file paths.append(path) elif os.path.isdir(path): # Directory for i, (dirpath, _, fnames) in enumerate(os.walk(path)): if i % 10000 == 0: print(i) for fname in fnames: paths.append(os.path.join(dirpath, fname)) # if i == 500000: # print("Breaking") # break else: # Assume glob paths = glob.glob(path) token_chunks = [] raw_text = '' for i, path in enumerate(tqdm.tqdm(paths)): # if 'after.java' not in path: # continue try: with open(path, 'r') as fp: raw_text += fp.read() tokens = np.stack(enc.encode(raw_text)) token_chunks.append(tokens) raw_text = '' except: print(e) # if i >= 500000: # break return token_chunks def binary_search(f, lo, hi): if f(lo) or not f(hi): return None while hi > lo + 1: mid = (lo + hi) // 2 if f(mid): hi = mid else: lo = mid return hi class Sampler(object): """Fairly samples a slice from a set of variable sized chunks. 'Fairly' means that the distribution is the same as sampling from one concatenated chunk, but without crossing chunk boundaries.""" def __init__(self, chunks, seed=None): self.chunks = chunks self.total_size = sum(chunk.shape[0] for chunk in chunks) self.boundaries = [0] for i in range(len(chunks)): self.boundaries.append(self.boundaries[-1] + chunks[i].shape[0]) self.rs = np.random.RandomState(seed=seed) def sample(self, length): assert length < self.total_size // len( self.chunks ), "Dataset files are too small to sample {} tokens at a time".format( length) while True: index = self.rs.randint(0, self.total_size - length - 1) i = binary_search(lambda j: self.boundaries[j] > index, 0, len(self.boundaries) - 1) - 1 if self.boundaries[i + 1] > index + length: within_chunk = index - self.boundaries[i] return self.chunks[i][within_chunk:within_chunk + length] # + colab={} colab_type="code" id="PLkRBQSysTKq" class Args(): def __init__(self, dataset, model_name, combine, batch_size, learning_rate, optimizer, noise, top_k, top_p, run_name, sample_every, sample_length, sample_num, save_every, val_dataset, val_batch_size, val_batch_count, val_every, pretrained, iterations): self.dataset = dataset self.model_name = model_name self.combine = combine self.batch_size = batch_size self.learning_rate = learning_rate self.optimizer = optimizer self.noise = noise self.top_k = top_k self.top_p = top_p self.run_name = run_name self.sample_every = sample_every self.sample_length = sample_length self.sample_num = sample_num self.save_every = save_every self.val_dataset = val_dataset self.val_batch_size = val_batch_size self.val_batch_count = val_batch_count self.val_every = val_every self.pretrained = pretrained self.iterations = iterations # - args = Args( dataset="../methods/DATA00M_[god-r]", model_name="117M", combine=50000, batch_size=1, # DO NOT TOUCH. INCREASING THIS WILL RAIN DOWN HELL FIRE ONTO YOUR COMPUTER. learning_rate=0.00002, optimizer="sgd", noise=0.0, top_k=40, top_p=0.0, run_name="run4", sample_every=100, sample_length=1023, sample_num=1, save_every=1000, val_dataset=None, val_batch_size=1, val_batch_count=40, val_every=100, pretrained=False, iterations=200000 ) enc = get_encoder(args.model_name, "models") data_set = load_dataset(enc, args.dataset, args.combine) len(data_set) # + DATA_SET_SIZE = len(data_set) TRN_SET_SIZE = int(DATA_SET_SIZE * 0.8) VAL_SET_SIZE = int(DATA_SET_SIZE * 0.1) TST_SET_SIZE = int(DATA_SET_SIZE * 0.1) trn_set = data_set[:TRN_SET_SIZE] val_set = data_set[TRN_SET_SIZE:TRN_SET_SIZE + VAL_SET_SIZE] tst_set = data_set[-TST_SET_SIZE:] DATA_SET_SIZE, len(trn_set), len(val_set), len(tst_set) # - # + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" executionInfo={"elapsed": 705262, "status": "error", "timestamp": 1562073894102, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15284233239426922637"}, "user_tz": 300} id="cfjs2UHNkN5J" outputId="0a2ea262-c6af-4ac5-b102-80e1e417b19f" CHECKPOINT_DIR = 'checkpoint' SAMPLE_DIR = 'samples' def maketree(path): try: os.makedirs(path) except: pass def randomize(context, hparams, p): if p > 0: mask = tf.random.uniform(shape=tf.shape(input=context)) < p noise = tf.random.uniform(shape=tf.shape(input=context), minval=0, maxval=hparams.n_vocab, dtype=tf.int32) return tf.compat.v1.where(mask, noise, context) else: return context def main(): enc = get_encoder(args.model_name, "models") hparams = default_hparams() if args.sample_length > hparams.n_ctx: raise ValueError( "Can't get samples longer than window size: %s" % hparams.n_ctx) config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True config.graph_options.rewrite_options.layout_optimizer = rewriter_config_pb2.RewriterConfig.OFF with tf.compat.v1.Session(config=config) as sess: context = tf.compat.v1.placeholder(tf.int32, [args.batch_size, None]) context_in = randomize(context, hparams, args.noise) output = model(hparams=hparams, X=context_in) # if args.val_every > 0: val_context = tf.compat.v1.placeholder(tf.int32, [args.val_batch_size, None]) val_output = model(hparams=hparams, X=val_context) tf_sample = sample_sequence( hparams=hparams, length=args.sample_length, context=context, batch_size=args.batch_size, temperature=1.0, top_k=args.top_k) all_vars = [v for v in tf.compat.v1.trainable_variables() if 'model' in v.name] train_vars = all_vars if args.optimizer == 'adam': opt = tf.compat.v1.train.AdamOptimizer(learning_rate=args.learning_rate) elif args.optimizer == 'sgd': opt = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=args.learning_rate) else: exit('Bad optimizer:', args.optimizer) ## Collect Metrics for Tensorboard with tf.compat.v1.name_scope('metrics'): with tf.compat.v1.name_scope('train'): trn_loss = tf.reduce_mean( input_tensor=tf.nn.sparse_softmax_cross_entropy_with_logits( labels=context[:, 1:], logits=output['logits'][:, :-1])) trn_loss_summ = tf.compat.v1.summary.scalar('loss', trn_loss) trn_med_ph = tf.compat.v1.placeholder(tf.float32,shape=None,name='median') trn_med_summ = tf.compat.v1.summary.scalar('median', trn_med_ph) trn_mean_ph = tf.compat.v1.placeholder(tf.float32,shape=None,name='mean') trn_mean_summ = tf.compat.v1.summary.scalar('mean', trn_mean_ph) with tf.compat.v1.name_scope('valid'): val_loss = tf.reduce_mean( input_tensor=tf.nn.sparse_softmax_cross_entropy_with_logits( labels=val_context[:, 1:], logits=val_output['logits'][:, :-1])) val_loss_summ = tf.compat.v1.summary.scalar('loss', val_loss) val_med_ph = tf.compat.v1.placeholder(tf.float32,shape=None,name='median') val_med_summ = tf.compat.v1.summary.scalar('median', val_med_ph) trn_summaries = tf.compat.v1.summary.merge([trn_loss_summ, trn_med_summ, trn_mean_summ]) val_summaries = tf.compat.v1.summary.merge([val_loss_summ, val_med_summ]) # summaries = tf.compat.v1.summary.merge_all() opt_grads = tf.gradients(ys=trn_loss, xs=train_vars) opt_grads = list(zip(opt_grads, train_vars)) opt_apply = opt.apply_gradients(opt_grads) trn_summ_log = tf.compat.v1.summary.FileWriter(os.path.join(CHECKPOINT_DIR, args.run_name, 'train')) val_summ_log = tf.compat.v1.summary.FileWriter(os.path.join(CHECKPOINT_DIR, args.run_name, 'valid')) # write_op = tf.compat.v1.summary.merge_all() saver = tf.compat.v1.train.Saver( var_list=all_vars, max_to_keep=5, keep_checkpoint_every_n_hours=2) sess.run(tf.compat.v1.global_variables_initializer()) ckpt = tf.train.latest_checkpoint( os.path.join(CHECKPOINT_DIR, args.run_name)) if ckpt is None: # Get fresh GPT weights if new run. ckpt = tf.train.latest_checkpoint( os.path.join('models', args.model_name)) if args.pretrained == True: print('Loading checkpoint', ckpt) saver.restore(sess, ckpt) print('Loading dataset...') data_sampler = Sampler(trn_set) if args.val_every > 0: val_chunks = val_set print('dataset has', data_sampler.total_size, 'tokens') print('Training...') if args.val_every > 0: # Sample from validation set once with fixed seed to make # it deterministic during training as well as across runs. val_data_sampler = Sampler(val_chunks, seed=1) val_batches = [[val_data_sampler.sample(128) for _ in range(args.val_batch_size)] for _ in range(args.val_batch_count)] counter = 1 counter_path = os.path.join(CHECKPOINT_DIR, args.run_name, 'counter') if os.path.exists(counter_path): # Load the step number if we're resuming a run # Add 1 so we don't immediately try to save again with open(counter_path, 'r') as fp: counter = int(fp.read()) + 1 def save(): maketree(os.path.join(CHECKPOINT_DIR, args.run_name)) print( 'Saving', os.path.join(CHECKPOINT_DIR, args.run_name, 'model-{}').format(counter)) saver.save( sess, os.path.join(CHECKPOINT_DIR, args.run_name, 'model'), global_step=counter) with open(counter_path, 'w') as fp: fp.write(str(counter) + '\n') def generate_samples(): print('Generating samples...') context_tokens = data_sampler.sample(1) all_text = [] index = 0 while index < args.sample_num: out = sess.run( tf_sample, feed_dict={context: args.batch_size * [context_tokens]}) for i in range(min(args.sample_num - index, args.batch_size)): text = enc.decode(out[i]) text = '======== SAMPLE {} ========\n{}\n'.format( index + 1, text) all_text.append(text) index += 1 print(text) maketree(os.path.join(SAMPLE_DIR, args.run_name)) with open( os.path.join(SAMPLE_DIR, args.run_name, 'samples-{}').format(counter), 'w') as fp: fp.write('\n'.join(all_text)) def validation(): print('Calculating validation loss...') losses = [] for batch in tqdm.tqdm(val_batches): losses.append(sess.run(val_loss, feed_dict={val_context: batch})) v_val_loss = np.mean(losses) v_summary = sess.run(val_summaries, feed_dict={val_loss: v_val_loss, val_med_ph: median(losses)}) val_summ_log.add_summary(v_summary, counter) val_summ_log.flush() print( '[{counter} | {time:2.2f}] validation loss = {loss:2.2f}' .format( counter=counter, time=time.time() - start_time, loss=v_val_loss)) def sample_batch(): return [data_sampler.sample(128) for _ in range(args.batch_size)] avg_loss = (0.0, 0.1) losses = [0.0] start_time = time.time() try: for _ in range(args.iterations): if counter % args.save_every == 0: save() if counter % args.sample_every == 0: generate_samples() if args.val_every > 0 and (counter % args.val_every == 0 or counter == 1): validation() if _ == 0: avg = 0 else: avg = avg_loss[0] / avg_loss[1] (_, v_loss, v_summary) = sess.run( (opt_apply, trn_loss, trn_summaries), feed_dict={context: sample_batch(), trn_med_ph: median(losses), trn_mean_ph: avg}) losses.append(v_loss) trn_summ_log.add_summary(v_summary, counter) avg_loss = (avg_loss[0] * 0.99 + v_loss, avg_loss[1] * 0.99 + 1.0) print( '[{counter} | {time:2.2f}] loss={loss:2.2f} avg={avg:2.2f}' .format( counter=counter, time=time.time() - start_time, loss=v_loss, avg=avg_loss[0] / avg_loss[1])) counter += 1 except KeyboardInterrupt: print('interrupted') save() if __name__ == '__main__': main() # - # cd data/gpt-2 # ! ls # %tensorboard --logdir ./checkpoint/run3/ # ! kill 21525 # !curl -X POST -H 'Content-type: application/json' --data '{"text":"from: semeru tower 1\nstatus: model finished training"}' https://hooks.slack.com/services/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 # %tensorboard --logdir ./checkpoint/run1 # # Self Supervised Experimentation # + def interact_model( model_name='117M', seed=None, nsamples=1, batch_size=1, length=None, temperature=1, top_k=0, models_dir='models', ): """ Interactively run the model :model_name=117M : String, which model to use :seed=None : Integer seed for random number generators, fix seed to reproduce results :nsamples=1 : Number of samples to return total :batch_size=1 : Number of batches (only affects speed/memory). Must divide nsamples. :length=None : Number of tokens in generated text, if None (default), is determined by model hyperparameters :temperature=1 : Float value controlling randomness in boltzmann distribution. Lower temperature results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive. Higher temperature results in more random completions. :top_k=0 : Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting meaning no restrictions. 40 generally is a good value. :models_dir : path to parent folder containing model subfolders (i.e. contains the <model_name> folder) """ models_dir = os.path.expanduser(os.path.expandvars(models_dir)) if batch_size is None: batch_size = 1 assert nsamples % batch_size == 0 enc = get_encoder(model_name, models_dir) hparams = default_hparams() # with open(os.path.join(models_dir, model_name, 'hparams.json')) as f: # hparams.override_from_dict(json.load(f)) if length is None: length = hparams.n_ctx // 2 elif length > hparams.n_ctx: raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx) with tf.compat.v1.Session(graph=tf.Graph()) as sess: context = tf.compat.v1.placeholder(tf.int32, [batch_size, None]) np.random.seed(seed) tf.compat.v1.set_random_seed(seed) output = sample_sequence( hparams=hparams, length=length, context=context, batch_size=batch_size, temperature=temperature, top_k=top_k ) saver = tf.compat.v1.train.Saver() ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, model_name)) saver.restore(sess, ckpt) tf.compat.v1.global_variables_initializer() # init = tf.compat.v1.global_variables_initializer() # sess.run(init) while True: raw_text = input("Model prompt >>> ") while not raw_text: print('Prompt should not be empty!') raw_text = input("Model prompt >>> ") context_tokens = enc.encode(raw_text) generated = 0 for _ in range(nsamples // batch_size): print("Output Obj: ", output) print("Context: ", [context_tokens for _ in range(batch_size)]) # out = output #predict(output, length, [context_tokens for _ in range(batch_size)]) out = sess.run(output, feed_dict={ context: [context_tokens for _ in range(batch_size)] })[:, len(context_tokens):] for i in range(batch_size): generated += 1 text = enc.decode(out[i]) print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40) print(text) print("=" * 80) interact_model(model_name='117M', seed=None, nsamples=1, batch_size=1, length=None, temperature=1, top_k=40, models_dir='models') # if __name__ == '__main__': # fire.Fire(interact_model) # -
main/nbs/poc/gpt-2/tf2/gpt2_cleaned.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import piplite await piplite.install('ipyleaflet'); # + from ipyleaflet import Map, basemaps, basemap_to_tiles m = Map( basemap=basemap_to_tiles(basemaps.OpenStreetMap.Mapnik), center=(48.204793, 350.121558), zoom=3 ) m
docs/source/ipyleaflet.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .sos # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: SoS # language: sos # name: sos # --- # + [markdown] kernel="SoS" # # How to execute other workflows in a SoS step # + [markdown] kernel="SoS" # * **Difficulty level**: intermediate # * **Time need to lean**: 10 minutes or less # * **Key points**: # * Action `sos_run` execute a workflow # * Multiple workflows can be executed in parallel if they are specified as a list to action `sos_run` # # + [markdown] kernel="SoS" # ### Action `sos_run` # + [markdown] kernel="SoS" # Action `sos_run(workflow=None, targets=None, shared=[], source=None, args={}, **kwargs)` executes a specified workflow from the current (default) or specified SoS script (`source`). The workflow can be a single workflow, a subworkflow (e.g. `A_-10`), a combined workflow (e.g. `A + B`), or a workflow that is constructed to generate `targets`. The workflow # # * Takes `_input` of the parental step as the input of the first step of the subworkflow # * Takes `args` (a dictionary) and `**kwargs` as parameters as if they are specified from command line # * Copies variables specified in `shared` (a string or a list of string) to the subworkflow if they exist in the parental namespace # * Returns variables defined in `shared` to the parental namespace after the completion of the workflow # # `sos_run` would be executed in a separate process in batch mode, and would be executed in the same process in interactive mode, so parameter `shared` is only needed for batch execution. # + [markdown] kernel="SoS" # The simplest use of action `sos_run` is for the execution of one or more workflows. For example, # + kernel="SoS" # %run [A] print(step_name) [B] print(step_name) [default] sos_run('A + B') # + [markdown] kernel="SoS" # The subworkflows are executed separately and only takes the `_input` of the step as the `input` of the workflow. For example, # + kernel="SoS" # %sandbox # %run !touch a.txt b.txt [process] print(f"Handling {_input}") [default] input: 'a.txt', 'b.txt', group_by=1 sos_run('process') # + [markdown] kernel="SoS" # If you would like to send one or more variables to the subworkflow or return a variable from the execution of subworkflow, you can specify them with the `shared` variable. The return variable part is a bit tricky here because you can only return workflow level variable that are usually `shared` from a step of the subworkflow. For example, # + kernel="SoS" # %sandbox # %run [process] print(f"Working with seed {seed}") [default] for seed in range(5): sos_run('process', seed=seed) # + kernel="SoS" # %sandbox # %run [process: shared='result'] result = 100 [default] sos_run('process') print(f"Result from subworkflow process is {result}") # + [markdown] kernel="SoS" # If the subworkflow accepts parameters, they can be specified using keyword arguments or as a dictionary for parameter `args` of the `sos_run` function. The subworkflow would take values from parameters as if they are passed from command line. # # For example, the following workflow defines parameter `cutoff` with default value 10. When it is executed without command line option, the default value is used. # + kernel="SoS" # %sandbox # %run [default] parameter: cutoff=10 print(f"Process with cutoff={cutoff}") [batch] for value in range(2, 10, 2): sos_run('default', cutoff=value) # + [markdown] kernel="SoS" # Command line argument could be used to specify a different `cutoff` value: # + kernel="SoS" # %sandbox # %rerun --cutoff 4 # + [markdown] kernel="SoS" # Now, if we run the `batch` workflow, which calls the `default` workflow with parameter `cutoff`, the `parameter: cutoff=10` statement takes the passed value as if it were specified from command line. # + kernel="SoS" # %sandbox # %rerun batch # + [markdown] kernel="SoS" # Note that the parameters could also be specified with parameter `args`, # + kernel="SoS" # %sandbox # %run batch [default] parameter: cutoff=10 print(f"Process with cutoff={cutoff}") [batch] for value in range(2, 10, 2): sos_run('default', args={'cutoff': value}) # + [markdown] kernel="SoS" # although the keyword arguments are usually easier to use. # + [markdown] kernel="SoS" # Action `sos_run` cannot be used in `task` (see [Remote Execution](Remote_Execution.html) for details) because tasks are designed to be executed independently of the workflow. # + [markdown] kernel="SoS" # ### Nested workflow (`sos_run`) <a id="Nested_workflow_sos_run"></a> # + [markdown] kernel="SoS" # SoS also supports nested workflow in which a complete workflow is treated as part of a step process. # The workflow is execute by SoS action `sos_run`, e.g. # # ```python # sos_run('A') # execute workflow A # sos_run('A + B') # execute workflow B after A # sos_run('D:-10 + C') # execute up to step 10 of D and workflow C # # # execute user-specified aligner and caller workflows # sos_run(f'{aligner} + {caller}') # ``` # + [markdown] kernel="SoS" # In its simplest form, nested workflow allows you to define another workflow from existing ones. For example, # + kernel="SoS" # %preview -n forward.dot # %run -d forward.dot [align_10] print(step_name) [align_20] print(step_name) [call_10] print(step_name) [call_20] print(step_name) [default] sos_run('align+call') # + [markdown] kernel="SoS" # defines a nested workflow that combines workflows `align` and `call` so that the workflow will by default execute two workflows, but can also execute one of them as separate workflows `align` and `call`. This example also uses option `-d` to output the execution path of the workflow to a file, and magic `%preview` to preview the path. # + [markdown] kernel="SoS" # Nested workflow also allows you to define multiple mini-workflows and connect them freely. For example # # ```python # [a_1] # [a_2] # [b] # [c] # [d_1] # sos_run('a+b') # [d_2] # sos_run('a+c') # ``` # # defines workflows `d` that will execute steps `d_1`, `a_1`, `a_2`, `b_0`, `d_2`, `a_1`, `a_2`, and `c_0`. # + [markdown] kernel="SoS" # A `parameter` statement usually gets its value from command line. However, when a workflow is executed as a subworkflow by action `sos_run`, the `parameter` statement can get its value from the `args` or `**kwargs` parameters of `sos_run`. # # For example, when the `default` workflow of the following script is executed, `cutoff` takes its default value of `10`. # + kernel="SoS" # %run [default_1] parameter: cutoff=10 run: expand=True echo {cutoff} [batch] for cutoff in range(3): sos_run('default', cutoff=cutoff) # + [markdown] kernel="SoS" # A command line argument can be used to set this parameter to `8`, # + kernel="SoS" # %rerun --cutoff 8 # + [markdown] kernel="SoS" # Now, if the workflow is called as a subworkflow of step `batch`, `sos_run` set up the environment so that the statement `parameter: cutoff=10` gets a different cutoff value pass by `sos_run`. # + kernel="SoS" # %rerun batch # + [markdown] kernel="SoS" # Because `sos_run` is simply a SoS action and takes a string as its parameter, it allows very flexible ways to compose (e.g. determine workflow from command line arguments) and execute (e.g. repeated execution of workflows with different options or input files) complex workflows. Furthermore, the workflows can be defined in another file so you can organize your workflow as a master workflow that calls nested workflows defined in other files. # # For example, suppose we create a workflow with two steps: # + kernel="SoS" # %preview -n nested.sos # %run [10] report: output='nested.sos' [nested_20] print(f"This is {step_name} of a nested workflow") [nested_30] print(f"This is {step_name} of a nested workflow") # + [markdown] kernel="SoS" # Then, we can execute this workflow with a `sos_run` action as follows # + kernel="SoS" sos_run('nested', source='nested.sos') # + [markdown] kernel="SoS" # ## Further reading # # *
src/user_guide/nested_workflow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.5 64-bit (''tf2.2_gpu'': conda)' # metadata: # interpreter: # hash: 90cf5eea794022e22fa180c9282a29d9e5d401b5dd5d691c4b114a9f7de9ba53 # name: 'Python 3.8.5 64-bit (''tf2.2_gpu'': conda)' # --- # + tags=[] from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" import platform import keras import tensorflow as tf print("python version :" + platform.python_version()) print("keras version :" + keras.__version__) print("tensorflow version :" + tf.__version__) # + tags=[] from matplotlib import pyplot as plt from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images.shape train_labels.shape test_images.shape test_labels.shape img = train_images[100] plt.imshow(img, cmap=plt.cm.binary) # + tags=[] from keras import models from keras import layers from keras.utils import to_categorical network = keras.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28*28,))) network.add(layers.Dense(10, activation='softmax')) network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'] ) train_images = train_images.reshape(60000, 28*28) train_images = train_images.astype('float32')/255 train_labels = to_categorical(train_labels) test_images = test_images.reshape(10000, 28*28) test_images = test_images.astype('float32')/255 test_labels = to_categorical(test_labels) network.fit(train_images, train_labels, epochs=5, batch_size=128) # + tags=[] test_loss, test_acc = network.evaluate(test_images, test_labels) print("test_loss : ", test_loss) print("test_acc : ", test_acc) # -
2.1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + [markdown] deletable=true editable=true # # Final Project - Predicting Movie Genres! # # ![Movie genre header](genre_header.jpg) # # Welcome to the final project of CS109b. # # The overall theme of the final project is movie data with a focus on movie genre prediction, because it is an area where we are all more or less application domain experts. First, you will explore your data and the challenges of the problem by exploratory data analysis. Use visualizations to find features that correlate with movie genres. These can be extracted from the movie posters, or meta data, or other data you gather, for example plot summaries or even movie transcripts. You will then compare traditional statistical or machine learning methods like generalized additive models, random forest, Bayesian prediction methods, boosting, and SVM, to deep learning models for movie genre prediction. # # For this project you will work in teams of 3-4 people and there are weekly milestones to guide you along the way. Even though the milestones are graded, they are mainly in place to make sure you stay in contact with your TF and make progress with the project. Throughout the project you also have room for creativity and to pursue your own ideas. While you need to hand in the milestones at the appropriate due date, there is nothing preventing you from working on a later milestone ahead of time. We suggest that you read through the whole project and all milestones in the beginning to be able to plan ahead. The project is pretty open-ended, so you can be creative and let your data science knowledge shine! # # For each milestone you will submit a notebook, in raw (`.ipynb`) and PDF formats, containing the deliverables of that week and the extra work you did so far. The notebooks need to contain your code, comments, explanations, thoughts, and visualizations. The final deliverables are a two-minute screencast, a report in paper style for a general data science audience, and all your data and code that you developed throughout the project. # # Below is a description of the data and the milestones with their due dates. All work is due by 11:59PM on the due date unless otherwise specified. We expect you to have the mandatory parts finished by the milestone due dates, and there will be no extensions. However, we strongly encourage you to plan ahead. For example, you need to think about the classification task early on to plan how you want to assemble your training data, and it is beneficial to start the deep learning work as early as possible. There is nothing hindering you to already train a model in the EDA phase to get a better feel for what challenges might lie ahead with the data. You should also see the milestone requirements as a basis for your own creativity, and we expect that most of you will go beyond the mandatory deliverables. For example, if you have a great idea about an interesting question that has to do with movie genre, but cannot be answered with the data from TMDb or IMDb, feel free to gather more data from somewhere else. # # We provide a data interface in Python, because it is convenient for IMDb, and we will use Python for the deep learning part. Specifically we will use Keras, a deep learning library that provides a high level interface to Google's Tensorflow framework for deep learning. However, if you feel that you prefer to do some of the work, e.g., visualizations or data cleanup, in R then feel free to use it. You can also use Spark to preprocess your data, especially if you collect large amounts of it from other sources. # # *Important:* Your grade for a milestone will depend on the required deliverables you submit at the due date for that milestone. But every milestone, especially the final project submission, can contain additional cool work you did that goes beyond the deliverables spelled out below. # # + [markdown] deletable=true editable=true # ### Logistics # # Please adhere to the following guidelines for all submissions: # - one submission per team # - notebooks should be submitted as PDF and as raw (`.ipynb`) version # - all notebooks should be executed so they contain relevant visualizations, and other results # - try to make it as easy as possible for the TFs to get all relevant information about your work # - do not submit big data sets, please provide a readme file with a link instead # - the final report should also be submitted as pdf # + [markdown] deletable=true editable=true # ### Movie Data: # # The project is based on two different sources of movie data: [IMDb](http://www.imdb.com/) and [TMDb](https://www.themoviedb.org/). TMDb is great, because it provides the movie posters in addition to the metadata. This is crucial for the deep learning part, in which you will try to predict movie genres from posters. IMDb has more metadata available and will supplement the TMDb data you have. # # TMDb provides an easy to use [API](https://www.themoviedb.org/documentation/api) that allows you to download the data selectively. IMDb does not provide an API, but there is a Python interface available to access the metadata. We will use [IMDbPY](http://imdbpy.sourceforge.net/), which is already installed on the AMI and virtual box images for your convenience. # # *Important*: Please remember to limit your data rate when obtaining the data. Play nicely and do not just spam servers as fast as you can. This will prevent your IP from getting banned. The easiest way to do this is to use the [sleep](http://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python) function in Python. # # + [markdown] deletable=true editable=true # ### Milestone 1: Getting to know your data, due Wednesday, April 5, 2017 # # In the beginning you should get acquainted with the data sources and do some EDA. Sign up for the TMDb [API](https://www.themoviedb.org/documentation/api), and try to download the poster of your favorite movie from within your notebook. Compare the genre entries of IMDb and TMDb for this movie and see if they are the same. Think about and write down some questions that you would like to answer in the following weeks. Keep the storytelling aspect of your final report in mind and do some pen and paper sketches about the visualizations you would like to produce. Include photographs of those sketches in your notebook. # # Most of the time a data scientist spends on a project is spent on cleaning the data. We are lucky that the data we have is already pretty clean. The Python interface to the IMDb ftp files does a lot of the additional work of cleaning as well. However, you will notice that the genre list for each movie from both databases can have different lengths. This needs to be changed in order to train a model to predict the movie genre. It is up to you to think about possible ways to address this problem and to implement one of them. There is no absolute right answer here. It depends on your interests and which questions you have in mind for the project. # # Optionally, you could also scrape additional data sources, such as Wikipedia, to obtain plot summaries. That data may give you additional useful features for genre classification. # # To guide your decision process, provide at least one visualization of how often genres are mentioned together in pairs. Your visualization should clearly show if a horror romance is more likely to occur in the data than a drama romance. # # The notebook to submit for this milestone needs to at least include: # # - API code to access the genre and movie poster path of your favorite movie # - Genre for this movie listed by TMDb and IMDb # - A list of the 10 most popular movies of 2016 from TMDb and their genre obtained via the API # - Comments on what challenges you see for predicting movie genre based on the data you have, and how to address them # - Code to generate the movie genre pairs and a suitable visualization of the result # - Additional visualization sketches and EDA with a focus on movie genres # - A list of questions you could answer with this and related data. Get creative here! # # The EDA questions do not necessarily have to tie into the modeling part later on. Think freely about things that might be interesting, like which actors are very specific to a genre? Are action movies more prone to producing sequels than romances? However, as you keep the focus on movie genres, think also about correlations you might discover that can help build features from the metadata for prediction. Is the length of a movie title correlated with genre? # # + import time import seaborn as sns import numpy as np import pandas as pd from IPython.display import Image import matplotlib.pyplot as plt from collections import Counter # %matplotlib inline ## Installed by running this line in terminal: pip install IMDbPY ## Tutorial found here http://imdbpy.sourceforge.net/support.html import imdb ### Downloaded this via this line: pip install tmdbsimple ## Tutorial found here https://pypi.python.org/pypi/tmdbsimple import tmdbsimple as tmdb # + ## Pass in our tmdb Key tmdb.API_KEY = '352e668a0df90032e0f1097459228131' # Create the object that will be used to access the IMDb's database. ia = imdb.IMDb() # - # # #1: API code to access the genre and movie poster path of your favorite movie # # * Favorite movie: 300 # * Database: TMDB # + # first need to get the tmdb id for 300 search = tmdb.Search() response = search.movie(query="300") for res in search.results: print res['title'], res['id'], res['release_date'], res['popularity'] ## in this case I just took the top result fav_movie_tmdb = search.results[0] # - fav_movie_id = search.results[0]["id"] print "Movie ID for '300': ", fav_movie_id # get the movie movie = tmdb.Movies(1271) info = movie.info() print "TMDB Genres for 300: ", [genre["name"] for genre in info["genres"]] print "TMDB Poster path for 300: ", info["poster_path"] # Search for a movie (get a list of Movie objects). s_result = ia.search_movie('300') for item in s_result: print item['long imdb canonical title'], item.movieID fav_movie_imdb = s_result[0] ia.update(fav_movie_imdb) print "IMDB Genres for 300: ", fav_movie_imdb['genre'] # # #2: Genre for this movie listed by TMDb and IMDb # In summary: # * TMDB says the genres are Action, Adventure, and War # * IMDB says the genres are Action, and Fantasy # # This difference could lead to problems in the future when we are trying to compare similar movies but that come have different supposed "genres." One way that we might avoid this is by doing a merge between the genres or selecting genres that appear in both (in this case that would be 'action') # # #3: A list of the 10 most popular movies of 2016 from TMDb and their genre obtained via the API # abdapted from http://programtalk.com/python-examples/tmdbsimple.Discover/ discover = tmdb.Discover() movies_2016 = discover.movie(year=2016) for movie in discover.results[0:10]: _id = movie["id"] movie = tmdb.Movies(_id) response = movie.info() print "Movie title: {0}".format(response["title"]) print "Movie popularity: {0}".format(response["popularity"]) print "Movie genre: {0}".format([info["name"] for info in movie.genres]) print "\n" # # #4: Comments on what challenges you see for predicting movie genre based on the data you have, and how to address them # # 1) There are differences in the genres listed by TMDb vs. IMDb # - We could use a union of the genres so that only those genres in both databases are considered correct # This also leads to a bigger question of "What does it mean to correctly select a movie genre?" Does thie mean that we select the best genre from IMDb, TMDb? Does this mean we might select multiple genres? These are all questions that we will need to face. # 2) The data will take a long time to load from the APIs because we need to restrict the rate at which we pull large amounts of data - ethics # - We need to work ahead and use AWS. In particular, if we are using a large dataset, we might need to pull a significant amount of our data in advance. # 3) We need to figure out what the "Correct" Genre means # - As we can see from the print out above, many movies have more than one genre. In this case we have that doctor strangelove is considered action, adventure, fantasy, AND science fiction. However, we probably want to create a model that only predicts one of these genres and not all of them. One way that we can break this down and make this easier is by creating a subset of genres that we believe exist in the world. (e.g. taking the top 50 genres.) Then for each of our movies, we make a prediction that only exists within that realm of genres. Another option is for us to try and predict all genres that might be attached to a movie, though this data might be too sparse to be predictive. # # #5: Code to generate the movie genre pairs and a suitable visualization of the result # This section gives a brief look at the relationship between genres. We will then extend upon it to choose only one genre per a movie. # + genres_obj = tmdb.Genres() genre_ids = {genre["name"]: genre["id"] for genre in genres_obj.list()["genres"]} print "Number of genres: {0}".format(len(genre_ids.keys())) genre_ids # - reverse_genre_ids = {v: k for k, v in genre_ids.iteritems()} reverse_genre_ids # + discover = tmdb.Discover() movie_dict = {genre: [] for genre in genre_ids.iterkeys()} # count how many results we get for each genre movie_cnts = {genre: 0 for genre in genre_ids.iterkeys()} # need ids for each genre for genre in genre_ids.keys(): # scan 10 pages for movies for p in range(1, 10): # find all movies with a given id on a given page discover.movie(with_genres = genre_ids[genre], page = p) for page in discover.results: # we found another movie movie_cnts[genre] += 1 # add the ids from this new movie to the list movie_dict[genre].extend(page["genre_ids"]) # sleep so that we don't get kicked off the API time.sleep(10) # + # make a copy of the movie dict so that we don't have # to rerun the above cell if we mess up genre_percentages_mutable = movie_dict.copy() genre_percentages_immutable = genre_percentages_mutable.copy() for genre in genre_percentages_mutable: # make a dictionary of frequencies instead of raw ids genre_percentages_mutable[genre] = Counter(genre_percentages_mutable[genre]) genre_percentages_immutable[genre] = Counter(genre_percentages_immutable[genre]) # for each genre in the dictionary for genre in genre_percentages_mutable: # normalize each raw number into a percentages for genre_id in genre_percentages_mutable[genre]: if genre_id == 10769: continue # this should represent the percent of the occurences in which `genre` is mentioned # in tandem with `genre_id` # # i.e. the key is a genre (e.g. drama) and the id is a genre id # that drama might be paired with (e.g. romance). So, to get the pairing occurence, # we need to take the counter of [genre][genre_id] with [genre_id][genre] and then # divide by the total counts (e.g. genre + genre_id) total_cnts = movie_cnts[genre] + movie_cnts[reverse_genre_ids[genre_id]] total_occ = genre_percentages_immutable[genre][genre_id] + genre_percentages_immutable[reverse_genre_ids[genre_id]][genre_ids[genre]] genre_percentages_mutable[genre][genre_id] = total_occ * 1.0 / total_cnts # + percent_df = pd.DataFrame([pd.Series(genre_percentages_mutable[genre]) for genre in genre_ids.keys()]) percent_df = percent_df.T percent_df.rename(columns=dict(zip(range(0, 19), genre_ids.keys())), inplace = True) # drop this rogue ID percent_df.drop([10769], inplace = True) percent_df.rename(index=dict(zip(percent_df.index, [reverse_genre_ids[genre_id] for genre_id in percent_df.index])), inplace = True) # replace all nans with 0, indicating a 0 percent mention rate for that pair percent_df.fillna(0, inplace = True) # reorder the axes so that they match up on the diagonals percent_df = percent_df.reindex_axis(sorted(percent_df.columns), axis=1) percent_df = percent_df.reindex_axis(sorted(percent_df.columns), axis=0) # - plt.figure(figsize=(12, 10)) plt.title("Normalized Frequency of Genre Pairings (Pages 1-20)", fontsize=16) sns.heatmap(percent_df) # ### Insights # # * Examining our heatmap for the first twenty page instances per genre, we see that the pairing are intuitive. # * Here, we see overlap between history and drama films along with adventure and action. In addition, we see high crossover between family and animation along with crime and thriller. # * Beyond seeing the tendancy for some genres to be listed together, we also see that some categories are vaguer than others. Here, for example, we see that Thriller and Drama serve as catch-alls whereas documentary has a relatively specific definition. # # #6: Additional visualization sketches and EDA with a focus on movie genres # + discover_ = tmdb.Discover() movie_dict = {genre: [] for genre in genre_ids.iterkeys()} # count how many results we get for each genre movie_cnts = {genre: 0 for genre in genre_ids.iterkeys()} # need ids for each genre for genre in genre_ids.keys(): # scan 20 pages for movies for p in range(30, 50): # find all movies with a given id on a given page discover.movie(with_genres = genre_ids[genre], page = p) for page in discover.results: # we found another movie movie_cnts[genre] += 1 # add the ids from this new movie to the list movie_dict[genre].extend(page["genre_ids"]) # sleep so that we don't get kicked off the API time.sleep(10) # make a copy of the movie dict so that we don't have # to rerun the above cell if we mess up genre_percentages = movie_dict.copy() # for each genre in the dictionary for genre in genre_percentages: # make a dictionary of frequencies instead of raw ids genre_percentages[genre] = Counter(genre_percentages[genre]) # normalize each raw number into a percentage for genre_id in genre_percentages[genre]: genre_percentages[genre][genre_id] = genre_percentages[genre][genre_id] * 1.0 / movie_cnts[genre] percent_df = pd.DataFrame([pd.Series(genre_percentages[genre]) for genre in genre_ids.keys()]) percent_df = percent_df.T percent_df.rename(columns=dict(zip(range(0, 19), genre_ids.keys())), inplace = True) # drop this rogue ID percent_df.drop([10769], inplace = True) percent_df.rename(index=dict(zip(percent_df.index, [reverse_genre_ids[genre_id] for genre_id in percent_df.index])), inplace = True) # replace all nans with 0, indicating a 0 percent mention rate for that pair percent_df.fillna(0, inplace = True) # reorder the axes so that they match up on the diagonals percent_df = percent_df.reindex_axis(sorted(percent_df.columns), axis=1) percent_df = percent_df.reindex_axis(sorted(percent_df.columns), axis=0) plt.figure(figsize=(12, 10)) plt.title("Normalized Frequency of Genre Pairings: 30-50 page results", fontsize=16) sns.heatmap(percent_df) # - # ## Checking Consistancy with Pages 30-50 # Comparing the results with the initial 1-20 pages, we see that our findings vary but remain consistant within a reasonable degree. This is to be expect as we have utilized large numbers to get a sample of a greater amount of data. # + ### There are 19 general genres, so 19 choose 2 (171) pairs) ### I Found these ideas by searching for movies that I knew that were romance/drama/horror, finding and then finding ### That genre id DRAMA_ID = 18 HORROR_ID = 27 ROMANCE_ID = 10749 movie = tmdb.Movies(565) response = movie.info() movie.genres ## initialize discover discover = tmdb.Discover() ## create a list of romance movies romance_list = [] ## iterate through 20 pages collecting movies for p in range(1,20): discover.movie(with_genres = ROMANCE_ID, page = p) romance_list.append(discover.results) # - ## iterate through the pages and then the movies ### this will give us back a list of lists of pairings genre_pairings = [] for page in romance_list: for movie in page: genre_pairings.append(movie["genre_ids"]) # + ### This will give horror_count = 0 drama_count = 0 ## iterate through the genre pairings for each movie ## add a count if horror appears or drama appears for pairing in genre_pairings: if HORROR_ID in pairing: horror_count += 1 if DRAMA_ID in pairing: drama_count += 1 # + num_movies = len(genre_pairings) print "We test on this many movies classified as Romance:", num_movies drama_romance_perc = drama_count / float(num_movies) horror_romance_perc= horror_count / float(num_movies) print "Percentage of Romance Movies Paired with Drama:", drama_romance_perc print "Percentage of Romance Movies Paired with Horror:", horror_romance_perc # + ## initialize X and Y for plotting Y = np.array([drama_romance_perc, horror_romance_perc]) LABELS = np.array(["Drama", "Horror"]) X = [1,2] plt.figure(figsize=(10, 7)) plt.bar(X, Y, color="blue") plt.xticks(X, LABELS) plt.title("Percentage of Films in Romance Genre In Other Genre", fontsize=14) plt.xlabel("Genre paired with Romance Films") plt.ylabel("Percentage of Genre Associated with Romance Genre") # - # ### Explanation of Romance and Other Dramas # The takeaway from the above bar graph is that more romance fils are paired with drama than they are by horror. (BY A LOT.) However, let's explain how we received our results. # # We decided to compare the percentage of romance films that were ALSO associated with other genres. To do this, we selected a random subset of our romance films. We used roughly 380 romance films randomly selected from all films with the genre "romance" tag. Of these 380 films, we then looked at the percentage of these films that also shared the genre tag "horror" or "drama" or both. We divided by the total number of films with the horror/drama tag by all romance films used. This gave us are above percentages. # ### Sketches and Future EDA # # Here are sketches of other visualizations we plan to complete. Image(filename='../eda_sketches/sketch1.jpg') # This is a normalized revenue graph, displaying the amount of revenue that genres have made over time. Image(filename='../eda_sketches/sketch2.jpg') # This graph is a color-coded line chart. This shows the distribution of secondary genres by main genres in comparison to each other genre. Image(filename='../eda_sketches/sketch3.jpg') # This graph is a bar graph that shows the frequency of other genres within a defined genre. For example, here we have the genre of โ€œAdventureโ€ along with all the subcategories that also exist within it. Image(filename='../eda_sketches/sketch4.jpg') # Finally, we have a treemap to show the relative amount of revenue by genre for a subset year. # # #7: A list of questions you could answer with this and related data. Get creative here! # * Which movies are the most fluid across genres? # * Which genres are most constrictive (i.e. does having genre X mean you're less likely to be paired with another genre?) # * What pairing of movies genres are most likely to go together? # * Do certain genre pairings result in higher amounts of revenue (e.g. "action romance" doing better than "action")? # * Are there statistically significant differences in movie length by genre? For example, are comedies consistently lower? # * Are there statistically significant differences in movie rating by movie length? Do people tend to like shorter movies more or longer movies more? How does this difference interact with genre? # * What is the highest revenue per minute by genre (we could answer this by dividing average revenue by average movie length)? # * Are adult films frequently labelled other genres? For example, are there such things as "adult fantasy" films and "adult comedy" films? # * How do these english genre distributions compare versus a similar analysis done on a different languageโ€™s database? Are french movies, for instance, more likely to have different genre pairings than english movies? # * How does genre density differ as a function of time? Are some genres more popular now vs. long ago? What about pairing of genres? # * Does having an unoriginal movie title (e.g. "300") help revenue or hurt? # * How has (normalized) revenue changed over time as a function of genre? What about popularity? # # Milestone 2: Assembling training data, due Wednesday, April 12, 2017 # # We are aware that you have little time this week, due to the midterm. So this milestone is a bit easier to achieve than the others. The goal for this week is to prepare the data for the modeling phase of the project. You should end up with a typical data setup of training data X and data labels Y. # # The exact form of X and Y depends on the ideas you had previously. In general though Y should involve the genre of a movie, and X the features you want to include to predict the genre. Remember from the lecture that more features does not necessarily equal better prediction performance. Use your application knowledge and the insight you gathered from your genre pair analysis and additional EDA to design Y. Do you want to include all genres? Are there genres that you assume to be easier to separate than others? Are there genres that could be grouped together? There is no one right answer here. We are looking for your insight, so be sure to describe your decision process in your notebook. # # In preparation for the deep learning part we strongly encourage you to have two sets of training data X, one with the metadata and one with the movie posters. Make sure to have a common key, like the movie ID, to be able to link the two sets together. Also be mindful of the data rate when you obtain the posters. Time your requests and choose which poster resolution you need. In most cases w500 should be sufficient, and probably a lower resolution will be fine. # # The notebook to submit this week should at least include: # # - **Discussion about the imbalanced nature of the data and how you want to address it** # There is natural imabalance in our data because not every genre is represented in the same frequency on the TMDB 'discover' page. This is potentially because some genres (like action/adventure) are more popular with viewers and thus with producers than other genres (like documentaries). We discuss our choices in building our dataset with regard to this popularity imbalance in the following section. # # We decided to perform a stratified sampling of our data because otherwise our poster dataframe would be too massive (700Gb). We want to downsize (scale) our dataset without changing the proportions of each of the genres in the original (large) dataset. To do this, we found the relative frequency of each movie genre in the entire dataset and then sampled according to these proportions. We ended up with a dataframe with 100 rows that has the same genre proportions as the big dataset. # # We chose 100 because some genres appear only 1% or 2% in the dataset, so using any size lower than 50 would mean that we wouldn't sample any of these genres, thus teaching our model not to predict these genres in the first place. # # Because of the imbalances we have in our data, we may want to explore combining some of the less-common genres such as Documentary and History into combined genres renamed as "Informative" for example (or Thriller and Horror into "Scary"). This will decrease the number of labels that we are predicting over and it makes our data less imbalanced by making sparse columns more populated. # # - **Description of your data ** # As shown in our summary table of the first 28 pages, adventure, action, and drama are the most represented within the database whereas documentary, western, and TV Movie are the least represented among sample, again, as shown in our summary table later in the notebook. Because the imbalance, we will need to take special precautions when sampling. # # It is important to note that the 28 pages of TMDB movies are the most popular movies on TMDB as determined by the website's 'popularity' metric. While we found that the 'discover' function was the most convenient way we could quickly scrape together the data of many different movies, it seems worthwhile to note that this may exacerbate imbalances in our data. For example, if documentaries are by some measure less entertaining and thus less popular (as determined by TMDB) than "mainstream" movies like action-dramas, then our data aggregation technique would naturally have a lower representation of documentaries. In this case, genre proportion would be driven by the overall popularity of the genre instead of the overal number of documentaries created relative to other genres. # # We don't believe that this is necessarily a bad thing for our data. It would simply mean that our universe of movies would be those that are most watched as opposed to those that are most made. This scheme has the added benefit that those movies that are more watched likely have fewer missing data. # # Furthermore, there is a technical constraint on shifting our universe to those that are most made. Because we believe (uncontroversially) that most movies are flops that few people have ever watched, we would need to scrape the movie data of a significantly higher number of movies in order to achieve a workable dataset. Furthremore, the 'discover' function in the API may not be enough, and we might need to slowly crawl through the alphabet to pick up those movies which don't appear on any of the pre-made pages by TMDB. While this may be an interesting problem to tackle, we think that the potential marginal benefit to this approach is not enough to greatly change the scope of the project. Thus, we will choose to continue to use a popularity-based approach. # - **How do you sample your data, how many samples, and why?** # Here, for our test sample, we selected the first 28 pages of data. Beyond this amount, certain catagories ran out of data to then fairly sample from all genres and get a unified sample set. We took 100 samples from our original data of 500+ movies. # # We then calculated and stored the genre proportions in our complete 28-page data. We then performed simple random sampling where we sampled each of the genres individually according to the previously calculated proportions. For instance, if 15% of our movies were "Action" in our 28-page dataset, we would sample 15 movies from our action movies in the original dataset. This would preserve the genre proportions in our new dataset while scaling down the size of our training data, thereby making it more tractable to train our models for our images. # - **What does your choice of Y look like?** # We decided for our Y that we would keep all of the genres that were labeled in TMDB. We decided to keep 18 of our 19 original genres (1 genre had extremely low occurence - just 1 data point). This means that when we make predictions, we will need to predict multiple lables (likely multiple bernoulli decisions, i.e. we will give a probability for all of the different genres. Because movie can have more than one genres, these selections are not mutually exclusive.) We will then predict the movie genres that are over 50% or we will take the top 2,3,4 or 5 genres as predictions. We might also take in our model the number of genres that the movie truly has. This will then make us only predict that number of genres (so we will take the four genres that are most likely). # # # - **Which features do you choose for X and why?** # For our X, we wanted to take in features that we believed would be predictive of our response variable. # # For our metadata, we chose to use variables such as the movie description, popularity, title, and vote average. We believe that each of These would have some predictive power in our model. In addition, we expanded our feature set beyond the suggested features by finding the director of each movie and the leading 3 actors. We did this by crawling through the credits of each movie and then crawling through the list of cast members and crew members. We think that the leading actors and directors should give us improved predictive ability because most actors work on similar-type movies that would have similar genres, and many directors have specialties in movie production that would lead them to make more or less of certain genres (e.g. Michael Bay loves explosions - action). # # Similarly, we took data from the poster path and the backdrop. This allows us to access the individual posters themselves and then use them in our machine learning analysis. We can also augment our poster image data with our metadata features, but this is something that we can continue to explore going forward. # # - **Next Steps** In the next milestone, we hope to incorporate priors into our models which indicate a priori prevalence of genre pairings. This is particularly important because when we are performing stratified sampling, we are using the genre proportions that are from only 28 pages of data. Thus, for more uncommon genres, there is high variance in simply applying a frequentist estimate of genre likelihood (e.g. the true proportion of documentaries could be 5% of movies, but in a sample of 500 movies it's very plausible that we could have only seen 10 documentaries (2% of sample). genre_ids.keys()[15:] # + # scrape the data discover = tmdb.Discover() base_url = "https://image.tmdb.org/t/p/w500" d_metadata = [] d_poster = [] # set to 20 to get more data NUM_PAGES = 4 count = 0 for genre in genre_ids.keys(): # only pull 3 genres per #if count >= 2: #break print genre, genre_ids[genre] for p in range(1, NUM_PAGES): # find all movies on a given page discover.movie(with_genres = genre_ids[genre], page = p) ## note that discover results is a list of dicts ## we are iterating through a page and getting each individual movie's information for movie in discover.results: time.sleep(2) # get list of cast and crew (contains directors) credits = tmdb.Movies(movie['id']).credits() # cycle through cast to extract 3 lead actors cast = credits['cast'] actor_lst = [] count = 0 for actor in cast: actor_lst.append(actor['name']) count = count + 1 if count >= 3: break # cycle through crew to extract director crew = credits['crew'] for person in crew: if person['job'] == 'Director': director = person['name'] break d_metadata.append({"movie_id": movie["id"], "title": movie["title"], "overview": movie["overview"], "poster_path": movie["poster_path"], "release_date": movie["release_date"], "vote_count": movie["vote_count"], "popularity": movie["popularity"], "video": movie["video"], "adult": movie["adult"], "vote_average": movie["vote_average"], "genre_ids": movie["genre_ids"], "lead actors": actor_lst, "director": director }) d_poster.append({"movie_id": movie["id"], "title": movie["title"], "genre_ids": movie["genre_ids"], "poster_url": base_url + str(movie["poster_path"]) }) # uncomment when extracting large amounts of data time.sleep(15) count = count + 1 # metaframe df df_metadata = pd.DataFrame(d_metadata) # poster df for neural nets df_poster = pd.DataFrame(d_poster) # + # metaframe df df_metadata = pd.DataFrame(d_metadata) # poster df for neural nets df_poster = pd.DataFrame(d_poster) # - df_metadata_15 = df_metadata.copy() df_poster_15 = df_metadata.copy() print df_metadata.shape df_metadata.head(1) #df_metadata.poster_path = map(lambda path: path.encode("utf-8"), df_metadata.poster_path) df_metadata.title = map(lambda title: title.encode("utf-8"), df_metadata.title) df_metadata.overview = map(lambda overview: overview.encode("utf-8"), df_metadata.overview) df_metadata.columns # fix a weird ascii encoding issue #for col in ["director", "overview"]: for col in ["director", "overview", "title"]: df_metadata[col] = map(lambda x: str(x), df_metadata[col]) # + df_metadata_dummies = df_metadata.genre_ids.astype(str).str.strip('[]').str.get_dummies(', ') df_metadata_dummies.columns = df_metadata_dummies.columns.str.strip("'") df_meta_movie_instance = df_metadata_dummies.apply(pd.value_counts).fillna(0) df_meta_movie_instance = df_meta_movie_instance.drop(df_meta_movie_instance.index[0]) colnames = list(df_metadata_dummies.columns) + list(df_metadata.columns) combined_df = pd.DataFrame(pd.concat([df_metadata_dummies, df_metadata], axis = 1), columns = colnames) # - combined_df.head(1) combined_df.shape combined_df.columns combined_df.drop("genre_ids", axis = 1, inplace = True) combined_df.to_csv("train.csv") combined_df.to_csv("../data/train.csv") # inspect data df_poster.head(1) # dummifies list of genres, placing genres in new columns df_dummies = df_poster.genre_ids.astype(str).str.strip('[]').str.get_dummies(', ') df_dummies.columns = df_dummies.columns.str.strip("'") # get number of occurences in dataset and remove nulls df_movie_instance = df_dummies.apply(pd.value_counts).fillna(0) df_movie_instance = df_movie_instance.drop(df_movie_instance.index[0]) df_movie_instance df_dummies.head(2) # + # create the dataframe that will be sampled colnames = list(df_dummies.columns) + list(df_poster.columns) to_sample = pd.DataFrame(pd.concat([df_dummies, df_poster], axis = 1), columns = colnames) to_sample.head(2) # - # relative freq for each movie genre total_cnt = df_movie_instance.sum(axis = 1).iloc[0] movie_percentages = df_movie_instance.divide(total_cnt).round(2) # + # perform stratified sampling # rename columns SAMPLE_SIZE = 100 sampled_df = pd.DataFrame({}) available_genres = map(int, df_dummies.columns) while available_genres: key = available_genres.pop(0) n_rows = SAMPLE_SIZE * movie_percentages[str(key)].iloc[0] relevant_rows = to_sample[to_sample[str(key)] == 1] sampled_rows = relevant_rows.sample(n = int(n_rows)) # redo sampling if len(sampled_df) > 0 and len(pd.merge(sampled_df, sampled_rows, on="movie_id")) > 0: available_genres.append(key) continue sampled_df = sampled_df.append(sampled_rows) # - # look at sampled df sampled_df = sampled_df.reset_index() sampled_df.head(2) # + # renaming ids to genre names column_names = {'12': 'Adventure', '14': 'Fantasy', '16': 'Animation', '18': 'Drama', '27': 'Horror', '28': 'Action', '35': 'Comedy', '36': 'History', '37': 'Western', '53': 'Thriller', '80': 'Crime', '99': 'Documentary', '878': 'Science Fiction', '9648': 'Mystery', '10402': 'Music', '10749': 'Romance', '10751': 'Family', '10752': 'War', '10770': 'TV Movie'} # format movie_percentages = movie_percentages.rename(columns=column_names).T.rename(columns={1: 'Percentage'}) # - movie_percentages.describe() movie_percentages['Percentage'].sort_values() # Here, we see within our sample we see that the most represented movie is action, adventure, and drama. Looking at our data, we that out least represented movies are Documentary and TV Movie.
milestones_1_2/.ipynb_checkpoints/milestones_1_2-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: threepointseven # language: python # name: threepointseven # --- # + from torchtext import data from torchtext import datasets import torch import spacy import random import numpy as np import torch.nn as nn import torch.nn.functional as F import spacy nlp = spacy.load('en') # + ##python3 -m spacy download en # - questions = data.Field(tokenize = 'spacy', batch_first = True) labels = data.LabelField(dtype = torch.float) # + train_data, _ = datasets.TREC.splits(questions, labels) train_data, valid_data = train_data.split() # - train_data.examples[0].text train_data.examples[0].label len(train_data) len(valid_data) # + questions.build_vocab(train_data, vectors = "glove.6B.200d", unk_init = torch.Tensor.normal_) labels.build_vocab(train_data) # + batch_size = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, valid_iterator = data.BucketIterator.splits( (train_data, valid_data), batch_size = batch_size, device = device) # - class CNN(nn.Module): def __init__(self, vocab_size, embedding_dim, n_filters, filter_sizes, output_dim, dropout, pad_idx): super().__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx) self.convs = nn.ModuleList([ nn.Conv2d(in_channels = 1, out_channels = n_filters, kernel_size = (fs, embedding_dim)) for fs in filter_sizes ]) self.fc = nn.Linear(len(filter_sizes) * n_filters, output_dim) self.dropout = nn.Dropout(dropout) def forward(self, text): embedded = self.embedding(text) embedded = embedded.unsqueeze(1) conved = [F.relu(conv(embedded)).squeeze(3) for conv in self.convs] pooled = [F.max_pool1d(conv, conv.shape[2]).squeeze(2) for conv in conved] cat = self.dropout(torch.cat(pooled, dim = 1)) return self.fc(cat) # + INPUT_DIM = len(questions.vocab) EMBEDDING_DIM = 200 N_FILTERS = 100 FILTER_SIZES = [2,3,4] OUTPUT_DIM = 6 DROPOUT = 0.5 PAD_IDX = questions.vocab.stoi[questions.pad_token] model = CNN(INPUT_DIM, EMBEDDING_DIM, N_FILTERS, FILTER_SIZES, OUTPUT_DIM, DROPOUT, PAD_IDX) # + pretrained_embeddings = questions.vocab.vectors model.embedding.weight.data.copy_(pretrained_embeddings) # + UNK_IDX = questions.vocab.stoi[questions.unk_token] model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM) model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM) # + optimizer = torch.optim.Adam(model.parameters()) criterion = nn.CrossEntropyLoss() model = model.to(device) criterion = criterion.to(device) # - def multi_accuracy(preds, y): pred = torch.max(preds,1).indices correct = (pred == y).float() acc = correct.sum() / len(correct) return acc def train(model, iterator, optimizer, criterion): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: optimizer.zero_grad() predictions = model(batch.text).squeeze(1) loss = criterion(predictions, batch.label.long()) acc = multi_accuracy(predictions, batch.label) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) def evaluate(model, iterator, criterion): epoch_loss = 0 epoch_acc = 0 model.eval() with torch.no_grad(): for batch in iterator: predictions = model(batch.text).squeeze(1) loss = criterion(predictions, batch.label.long()) acc = multi_accuracy(predictions, batch.label) epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) # + import time def time_it(start_time, end_time): return int(end_time - start_time) # + N_EPOCHS = 10 best_valid_loss = float('inf') for epoch in range(N_EPOCHS): start_time = time.time() train_loss, train_acc = train(model, train_iterator, optimizer, criterion) valid_loss, valid_acc = evaluate(model, valid_iterator, criterion) end_time = time.time() if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model.state_dict(), 'tut4-model.pt') print(f'Epoch: {epoch+1:02} | Epoch Time: {time_it(start_time, end_time)}s') print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%') print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%') # - model.load_state_dict(torch.load('tut4-model.pt')) def predict_sentiment(model, sentence, min_len = 5): model.eval() tokenized = [tok.text for tok in nlp.tokenizer(sentence)] if len(tokenized) < min_len: tokenized += ['<pad>'] * (min_len - len(tokenized)) indexed = [questions.vocab.stoi[t] for t in tokenized] tensor = torch.LongTensor(indexed).to(device) tensor = tensor.unsqueeze(0) prediction = torch.max(model(tensor),1).indices.item() pred_index = labels.vocab.itos[prediction] return pred_index pred_class = predict_sentiment(model, "How many roads must a man walk down?") print('Predicted class is: ' + str(pred_class))
Chapter06/.ipynb_checkpoints/CNN-safe-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 6. Recurrent Neural Networks and Language Models # * http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture8.pdf # * http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture9.pdf # * http://colah.github.io/posts/2015-08-Understanding-LSTMs/ # * https://github.com/pytorch/examples/tree/master/word_language_model # * https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/language_model import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import torch.nn.functional as F import nltk import random import numpy as np from collections import Counter, OrderedDict import nltk from copy import deepcopy flatten = lambda l: [item for sublist in l for item in sublist] # + USE_CUDA = torch.cuda.is_available() FloatTensor = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor LongTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor ByteTensor = torch.cuda.ByteTensor if USE_CUDA else torch.ByteTensor # - def prepare_sequence(seq, to_index): idxs = list(map(lambda w: to_index[w] if w in to_index.keys() else to_index["<unk>"], seq)) return LongTensor(idxs) # ## Data load and Preprocessing # ### Penn TreeBank def prepare_ptb_dataset(filename,word2index=None): corpus = open(filename,'r',encoding='utf-8').readlines() corpus = flatten([co.strip().split() + ['</s>'] for co in corpus]) if word2index==None: vocab = list(set(corpus)) word2index={'<unk>':0} for vo in vocab: if vo not in word2index.keys(): word2index[vo]=len(word2index) return prepare_sequence(corpus,word2index), word2index # + # borrowed code from https://github.com/pytorch/examples/tree/master/word_language_model def batchify(data, bsz): # Work out how cleanly we can divide the dataset into bsz parts. nbatch = data.size(0) // bsz # Trim off any extra elements that wouldn't cleanly fit (remainders). data = data.narrow(0, 0, nbatch * bsz) # Evenly divide the data across the bsz batches. data = data.view(bsz, -1).contiguous() if USE_CUDA: data = data.cuda() return data # - def getBatch(data,seq_length): for i in range(0, data.size(1) - seq_length, seq_length): inputs = Variable(data[:, i:i+seq_length]) targets = Variable(data[:, (i+1):(i+1)+seq_length].contiguous()) yield (inputs,targets) train_data, word2index= prepare_ptb_dataset('../dataset/ptb/ptb.train.txt',) dev_data , _ = prepare_ptb_dataset('../dataset/ptb/ptb.valid.txt',word2index) test_data, _ = prepare_ptb_dataset('../dataset/ptb/ptb.test.txt',word2index) len(word2index) index2word = {v:k for k,v in word2index.items()} # ## Modeling # <img src="../images/06.rnnlm-architecture.png"> # <center>borrowed image from http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture8.pdf</center> class LanguageModel(nn.Module): def __init__(self,vocab_size,embedding_size,hidden_size,n_layers=1,dropout_p=0.5): super(LanguageModel, self).__init__() self.n_layers = n_layers self.hidden_size = hidden_size self.embed = nn.Embedding(vocab_size,embedding_size) self.rnn = nn.LSTM(embedding_size,hidden_size,n_layers,batch_first=True) self.linear = nn.Linear(hidden_size,vocab_size) self.dropout = nn.Dropout(dropout_p) def init_weight(self): self.embed.weight = nn.init.xavier_uniform(self.embed.weight) self.linear.weight = nn.init.xavier_uniform(self.linear.weight) self.linear.bias.data.fill_(0) def init_hidden(self,batch_size): hidden = Variable(torch.zeros(self.n_layers,batch_size,self.hidden_size)) context = Variable(torch.zeros(self.n_layers,batch_size,self.hidden_size)) return (hidden.cuda(), context.cuda()) if USE_CUDA else (hidden,context) def detach_hidden(self,hiddens): return tuple([hidden.detach() for hidden in hiddens]) def forward(self, inputs,hidden,is_training=False): embeds = self.embed(inputs) if is_training: embeds = self.dropout(embeds) out,hidden = self.rnn(embeds,hidden) return self.linear(out.contiguous().view(out.size(0)*out.size(1),-1)), hidden # ## Train # It takes for a while... EMBED_SIZE=128 HIDDEN_SIZE=1024 NUM_LAYER=1 LR = 0.01 SEQ_LENGTH = 30 # for bptt BATCH_SIZE = 20 EPOCH = 40 RESCHEDULED=False train_data = batchify(train_data,BATCH_SIZE) dev_data = batchify(dev_data,BATCH_SIZE//2) test_data = batchify(test_data,BATCH_SIZE//2) model = LanguageModel(len(word2index),EMBED_SIZE,HIDDEN_SIZE,NUM_LAYER,0.5) model.init_weight() if USE_CUDA: model = model.cuda() loss_function = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(),lr=LR) for epoch in range(EPOCH): total_loss = 0 losses=[] hidden = model.init_hidden(BATCH_SIZE) for i,batch in enumerate(getBatch(train_data,SEQ_LENGTH)): inputs, targets = batch hidden = model.detach_hidden(hidden) model.zero_grad() preds,hidden = model(inputs,hidden,True) loss = loss_function(preds,targets.view(-1)) losses.append(loss.data[0]) loss.backward() torch.nn.utils.clip_grad_norm(model.parameters(),0.5) # gradient clipping optimizer.step() if i>0 and i % 500==0: print("[%02d/%d] mean_loss : %0.2f, Perplexity : %0.2f" % (epoch,EPOCH, \ np.mean(losses),np.exp(np.mean(losses)))) losses=[] # learning rate anealing # You can use http://pytorch.org/docs/master/optim.html#how-to-adjust-learning-rate if RESCHEDULED==False and epoch==EPOCH//2: LR=LR*0.1 optimizer = optim.Adam(model.parameters(),lr=LR) RESCHEDULED=True # ### Test # + total_loss = 0 hidden = model.init_hidden(BATCH_SIZE//2) for batch in getBatch(test_data,SEQ_LENGTH): inputs,targets = batch hidden = model.detach_hidden(hidden) model.zero_grad() preds,hidden = model(inputs,hidden) total_loss += inputs.size(1) * loss_function(preds, targets.view(-1)).data total_loss = total_loss[0]/test_data.size(1) print("Test Perpelexity : %5.2f" % (np.exp(total_loss))) # - # ## Further topics # * <a href="https://arxiv.org/pdf/1609.07843.pdf">Pointer Sentinel Mixture Models</a> # * <a href="https://arxiv.org/pdf/1708.02182">Regularizing and Optimizing LSTM Language Models</a>
notebooks/06.RNN-Language-Model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from scipy.spatial import Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d import matplotlib.pyplot as plt import numpy as np w = h = 360 n = 6 np.random.seed(0) pts = np.random.randint(0, w, (n, 2)) print(pts) print(type(pts)) print(pts.shape) tri = Delaunay(pts) print(type(tri)) fig = delaunay_plot_2d(tri) fig.savefig('data/dst/scipy_matplotlib_delaunay.png') plt.close() # ![data/dst/scipy_matplotlib_delaunay.png](data/dst/scipy_matplotlib_delaunay.png) print(tri.points) print(tri.points == pts) print(tri.simplices) print(pts[tri.simplices]) vor = Voronoi(pts) print(type(vor)) fig = voronoi_plot_2d(vor) fig.savefig('data/dst/scipy_matplotlib_voronoi.png') plt.close() # ![data/dst/scipy_matplotlib_voronoi.png](data/dst/scipy_matplotlib_voronoi.png) print(vor.vertices) print(vor.regions) print([r for r in vor.regions if -1 not in r and r]) for region in [r for r in vor.regions if -1 not in r and r]: print(vor.vertices[region]) # + fig, ax = plt.subplots() voronoi_plot_2d(vor, ax) for region, c in zip([r for r in vor.regions if -1 not in r and r], ['yellow', 'pink']): ax.fill(vor.vertices[region][:, 0], vor.vertices[region][:, 1], color=c) fig.savefig('data/dst/scipy_matplotlib_voronoi_fill.png') plt.close() # - # ![data/dst/scipy_matplotlib_voronoi_fill.png](data/dst/scipy_matplotlib_voronoi_fill.png) # + fig, ax = plt.subplots(figsize=(4, 4)) delaunay_plot_2d(tri, ax) voronoi_plot_2d(vor, ax, show_vertices=False) ax.set_xlim(0, w) ax.set_ylim(0, h) ax.grid(linestyle='--') fig.savefig('data/dst/scipy_matplotlib_delaunay_voronoi.png') plt.close() # - # ![data/dst/scipy_matplotlib_delaunay_voronoi.png](data/dst/scipy_matplotlib_delaunay_voronoi.png)
notebook/scipy_matplotlib_delaunay_voronoi.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="s_qNSzzyaCbD" # ##### Copyright 2019 The TensorFlow Authors. # + cellView="form" id="jmjh290raIky" #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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. # + [markdown] id="J0Qjg6vuaHNt" # # Neural machine translation with attention # + [markdown] id="AOpGoE2T-YXS" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/text/tutorials/nmt_with_attention"> # <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> # View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/text/blob/master/docs/tutorials/nmt_with_attention.ipynb"> # <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> # Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/text/blob/master/docs/tutorials/nmt_with_attention.ipynb"> # <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> # View source on GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/text/docs/tutorials/nmt_with_attention.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> # </td> # </table> # + [markdown] id="CiwtNgENbx2g" # This notebook trains a sequence to sequence (seq2seq) model for Spanish to English translation based on [Effective Approaches to Attention-based Neural Machine Translation](https://arxiv.org/abs/1508.04025v5). This is an advanced example that assumes some knowledge of: # # * Sequence to sequence models # * TensorFlow fundamentals below the keras layer: # * Working with tensors directly # * Writing custom `keras.Model`s and `keras.layers` # # While this architecture is somewhat outdated it is still a very useful project to work through to get a deeper understanding of attention mechanisms (before going on to [Transformers](transformers.ipynb)). # # After training the model in this notebook, you will be able to input a Spanish sentence, such as "*ยฟtodavia estan en casa?*", and return the English translation: "*are you still at home?*" # # The resulting model is exportable as a `tf.saved_model`, so it can be used in other TensorFlow environments. # # The translation quality is reasonable for a toy example, but the generated attention plot is perhaps more interesting. This shows which parts of the input sentence has the model's attention while translating: # # <img src="https://tensorflow.org/images/spanish-english.png" alt="spanish-english attention plot"> # # Note: This example takes approximately 10 minutes to run on a single P100 GPU. # + [markdown] id="yAmSR1FaqKrl" # ## Setup # + id="DGFTkuRvzWqc" # !pip install tensorflow_text # + id="tnxXKDjq3jEL" import numpy as np import typing from typing import Any, Tuple import tensorflow as tf from tensorflow.keras.layers.experimental import preprocessing import tensorflow_text as tf_text import matplotlib.pyplot as plt import matplotlib.ticker as ticker # + [markdown] id="Vs8zge-RUdC2" # This tutorial builds a few layers from scratch, use this variable if you want to switch between the custom and builtin implementations. # + id="KPJ9J7iPUchc" use_builtins = True # + [markdown] id="l_yq8kvIqoqQ" # This tutorial uses a lot of low level API's where it's easy to get shapes wrong. This class is used to check shapes throughout the tutorial. # # + id="KqFqKi4fqN9X" #@title Shape checker class ShapeChecker(): def __init__(self): # Keep a cache of every axis-name seen self.shapes = {} def __call__(self, tensor, names, broadcast=False): if not tf.executing_eagerly(): return if isinstance(names, str): names = (names,) shape = tf.shape(tensor) rank = tf.rank(tensor) if rank != len(names): raise ValueError(f'Rank mismatch:\n' f' found {rank}: {shape.numpy()}\n' f' expected {len(names)}: {names}\n') for i, name in enumerate(names): if isinstance(name, int): old_dim = name else: old_dim = self.shapes.get(name, None) new_dim = shape[i] if (broadcast and new_dim == 1): continue if old_dim is None: # If the axis name is new, add its length to the cache. self.shapes[name] = new_dim continue if new_dim != old_dim: raise ValueError(f"Shape mismatch for dimension: '{name}'\n" f" found: {new_dim}\n" f" expected: {old_dim}\n") # + [markdown] id="gjUROhJfH3ML" # ## The data # + [markdown] id="puE_K74DIE9W" # We'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format: # # ``` # May I borrow this book? ยฟPuedo tomar prestado este libro? # ``` # # They have a variety of languages available, but we'll use the English-Spanish dataset. # + [markdown] id="wfodePkj3jEa" # ### Download and prepare the dataset # # For convenience, we've hosted a copy of this dataset on Google Cloud, but you can also download your own copy. After downloading the dataset, here are the steps we'll take to prepare the data: # # 1. Add a *start* and *end* token to each sentence. # 2. Clean the sentences by removing special characters. # 3. Create a word index and reverse word index (dictionaries mapping from word โ†’ id and id โ†’ word). # 4. Pad each sentence to a maximum length. # + id="kRVATYOgJs1b" # Download the file import pathlib path_to_zip = tf.keras.utils.get_file( 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip', extract=True) path_to_file = pathlib.Path(path_to_zip).parent/'spa-eng/spa.txt' # + id="OHn4Dct23jEm" def load_data(path): text = path.read_text(encoding='utf-8') lines = text.splitlines() pairs = [line.split('\t') for line in lines] inp = [inp for targ, inp in pairs] targ = [targ for targ, inp in pairs] return targ, inp # + id="cTbSbBz55QtF" targ, inp = load_data(path_to_file) print(inp[-1]) # + id="lH_dPY8TRp3c" print(targ[-1]) # + [markdown] id="rgCLkfv5uO3d" # ### Create a tf.data dataset # + [markdown] id="PfVWx3WaI5Df" # From these arrays of strings you can create a `tf.data.Dataset` of strings that shuffles and batches them efficiently: # + id="TqHsArVZ3jFS" BUFFER_SIZE = len(inp) BATCH_SIZE = 64 dataset = tf.data.Dataset.from_tensor_slices((inp, targ)).shuffle(BUFFER_SIZE) dataset = dataset.batch(BATCH_SIZE) # + id="qc6-NK1GtWQt" for example_input_batch, example_target_batch in dataset.take(1): print(example_input_batch[:5]) print() print(example_target_batch[:5]) break # + [markdown] id="zCoxLcuN3bwv" # ### Text preprocessing # + [markdown] id="7kwdPcHvzz_a" # One of the goals of this tutorial is to build a model that can be exported as a `tf.saved_model`. To make that exported model useful it should take `tf.string` inputs, and retrun `tf.string` outputs: All the text processing happens inside the model. # + [markdown] id="EOQ5n55X4uDB" # #### Standardization # + [markdown] id="upKhKAMK4zzI" # The model is dealing with multilingual text with a limited vocabulary. So it will be important to standardize the input text. # # The first step is Unicode normalization to split accented characters and replace compatibility characters with their ASCII equivalents. # # The `tensroflow_text` package contains a unicode normalize operation: # + id="mD0e-DWGQ2Vo" example_text = tf.constant('ยฟTodavรญa estรก en casa?') print(example_text.numpy()) print(tf_text.normalize_utf8(example_text, 'NFKD').numpy()) # + [markdown] id="6hTllEjK6RSo" # Unicode normalization will be the first step in the text standardization function: # + id="chTF5N885F0P" def tf_lower_and_split_punct(text): # Split accecented characters. text = tf_text.normalize_utf8(text, 'NFKD') text = tf.strings.lower(text) # Keep space, a to z, and select punctuation. text = tf.strings.regex_replace(text, '[^ a-z.?!,ยฟ]', '') # Add spaces around punctuation. text = tf.strings.regex_replace(text, '[.?!,ยฟ]', r' \0 ') # Strip whitespace. text = tf.strings.strip(text) text = tf.strings.join(['[START]', text, '[END]'], separator=' ') return text # + id="UREvDg3sEKYa" print(example_text.numpy().decode()) print(tf_lower_and_split_punct(example_text).numpy().decode()) # + [markdown] id="4q-sKsSI7xRZ" # #### Text Vectorization # + [markdown] id="6aKn8qd37abi" # This standardization function will be wrapped up in a `preprocessing.TextVectorization` layer which will handle the vocabulary extraction and conversion of input text to sequences of tokens. # + id="eAY9k49G3jE_" max_vocab_size = 5000 input_text_processor = preprocessing.TextVectorization( standardize=tf_lower_and_split_punct, max_tokens=max_vocab_size) # + [markdown] id="7kbC6ODP8IK_" # The `TextVectorization` layer and many other `experimental.preprocessing` layers have an `adapt` method. This method reads one epoch of the training data, and works a lot like `Model.fix`. This `adapt` method initializes the layer based on the data. Here it determines the vocabulary: # + id="bmsI1Yql8FYe" input_text_processor.adapt(inp) # Here are the first 10 words from the vocabulary: input_text_processor.get_vocabulary()[:10] # + [markdown] id="9kGjIFjX8_Wp" # That's the Spanish `TextVectorization` layer, now build and `.adapt()` the English one: # + id="jlC4xuZnKLBS" output_text_processor = preprocessing.TextVectorization( standardize=tf_lower_and_split_punct, max_tokens=max_vocab_size) output_text_processor.adapt(targ) output_text_processor.get_vocabulary()[:10] # + [markdown] id="BWQqlP_s9eIv" # Now these layers can convert a batch of strings into a batch of token IDs: # + id="9KZxj8IrNZ9S" example_tokens = input_text_processor(example_input_batch) example_tokens[:3, :10] # + [markdown] id="AA9rUn9G9n78" # The `get_vocabulary` method can be used to convert token IDs back to text: # + id="98g9rcxGQY0I" input_vocab = np.array(input_text_processor.get_vocabulary()) tokens = input_vocab[example_tokens[0].numpy()] ' '.join(tokens) # + [markdown] id="Ot0aCL9t-Ghi" # The returned token IDs are zero-padded. This can easily be turned into a mask: # + id="_jx4Or_eFRSz" plt.subplot(1, 2, 1) plt.pcolormesh(example_tokens) plt.title('Token IDs') plt.subplot(1, 2, 2) plt.pcolormesh(example_tokens != 0) plt.title('Mask') # + [markdown] id="TNfHIF71ulLu" # ## The encoder/decoder model # # The following diagram shows an overview of the model. At each time-step the decoder's output is combined with a weighted sum over the encoded input, to predict the next word. The diagram and formulas are from [Luong's paper](https://arxiv.org/abs/1508.04025v5). # # <img src="https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg" width="500" alt="attention mechanism"> # # + [markdown] id="gzQWx2saImMV" # Before getting into it define a few constants for the model: # + id="_a9uNz3-IrF-" embedding_dim = 256 units = 1024 # + [markdown] id="blNgVbLSzpsr" # ### The encoder # # Start by building the encoder, the blue part of the diagram above. # # The encoder: # # 1. Takes a list of token IDs (from `input_text_processor`). # 3. Looks up an embedding vector for each token (Using a `layers.Embedding`). # 4. Processes the embeddings into a new sequence (Using a `layers.GRU`). # 5. Returns: # * The processed sequence. This will be passed to the attention head. # * The internal state. This will be used to initialize the decoder # # + id="nZ2rI24i3jFg" class Encoder(tf.keras.layers.Layer): def __init__(self, input_vocab_size, embedding_dim, enc_units): super(Encoder, self).__init__() self.enc_units = enc_units self.input_vocab_size = input_vocab_size # The embedding layer converts tokens to vectors self.embedding = tf.keras.layers.Embedding(self.input_vocab_size, embedding_dim) # The GRU RNN layer processes those vectors sequentially. self.gru = tf.keras.layers.GRU(self.enc_units, # Return the sequence and state return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') def call(self, tokens, state=None): shape_checker = ShapeChecker() shape_checker(tokens, ('batch', 's')) # 2. The embedding layer looks up the embedding for each token. vectors = self.embedding(tokens) shape_checker(vectors, ('batch', 's', 'embed_dim')) # 3. The GRU processes the embedding sequence. # output shape: (batch, s, enc_units) # state shape: (batch, enc_units) output, state = self.gru(vectors, initial_state=state) shape_checker(output, ('batch', 's', 'enc_units')) shape_checker(state, ('batch', 'enc_units')) # 4. Returns the new sequence and its state. return output, state # + [markdown] id="D3SKkaQeGn-Q" # Here is how it fits together so far: # + id="60gSVh05Jl6l" # Convert the input text to tokens. example_tokens = input_text_processor(example_input_batch) # Encode the input sequence. encoder = Encoder(input_text_processor.vocabulary_size(), embedding_dim, units) example_enc_output, example_enc_state = encoder(example_tokens) print(f'Input batch, shape (batch): {example_input_batch.shape}') print(f'Input batch tokens, shape (batch, s): {example_tokens.shape}') print(f'Encoder output, shape (batch, s, units): {example_enc_output.shape}') print(f'Encoder state, shape (batch, units): {example_enc_state.shape}') # + [markdown] id="2RIPHh4O9ixB" # The encoder returns its internal state so that its state can be used to initialize the decoder. # # It's also common for an RNN to return its state so that it can process a sequence over multiple calls. You'll see more of that building the decoder. # + [markdown] id="45xM_Gl1MgXY" # ### The attention head # # The decoder uses attention to selectively focus on parts of the input sequence. # The attention takes a sequence of vectors as input for each example and returns an "attention" vector for each example. This attention layer is similar to a `layers.GlobalAveragePoling1D` but the attention layer performs a _weighted_ average. # # Let's look at how this works: # # <img src="images/attention_equation_1.jpg" alt="attention equation 1" width="800"> # # <img src="images/attention_equation_2.jpg" alt="attention equation 2" width="800"> # + [markdown] id="NX2JsKzzzgZ5" # Where: # # * $s$ is the encoder index. # * $t$ is the decoder index. # * $\alpha_{ts}$ is the attention weights. # * $h_s$ is the sequence of encoder outputs being attended to (the attention "key" and "value" in transformer terminology). # * $h_t$ is the the decoder state attending to the sequence (the attention "query" in transformer terminology). # * $c_t$ is the resulting context vector. # * $a_t$ is the final output combining the "context" and "query". # # The equations: # # 1. Calculates the attention weights, $\alpha_{ts}$, as a softmax across the encoder's output sequence. # 2. Calculates the context vector as the weighted sum of the encoder outputs. # # + [markdown] id="fNA5GeHHPsGL" # Last is the $score$ function. Its job is to calculate a scalar logit-score for each key-query pair. There are two common approaches: # # <img src="images/attention_equation_4.jpg" alt="attention equation 4" width="800"> # # This tutorial uses [Bahdanau's additive attention](https://arxiv.org/pdf/1409.0473.pdf). TensorFlow includes implementations of both as `layers.Attention` and # `layers.AdditiveAttention`. The class below handles the weight matrices in a pair of `layers.Dense` layers, and calls the builtin implementation. # + id="momiE59lXo6U" class BahdanauAttention(tf.keras.layers.Layer): def __init__(self, units): super().__init__() # For Eqn. (4), the Bahdanau attention self.W1 = tf.keras.layers.Dense(units, use_bias=False) self.W2 = tf.keras.layers.Dense(units, use_bias=False) self.attention = tf.keras.layers.AdditiveAttention() def call(self, query, value, mask): shape_checker = ShapeChecker() shape_checker(query, ('batch', 't', 'query_units')) shape_checker(value, ('batch', 's', 'value_units')) shape_checker(mask, ('batch', 's')) # From Eqn. (4), `W1@ht`. w1_query = self.W1(query) shape_checker(w1_query, ('batch', 't', 'attn_units')) # From Eqn. (4), `W2@hs`. w2_key = self.W2(value) shape_checker(w2_key, ('batch', 's', 'attn_units')) query_mask = tf.ones(tf.shape(query)[:-1], dtype=bool) value_mask = mask context_vector, attention_weights = self.attention( inputs = [w1_query, value, w2_key], mask=[query_mask, value_mask], return_attention_scores = True, ) shape_checker(context_vector, ('batch', 't', 'value_units')) shape_checker(attention_weights, ('batch', 't', 's')) return context_vector, attention_weights # + [markdown] id="Cf13LubPGjDO" # ### Test the Attention layer # # Create a `BahdanauAttention` layer: # + id="t4QMlOp8Gidh" attention_layer = BahdanauAttention(units) # + [markdown] id="snA1uL9AI-JE" # This layer takes 3 inputs: # # * The `query`: This will be generated by the decoder, later. # * The `value`: This Will be the output of the encoder. # * The `mask`: To exclude the padding, `example_tokens != 0` # + id="DYSHqmORgVFo" (example_tokens != 0).shape # + [markdown] id="g2bmvT25pXnr" # The vectorized implementation of the attention layer lets you pass a batch of sequences of query vectors and a batch of sequence of value vectors. The result is: # # 1. A batch of sequences of result vectors the size of the queries. # 2. A batch attention maps, with size `(query_length, value_length)`. # + id="7y7hjPkNMmHh" # Later, the decoder will generate this attention query example_attention_query = tf.random.normal(shape=[len(example_tokens), 2, 10]) # Attend to the encoded tokens context_vector, attention_weights = attention_layer( query=example_attention_query, value=example_enc_output, mask=(example_tokens != 0)) print(f'Attention result shape: (batch_size, query_seq_length, units): {context_vector.shape}') print(f'Attention weights shape: (batch_size, query_seq_length, value_seq_length): {attention_weights.shape}') # + [markdown] id="AagyXMH-Jhqt" # The attention weights should sum to `1.0` for each sequence. # # Here are the attention weights across the sequences at `t=0`: # + id="Rqr8XGsAJlf6" plt.subplot(1, 2, 1) plt.pcolormesh(attention_weights[:, 0, :]) plt.title('Attention weights') plt.subplot(1, 2, 2) plt.pcolormesh(example_tokens != 0) plt.title('Mask') # + [markdown] id="6Eil-C_NN1rp" # Because of the small-random initialization the attention weights are all close to `1/(sequence_length)`. If you zoom in on the weights for a single sequence, you can see that there is some _small_ variation that the model can learn to expand, and exploit. # + id="ZuzrCdmYlTcJ" attention_weights.shape # + id="qIMwC-f-ZC8N" attention_slice = attention_weights[0, 0].numpy() attention_slice = attention_slice[attention_slice != 0] # + id="ysWDPO6hOS8X" #@title plt.suptitle('Attention weights for one sequence') plt.figure(figsize=(12, 6)) a1 = plt.subplot(1, 2, 1) plt.bar(range(len(attention_slice)), attention_slice) # freeze the xlim plt.xlim(plt.xlim()) plt.xlabel('Attention weights') a2 = plt.subplot(1, 2, 2) plt.bar(range(len(attention_slice)), attention_slice) plt.xlabel('Attention weights, zoomed') # zoom in top = max(a1.get_ylim()) zoom = 0.85*top a2.set_ylim([0.90*top, top]) a1.plot(a1.get_xlim(), [zoom, zoom], color='k') # + [markdown] id="aQ638eHN4iCK" # ### The decoder # # The decoder's job is to generate predictions for the next output token. # # 1. The decoder receives the complete encoder output. # 2. It uses an RNN to keep track of what it has generated so far. # 3. It uses its RNN output as the query to the attention over the encoder's output, producing the context vector. # 4. It combines the RNN output and the context vector using Equation 3 (below) to generate the "attention vector". # 5. It generates logit predictions for the next token based on the "attention vector". # # <img src="images/attention_equation_3.jpg" alt="attention equation 3" width="800"> # # + [markdown] id="pZsQJMqNmg_L" # Here is the `Decoder` class and its initializer. The initializer creates all the necessary layers. # + id="erYvHIgAl8kh" class Decoder(tf.keras.layers.Layer): def __init__(self, output_vocab_size, embedding_dim, dec_units): super(Decoder, self).__init__() self.dec_units = dec_units self.output_vocab_size = output_vocab_size self.embedding_dim = embedding_dim # For Step 1. The embedding layer convets token IDs to vectors self.embedding = tf.keras.layers.Embedding(self.output_vocab_size, embedding_dim) # For Step 2. The RNN keeps track of what's been generated so far. self.gru = tf.keras.layers.GRU(self.dec_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') # For step 3. The RNN output will be the query for the attention layer. self.attention = BahdanauAttention(self.dec_units) # For step 4. Eqn. (3): converting `ct` to `at` self.Wc = tf.keras.layers.Dense(dec_units, activation=tf.math.tanh, use_bias=False) # For step 5. This fully connected layer produces the logits for each # output token. self.fc = tf.keras.layers.Dense(self.output_vocab_size) # + [markdown] id="eUTfYHmfmwKH" # The `call` method for this layer takes and returns multiple tensors. Organize those into simple container classes: # + id="7WfSIb2sArRT" class DecoderInput(typing.NamedTuple): new_tokens: Any enc_output: Any mask: Any class DecoderOutput(typing.NamedTuple): logits: Any attention_weights: Any # + [markdown] id="NChkl2KrnV2y" # Here is the implementation of the `call` method: # + id="PJOi5btHAPNK" def call(self, inputs: DecoderInput, state=None) -> Tuple[DecoderOutput, tf.Tensor]: shape_checker = ShapeChecker() shape_checker(inputs.new_tokens, ('batch', 't')) shape_checker(inputs.enc_output, ('batch', 's', 'enc_units')) shape_checker(inputs.mask, ('batch', 's')) if state is not None: shape_checker(state, ('batch', 'dec_units')) # Step 1. Lookup the embeddings vectors = self.embedding(inputs.new_tokens) shape_checker(vectors, ('batch', 't', 'embedding_dim')) # Step 2. Process one step with the RNN rnn_output, state = self.gru(vectors, initial_state=state) shape_checker(rnn_output, ('batch', 't', 'dec_units')) shape_checker(state, ('batch', 'dec_units')) # Step 3. Use the RNN output as the query for the attention over the # encoder output. context_vector, attention_weights = self.attention( query=rnn_output, value=inputs.enc_output, mask=inputs.mask) shape_checker(context_vector, ('batch', 't', 'dec_units')) shape_checker(attention_weights, ('batch', 't', 's')) # Step 4. Eqn. (3): Join the context_vector and rnn_output # [ct; ht] shape: (batch t, value_units + query_units) context_and_rnn_output = tf.concat([context_vector, rnn_output], axis=-1) # Step 4. Eqn. (3): `at = tanh(Wc@[ct; ht])` attention_vector = self.Wc(context_and_rnn_output) shape_checker(attention_vector, ('batch', 't', 'dec_units')) # Step 5. Generate logit predictions: logits = self.fc(attention_vector) shape_checker(logits, ('batch', 't', 'output_vocab_size')) return DecoderOutput(logits, attention_weights), state # + id="Ay_mTMPfnb2a" Decoder.call = call # + [markdown] id="arTOBklcFTiC" # The **encoder** processes its full input sequence with a single call to its RNN. This implementation of the **decoder** _can_ do that as well for efficient training. But this tutorial will run the decoder in a loop for a few reasons: # # * Flexibility: Writing the loop gives you direct control over the training procedure. # * Clarity: It's possible to do masking tricks and use `layers.RNN`, or `tfa.seq2seq` APIs to pack this all into a single call. But writing it out as a loop may be clearer. # * Loop free training is demonstrated in the [Text generation](text_generation.ipynb) tutiorial. # # + [markdown] id="E1-mLAcUEXpK" # Now try using this decoder. # + id="4ZUMbYXIEVeA" decoder = Decoder(output_text_processor.vocabulary_size(), embedding_dim, units) # + [markdown] id="UPnaw583CpnY" # The decoder takes 4 inputs. # # * `new_tokens` - The last token generated. Initialize the decoder with the `"[START]"` token. # * `enc_output` - Generated by the `Encoder`. # * `mask` - A boolean tensor indicating where `tokens != 0` # * `state` - The previous `state` output from the decoder (the internal state # of the decoder's RNN). Pass `None` to zero-initialize it. The original # paper initializes it from the encoder's final RNN state. # + id="4u6eJBU4GL40" # Convert the target sequence, and collect the "[START]" tokens example_output_tokens = output_text_processor(example_target_batch) start_index = output_text_processor._index_lookup_layer('[START]').numpy() first_token = tf.constant([[start_index]] * example_output_tokens.shape[0]) # + id="E5hqvbR5FUCD" # Run the decoder dec_result, dec_state = decoder( inputs = DecoderInput(new_tokens=first_token, enc_output=example_enc_output, mask=(example_tokens != 0)), state = example_enc_state ) print(f'logits shape: (batch_size, t, output_vocab_size) {dec_result.logits.shape}') print(f'state shape: (batch_size, dec_units) {dec_state.shape}') # + [markdown] id="vEZvXZRVPHd6" # Sample a token according to the logits: # + id="P5UY8wko3jFp" sampled_token = tf.random.categorical(dec_result.logits[:, 0, :], num_samples=1) # + [markdown] id="-xTpX44VkzrY" # Decode the token as the first word of the output: # + id="lKXTLYu4IV7I" vocab = np.array(output_text_processor.get_vocabulary()) first_word = vocab[sampled_token.numpy()] first_word[:5] # + [markdown] id="LUQV6AXoQR7z" # Now use the decoder to generate a second set of logits. # # - Pass the same `enc_output` and `mask`, these haven't changed. # - Pass the sampled token as `new_tokens`. # - Pass the `decoder_state` the decoder returned last time, so the RNN continues with a memory of where it left off last time. # # + id="pX1VF9XDJTOM" dec_result, dec_state = decoder( DecoderInput(sampled_token, example_enc_output, mask=(example_tokens != 0)), state=dec_state) # + id="H1rs0XL7Y2aS" sampled_token = tf.random.categorical(dec_result.logits[:, 0, :], num_samples=1) first_word = vocab[sampled_token.numpy()] first_word[:5] # + [markdown] id="B6xyru86m914" # ## Training # # Now that you have all the model components, it's time to start training the model. You'll need: # # - A loss function and optimizer to perform the optimization. # - A training step function defining how to update the model for each input/target batch. # - A training loop to drive the training and save checkpoints. # + [markdown] id="_ch_71VbIRfK" # ### Define the loss function # + id="WmTHr5iV3jFr" class MaskedLoss(tf.keras.losses.Loss): def __init__(self): self.name = 'masked_loss' self.loss = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True, reduction='none') def __call__(self, y_true, y_pred): shape_checker = ShapeChecker() shape_checker(y_true, ('batch', 't')) shape_checker(y_pred, ('batch', 't', 'logits')) # Calculate the loss for each item in the batch. loss = self.loss(y_true, y_pred) shape_checker(loss, ('batch', 't')) # Mask off the losses on padding. mask = tf.cast(y_true != 0, tf.float32) shape_checker(mask, ('batch', 't')) loss *= mask # Return the total. return tf.reduce_sum(loss) # + [markdown] id="M5AgEBh2S404" # ### Implement the training step # + [markdown] id="r_G20Te1XSmJ" # Start with a model class, the training process will be implemented as the `train_step` method on this model. See [Customizing fit](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit) for details. # # Here the `train_step` method is a wrapper around the `_train_step` implementation which will come later. This wrapper includes a switch to turn on and off `tf.function` compilation, to make debugging easier. # + id="WWIyuy71TkJT" class TrainTranslator(tf.keras.Model): def __init__(self, embedding_dim, units, input_text_processor, output_text_processor, use_tf_function=True): super().__init__() # Build the encoder and decoder encoder = Encoder(input_text_processor.vocabulary_size(), embedding_dim, units) decoder = Decoder(output_text_processor.vocabulary_size(), embedding_dim, units) self.encoder = encoder self.decoder = decoder self.input_text_processor = input_text_processor self.output_text_processor = output_text_processor self.use_tf_function = use_tf_function self.shape_checker = ShapeChecker() def train_step(self, inputs): self.shape_checker = ShapeChecker() if self.use_tf_function: return self._tf_train_step(inputs) else: return self._train_step(inputs) # + [markdown] id="-i0i1x6jwsLm" # Overall the implementation for the `Model.train_step` method is as follows: # # 1. Receive a batch of `input_text, target_text` from the `tf.data.Dataset`. # 2. Convert those raw text inputs to token-embeddings and masks. # 3. Run the encoder on the `input_tokens` to get the `encoder_output` and `encoder_state`. # 4. Initialize the decoder state and loss. # 5. Loop over the `target_tokens`: # 1. Run the decoder one step at a time. # 2. Calculate the loss for each step. # 3. Accumulate the average loss. # 6. Calculate the gradient of the loss and use the optimizer to apply updates to the model's `trainable_variables`. # + [markdown] id="ngBjFw4BU5G7" # The `_preprocess` method, added below, implements steps #1 and #2: # + id="ZlYE68wzXoA8" def _preprocess(self, input_text, target_text): self.shape_checker(input_text, ('batch',)) self.shape_checker(target_text, ('batch',)) # Convert the text to token IDs input_tokens = self.input_text_processor(input_text) target_tokens = self.output_text_processor(target_text) self.shape_checker(input_tokens, ('batch', 's')) self.shape_checker(target_tokens, ('batch', 't')) # Convert IDs to masks. input_mask = input_tokens != 0 self.shape_checker(input_mask, ('batch', 's')) target_mask = target_tokens != 0 self.shape_checker(target_mask, ('batch', 't')) return input_tokens, input_mask, target_tokens, target_mask # + id="lHy6hzStrgjQ" TrainTranslator._preprocess = _preprocess # + [markdown] id="d3kvbcArc2y-" # The `_train_step` method, added below, handles the remaining steps except for actually running the decoder: # + id="Qs_gsISsYPpY" def _train_step(self, inputs): input_text, target_text = inputs (input_tokens, input_mask, target_tokens, target_mask) = self._preprocess(input_text, target_text) max_target_length = tf.shape(target_tokens)[1] with tf.GradientTape() as tape: # Encode the input enc_output, enc_state = self.encoder(input_tokens) self.shape_checker(enc_output, ('batch', 's', 'enc_units')) self.shape_checker(enc_state, ('batch', 'enc_units')) # Initialize the decoder's state to the encoder's final state. # This only works if the encoder and decoder have the same number of # units. dec_state = enc_state loss = tf.constant(0.0) for t in tf.range(max_target_length-1): # Pass in two tokens from the target sequence: # 1. The current input to the decoder. # 2. The target the target for the decoder's next prediction. new_tokens = target_tokens[:, t:t+2] step_loss, dec_state = self._loop_step(new_tokens, input_mask, enc_output, dec_state) loss = loss + step_loss # Average the loss over all non padding tokens. average_loss = loss / tf.reduce_sum(tf.cast(target_mask, tf.float32)) # Apply an optimization step variables = self.trainable_variables gradients = tape.gradient(average_loss, variables) self.optimizer.apply_gradients(zip(gradients, variables)) # Return a dict mapping metric names to current value return {'batch_loss': average_loss} # + id="KGwWHIxLrjGR" TrainTranslator._train_step = _train_step # + [markdown] id="F7g40o-mXyt5" # The `_loop_step` method, added below, executes the decoder and calculates the incremental loss and new decoder state (`dec_state`). # + id="9VrzgwztXzYJ" def _loop_step(self, new_tokens, input_mask, enc_output, dec_state): input_token, target_token = new_tokens[:, 0:1], new_tokens[:, 1:2] # Run the decoder one step. decoder_input = DecoderInput(new_tokens=input_token, enc_output=enc_output, mask=input_mask) dec_result, dec_state = self.decoder(decoder_input, state=dec_state) self.shape_checker(dec_result.logits, ('batch', 't1', 'logits')) self.shape_checker(dec_result.attention_weights, ('batch', 't1', 's')) self.shape_checker(dec_state, ('batch', 'dec_units')) # `self.loss` returns the total for non-padded tokens y = target_token y_pred = dec_result.logits step_loss = self.loss(y, y_pred) return step_loss, dec_state # + id="xj3I7VULrk1R" TrainTranslator._loop_step = _loop_step # + [markdown] id="WACCHvKWBQ9C" # ### Test the training step # # Build a `TrainTranslator`, and configure it for training using the `Model.compile` method: # + id="OA6bCske8TXm" translator = TrainTranslator( embedding_dim, units, input_text_processor=input_text_processor, output_text_processor=output_text_processor, use_tf_function=False) # Configure the loss and optimizer translator.compile( optimizer=tf.optimizers.Adam(), loss=MaskedLoss(), ) # + [markdown] id="6y5OnZDsB3sB" # Test out the `train_step`. For a text model like this the loss should start near: # + id="zHe-OudqCFGK" np.log(output_text_processor.vocabulary_size()) # + id="VwMU9cFEfjha" # %%time for n in range(10): print(translator.train_step([example_input_batch, example_target_batch])) print() # + [markdown] id="A-xqtsMbCUp2" # While it's easier to debug without a `tf.function` it does give a performance boost. So now that the `_train_step` method is working, try the `tf.function`-wrapped `_tf_train_step`, to maximize performance while training: # + id="UFUsTKQx0jaH" @tf.function(input_signature=[[tf.TensorSpec(dtype=tf.string, shape=[None]), tf.TensorSpec(dtype=tf.string, shape=[None])]]) def _tf_train_step(self, inputs): return self._train_step(inputs) # + id="2-bgU59jrztQ" TrainTranslator._tf_train_step = _tf_train_step # + id="KC8bRv_Gr3H9" translator.use_tf_function = True # + [markdown] id="EKMYNF_sIFb9" # The first call will be slow, because it traces the function. # + id="pLQZsX2dp1QK" translator.train_step([example_input_batch, example_target_batch]) # + [markdown] id="W3t2Hg7UISYi" # But after that it's usually 2-3x faster than the eager `train_step` method: # + id="UzXXMwjXCqqh" # %%time for n in range(10): print(translator.train_step([example_input_batch, example_target_batch])) print() # + [markdown] id="OIvigTqaEcu1" # A good test of a new model is to see that it can overfit a single batch of input. Try it, the loss should quickly go to zero: # + id="U-dIWMIBqK7b" losses = [] for n in range(100): print('.', end='') logs = translator.train_step([example_input_batch, example_target_batch]) losses.append(logs['batch_loss'].numpy()) print() plt.plot(losses) # + [markdown] id="aI02XFjoEt1k" # Now that you're confident that the training step is working, build a fresh copy of the model to train from scratch: # + id="Emgfgh4tAmJt" train_translator = TrainTranslator( embedding_dim, units, input_text_processor=input_text_processor, output_text_processor=output_text_processor) # Configure the loss and optimizer train_translator.compile( optimizer=tf.optimizers.Adam(), loss=MaskedLoss(), ) # + [markdown] id="hpObfY22IddU" # ### Train the model # # While there's nothing wrong with writing your own custom training loop, implementing the `Model.train_step` method, as in the previous section, allows you to run `Model.fit` and avoid rewriting all that boiler-plate code. # # This tutorial only trains for a couple of epochs, so use a `callbacks.Callback` to collect the history of batch losses, for plotting: # + id="J7m4mtnj80sq" class BatchLogs(tf.keras.callbacks.Callback): def __init__(self, key): self.key = key self.logs = [] def on_train_batch_end(self, n, logs): self.logs.append(logs[self.key]) batch_loss = BatchLogs('batch_loss') # + id="BQd_esVVoSf3" train_translator.fit(dataset, epochs=3, callbacks=[batch_loss]) # + id="38rLdlmtQHCm" plt.plot(batch_loss.logs) plt.ylim([0, 3]) plt.xlabel('Batch #') plt.ylabel('CE/token') # + [markdown] id="w0S_O_RzHmfe" # The visible jumps in the plot are at the epoch boundaries. # + [markdown] id="mU3Ce8M6I3rz" # ## Translate # # Now that the model is trained, implement a function to execute the full `text => text` translation. # # For this the model needs to invert the `text => token IDs` mapping provided by the `output_text_processor`. It also needs to know the IDs for special tokens. This is all implemented in the constructor for the new class. The implementation of the actual translate method will follow. # # Overall this is similar to the training loop, except that the input to the decoder at each time step is a sample from the decoder's last prediction. # + id="PO-CLL1LVBbM" class Translator(tf.Module): def __init__(self, encoder, decoder, input_text_processor, output_text_processor): self.encoder = encoder self.decoder = decoder self.input_text_processor = input_text_processor self.output_text_processor = output_text_processor self.output_token_string_from_index = ( tf.keras.layers.experimental.preprocessing.StringLookup( vocabulary=output_text_processor.get_vocabulary(), invert=True)) # The output should never generate padding, unknown, or start. index_from_string = tf.keras.layers.experimental.preprocessing.StringLookup( vocabulary=output_text_processor.get_vocabulary()) token_mask_ids = index_from_string(['', '[UNK]', '[START]']).numpy() token_mask = np.zeros([index_from_string.vocabulary_size()], dtype=np.bool) token_mask[np.array(token_mask_ids)] = True self.token_mask = token_mask self.start_token = index_from_string('[START]') self.end_token = index_from_string('[END]') # + id="iBQzFZ9uWU79" translator = Translator( encoder=train_translator.encoder, decoder=train_translator.decoder, input_text_processor=input_text_processor, output_text_processor=output_text_processor, ) # + [markdown] id="b59PN-UxqYrU" # ### Convert token IDs to text # + [markdown] id="-razg3Aso737" # The first method to implement is `tokens_to_text` which converts from token IDs to human readable text. # + id="8IjwKTwtmdFf" def tokens_to_text(self, result_tokens): shape_checker = ShapeChecker() shape_checker(result_tokens, ('batch', 't')) result_text_tokens = self.output_token_string_from_index(result_tokens) shape_checker(result_text_tokens, ('batch', 't')) result_text = tf.strings.reduce_join(result_text_tokens, axis=1, separator=' ') shape_checker(result_text, ('batch')) result_text = tf.strings.strip(result_text) shape_checker(result_text, ('batch',)) return result_text # + id="912aV0K7r90w" Translator.tokens_to_text = tokens_to_text # + [markdown] id="krBuAapkqNs9" # Input some random token IDs and see what it generates: # + id="cWCMHdoS32QN" example_output_tokens = tf.random.uniform( shape=[5, 2], minval=0, dtype=tf.int64, maxval=output_text_processor.vocabulary_size()) translator.tokens_to_text(example_output_tokens).numpy() # + [markdown] id="AC9De_kAqtaE" # ### Sample from the decoder's predictions # + [markdown] id="q5tno-2ksJv6" # This function takes the decoder's logit outputs and samples token IDs from that distribution: # + id="8lfuj3GcdD6e" def sample(self, logits, temperature): shape_checker = ShapeChecker() # 't' is usually 1 here. shape_checker(logits, ('batch', 't', 'vocab')) shape_checker(self.token_mask, ('vocab',)) token_mask = self.token_mask[tf.newaxis, tf.newaxis, :] shape_checker(token_mask, ('batch', 't', 'vocab'), broadcast=True) # Set the logits for all masked tokens to -inf, so they are never chosen. logits = tf.where(self.token_mask, -np.inf, logits) if temperature == 0.0: new_tokens = tf.argmax(logits, axis=-1) else: logits = tf.squeeze(logits, axis=1) new_tokens = tf.random.categorical(logits/temperature, num_samples=1) shape_checker(new_tokens, ('batch', 't')) return new_tokens # + id="4DpDnBdBdL9_" Translator.sample = sample # + [markdown] id="QwdHfGEfsmy5" # Test run this function on some random inputs: # + id="rwLT0nxXym80" example_logits = tf.random.normal([5, 1, output_text_processor.vocabulary_size()]) example_output_tokens = translator.sample(example_logits, temperature=1.0) example_output_tokens # + [markdown] id="NEWIKFIJ2HWM" # ### Implement the translation loop # # Here is a complete implementation of the text to text translation loop. # # This implementation collects the results into python lists, before using `tf.concat` to join them into tensors. # # This implementation statically unrolls the graph out to `max_length` iterations. # This is okay with eager execution in python. # + id="ZmOvVrZmwAxg" def translate_unrolled(self, input_text, *, max_length=50, return_attention=True, temperature=1.0): batch_size = tf.shape(input_text)[0] input_tokens = self.input_text_processor(input_text) enc_output, enc_state = self.encoder(input_tokens) dec_state = enc_state new_tokens = tf.fill([batch_size, 1], self.start_token) result_tokens = [] attention = [] done = tf.zeros([batch_size, 1], dtype=tf.bool) for _ in range(max_length): dec_input = DecoderInput(new_tokens=new_tokens, enc_output=enc_output, mask=(input_tokens!=0)) dec_result, dec_state = self.decoder(dec_input, state=dec_state) attention.append(dec_result.attention_weights) new_tokens = self.sample(dec_result.logits, temperature) # If a sequence produces an `end_token`, set it `done` done = done | (new_tokens == self.end_token) # Once a sequence is done it only produces 0-padding. new_tokens = tf.where(done, tf.constant(0, dtype=tf.int64), new_tokens) # Collect the generated tokens result_tokens.append(new_tokens) if tf.executing_eagerly() and tf.reduce_all(done): break # Convert the list of generates token ids to a list of strings. result_tokens = tf.concat(result_tokens, axis=-1) result_text = self.tokens_to_text(result_tokens) if return_attention: attention_stack = tf.concat(attention, axis=1) return {'text': result_text, 'attention': attention_stack} else: return {'text': result_text} # + id="JOmd8Y269MG3" Translator.translate = translate_unrolled # + [markdown] id="NxYXf3GNKKLS" # Run it on a simple input: # + id="hd2rgyHwVVrv" # %%time input_text = tf.constant([ 'hace mucho frio aqui.', # "It's really cold here." 'Esta es mi vida.', # "This is my life."" ]) result = translator.translate( input_text = input_text) print(result['text'][0].numpy().decode()) print(result['text'][1].numpy().decode()) print() # + [markdown] id="S-6cFyqeUPQm" # If you want to export this model you'll need to wrap this method in a `tf.function`. This basic implementation has a few issues if you try to do that: # # 1. The resulting graphs are very large and take a few seconds to build, save or load. # 2. You can't break from a statically unrolled loop, so it will always run `max_length` iterations, even if all the outputs are done. But even then it's marginally faster than eager execution. # # + id="_JhTZ5hOptO-" f = tf.function(input_signature=[tf.TensorSpec(dtype=tf.string, shape=[None])]) def tf_translate(self, input_text): return self.translate(input_text) Translator.tf_translate = tf_translate # + [markdown] id="fkccvHDvXCa8" # Run the `tf.function` once to compile it: # + id="_NzrixLvVBjQ" # %%time result = translator.tf_translate( input_text = input_text) # + id="USJdu00tVFbd" # %%time result = translator.tf_translate( input_text = input_text) print(result['text'][0].numpy().decode()) print(result['text'][1].numpy().decode()) print() # + id="EbQpyYs13jF_" #@title [Optional] Use a symbolic loop def translate_symbolic(self, input_text, *, max_length=50, return_attention=True, temperature=1.0): shape_checker = ShapeChecker() shape_checker(input_text, ('batch',)) batch_size = tf.shape(input_text)[0] # Encode the input input_tokens = self.input_text_processor(input_text) shape_checker(input_tokens, ('batch', 's')) enc_output, enc_state = self.encoder(input_tokens) shape_checker(enc_output, ('batch', 's', 'enc_units')) shape_checker(enc_state, ('batch', 'enc_units')) # Initialize the decoder dec_state = enc_state new_tokens = tf.fill([batch_size, 1], self.start_token) shape_checker(new_tokens, ('batch', 't1')) # Initialize the accumulators result_tokens = tf.TensorArray(tf.int64, size=1, dynamic_size=True) attention = tf.TensorArray(tf.float32, size=1, dynamic_size=True) done = tf.zeros([batch_size, 1], dtype=tf.bool) shape_checker(done, ('batch', 't1')) for t in tf.range(max_length): dec_input = DecoderInput(new_tokens=new_tokens, enc_output=enc_output, mask = (input_tokens!=0)) dec_result, dec_state = self.decoder(dec_input, state=dec_state) shape_checker(dec_result.attention_weights, ('batch', 't1', 's')) attention = attention.write(t, dec_result.attention_weights) new_tokens = self.sample(dec_result.logits, temperature) shape_checker(dec_result.logits, ('batch', 't1', 'vocab')) shape_checker(new_tokens, ('batch', 't1')) # If a sequence produces an `end_token`, set it `done` done = done | (new_tokens == self.end_token) # Once a sequence is done it only produces 0-padding. new_tokens = tf.where(done, tf.constant(0, dtype=tf.int64), new_tokens) # Collect the generated tokens result_tokens = result_tokens.write(t, new_tokens) if tf.reduce_all(done): break # Convert the list of generates token ids to a list of strings. result_tokens = result_tokens.stack() shape_checker(result_tokens, ('t', 'batch', 't0')) result_tokens = tf.squeeze(result_tokens, -1) result_tokens = tf.transpose(result_tokens, [1, 0]) shape_checker(result_tokens, ('batch', 't')) result_text = self.tokens_to_text(result_tokens) shape_checker(result_text, ('batch',)) if return_attention: attention_stack = attention.stack() shape_checker(attention_stack, ('t', 'batch', 't1', 's')) attention_stack = tf.squeeze(attention_stack, 2) shape_checker(attention_stack, ('t', 'batch', 's')) attention_stack = tf.transpose(attention_stack, [1, 0, 2]) shape_checker(attention_stack, ('batch', 't', 's')) return {'text': result_text, 'attention': attention_stack} else: return {'text': result_text} # + id="ngywxv1WYO_O" Translator.translate = translate_symbolic # + [markdown] id="lItV7qjEGsYc" # The initial implementation used python lists to collect the outputs. This uses `tf.range` as the loop iterator, allowing `tf.autograph` to convert the loop. The biggest change in this implementation is the use of `tf.TensorArray` instead of python `list` to accumulate tensors. `tf.TensorArray` is required to collect a variable number of tensors in graph mode. # + [markdown] id="AJ_NznOgZTxC" # With eager execution this implementation performs on par with the original: # + id="JRh66y-YYeBw" # %%time result = translator.translate( input_text = input_text) print(result['text'][0].numpy().decode()) print(result['text'][1].numpy().decode()) print() # + [markdown] id="l6B8W4_MZdX0" # But when you wrap it in a `tf.function` you'll notice two differences. # + id="WX6EF8KtYh20" @tf.function(input_signature=[tf.TensorSpec(dtype=tf.string, shape=[None])]) def tf_translate(self, input_text): return self.translate(input_text) Translator.tf_translate = tf_translate # + [markdown] id="9S0kQ-bBZswZ" # First: Graph creation is much faster (~10x), since it doesn't create `max_iterations` copies of the model. # + id="Eq8d40RKYoJa" # %%time result = translator.tf_translate( input_text = input_text) # + [markdown] id="2ABEwtKIZ6eE" # Second: The compiled function is much faster on small inputs (5x on this example), because it can break out of the loop. # + id="d5VdCLxPYrpz" # %%time result = translator.tf_translate( input_text = input_text) print(result['text'][0].numpy().decode()) print(result['text'][1].numpy().decode()) print() # + [markdown] id="eo5sf4jZaO2l" # ### Visualize the process # + [markdown] id="FzZzC2cJacTv" # The attention weights returned by the `translate` method show where the model was "looking" when it generated each output token. # # So the sum of the attention over the input should return all ones: # + id="UEd2GljgqQ-0" a = result['attention'][0] print(np.sum(a, axis=-1)) # + [markdown] id="k_HWQHcI2_h5" # Here is the attention distribution for the first output step of the first example. Note how the attention is now much more focused than it was for the untrained model: # + id="M8BHdqQujALu" _ = plt.bar(range(len(a[0, :])), a[0, :]) # + [markdown] id="qB13OG472Z3V" # Since there is some rough alignment between the input and output words, you expect the attention to be focused near the diagonal: # + id="xyeXuEYHd0kQ" plt.imshow(np.array(a), vmin=0.0) # + [markdown] id="mXECcNTn2mxN" # Here is some code to make a better attention plot: # + id="s5hQWlbN3jGF" #@title Labeled attention plots def plot_attention(attention, sentence, predicted_sentence): sentence = tf_lower_and_split_punct(sentence).numpy().decode().split() predicted_sentence = predicted_sentence.numpy().decode().split() + ['[END]'] fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1) attention = attention[:len(predicted_sentence), :len(sentence)] ax.matshow(attention, cmap='viridis', vmin=0.0) fontdict = {'fontsize': 14} ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90) ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) ax.set_xlabel('Input text') ax.set_ylabel('Output text') plt.suptitle('Attention weights') # + id="rrGawQv2eiA4" i=0 plot_attention(result['attention'][i], input_text[i], result['text'][i]) # + [markdown] id="JHBdOf9duumm" # Translate a few more sentences and plot them: # + id="WrAM0FDomq3E" # %%time three_input_text = tf.constant([ # This is my life. 'Esta es mi vida.', # Are they still home? 'ยฟTodavรญa estรกn en casa?', # Try to find out.' 'Tratar de descubrir.', ]) result = translator.tf_translate(three_input_text) for tr in result['text']: print(tr.numpy().decode()) print() # + id="-LjFp0AljOaZ" result['text'] # + id="v7QwIMrG-id2" i = 0 plot_attention(result['attention'][i], three_input_text[i], result['text'][i]) # + id="zYVoVf8P-lr-" i = 1 plot_attention(result['attention'][i], three_input_text[i], result['text'][i]) # + id="9sFvlZBk-me4" i = 2 plot_attention(result['attention'][i], three_input_text[i], result['text'][i]) # + [markdown] id="rA3xI3NzrRJt" # The short sentences often work well, but if the input is too long the model literally loses focus and stops providing reasonable predictions. There are two main reasons for this: # # 1. The model was trained with teacher-forcing feeding the correct token at each step, regardless of the model's predictions. The model could be made more robust if it were sometimes fed its own predictions. # 2. The model only has access to its previous output through the RNN state. If the RNN state gets corrupted, there's no way for the model to recover. [Transformers](transformer.ipynb) solve this by using self-attention in the encoder and decoder. # + id="-FUHFLEvSMbG" long_input_text = tf.constant([inp[-1]]) import textwrap print('Expected output:\n', '\n'.join(textwrap.wrap(targ[-1]))) # + id="lDa_8NaN_RUy" result = translator.tf_translate(long_input_text) i = 0 plot_attention(result['attention'][i], long_input_text[i], result['text'][i]) _ = plt.suptitle('This never works') # + [markdown] id="mMA9Pp71nzH9" # ## Export # + [markdown] id="5rLMNOmsKoXe" # Once you have a model you're satisfied with you might want to export it as a `tf.saved_model` for use outside of this python program that created it. # # Since the model is a subclass of `tf.Module` (through `keras.Model`), and all the functionality for export is compiled in a `tf.function` the model should export cleanly with `tf.saved_model.save`: # + [markdown] id="NP2dNtEXJPEL" # Now that the function has been traced it can be exported using `saved_model.save`: # + id="OyvxT5V0_X5B" tf.saved_model.save(translator, 'translator', signatures={'serving_default': translator.tf_translate}) # + id="-I0j3i3ekOba" reloaded = tf.saved_model.load('translator') result = reloaded.tf_translate(three_input_text) # + id="GXZF__FZXJCm" # %%time result = reloaded.tf_translate(three_input_text) for tr in result['text']: print(tr.numpy().decode()) print() # + [markdown] id="RTe5P5ioMJwN" # ## Next steps # # * [Download a different dataset](http://www.manythings.org/anki/) to experiment with translations, for example, English to German, or English to French. # * Experiment with training on a larger dataset, or using more epochs. # * Try the [transformer tutorial](transformer.ipynb) which implements a similar translation task but uses a transformer layers instead of RNNs. This version also uses a `text.BertTokenizer` to implement wordpiece tokenization. # * Have a look at the [tensorflow_addons.seq2seq](https://www.tensorflow.org/addons/tutorials/networks_seq2seq_nmt) for implementing this sort of sequence to sequence model. The `tfa.seq2seq` package includes higher level functionality like `seq2seq.BeamSearchDecoder`.
docs/tutorials/nmt_with_attention.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- import adaboost import numpy as np datMat,classLabels = adaboost.loadSimpData() reload(adaboost) D = np.mat(np.ones((5,1))/5) adaboost.buildStump(datMat,classLabels,D) # ๅˆ†็ฑป reload(adaboost) datArr,labelArr = adaboost.loadSimpData() classifierArr, aggClassEst = adaboost.adaBoostTrainDS(datArr,labelArr,30) print classifierArr print type(classifierArr) adaboost.adaClassify([0,0],classifierArr) adaboost.adaClassify([[5,5],[0,0]],classifierArr) datArr,labelArr = adaboost.loadDataSet('horseColicTraining2.txt') classifierArray,agg = adaboost.adaBoostTrainDS(datArr,labelArr,10) # + testArr,testLabelArr = adaboost.loadDataSet('horseColicTest2.txt') prediction10 = adaboost.adaClassify(testArr,classifierArray) errArr = np.mat(np.ones((67,1))) print errArr[prediction10!=np.mat(testLabelArr).T].sum() # -
Intelligence/Machine_Learning_in_Action/Ch07/.ipynb_checkpoints/adaboost-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # %config InlineBackend.figure_format = 'svg' from scipy.io import loadmat x = loadmat('walsh.mat') # - np.shape(x['code'][0]) c1=np.array([-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-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,-1,0,1,0,-1,0,1,0]) t = np.arange(0, 512, 1) data1 = np.cos( 2 * np.pi / 512 * t * 256) + 1j * np.sin(2 * np.pi / 512 * t * 256) data2 = np.cos( 2 * np.pi / 512 * t * 128+np.pi) + 1j * np.sin(2 * np.pi / 512 * t * 128+np.pi) data3 = np.cos( 2 * np.pi / 512 * t * 16) + 1j * np.sin(2 * np.pi / 512 * t * 16) data4 = np.cos( 2 * np.pi / 512 * t * 400+np.pi/4) + 1j * np.sin(2 * np.pi / 512 * t * 400+np.pi/4) plt.plot(t, np.real(data1)) plt.plot(t, np.real(data2)) plt.plot(t, np.real(data3)) plt.plot(t, np.real(data4)) plt.plot(np.abs(np.fft.fft(data1))) plt.plot(np.abs(np.fft.fft(data2))) plt.plot(np.abs(np.fft.fft(data3))) plt.plot(np.abs(np.fft.fft(data4))) # addition=data1*x['code'][0]+data2*x['code'][1]+data3*x['code'][2]+data4*x['code'][3] addition = data1 * x['code'][0] + data2 * x['code'][2] + data4 * x['code'][4] plt.plot(np.abs(np.fft.fft(addition * x['code'][0]))) plt.plot(np.abs(np.fft.fft(addition * x['code'][2]))) plt.plot(np.real(np.fft.fft(addition * x['code'][4]))) plt.imshow(x['code'])
cdm.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Continuous Time FW # ## Huber Regression with nuclear norm constraints import numpy as np from numpy.linalg import norm import pylab as plt from scipy import sparse import pandas as pd from sklearn.preprocessing import StandardScaler import pickle from scipy.sparse.linalg import svds from frank_wolfe import FW_matfact data = pd.read_csv('data/movielens100k.csv', names=['user id', 'item id', 'rating', 'timestamp']) B = np.double(pd.pivot_table(data, values='rating', index='user id', columns='item id').values)-3. BI,BJ = np.where(np.logical_not(np.isnan(B))) # + def huber(t,rho): x = t*0. x[np.less_equal(np.abs(t),rho)] = np.power(t[np.less_equal(np.abs(t),rho)],2.)/2. x[np.greater(np.abs(t),rho)] = np.abs(x[np.greater(np.abs(t),rho)] -rho) + np.power(rho,2.)/2. return x def der_huber(t,rho): x = t*0. x[np.less_equal(np.abs(t),rho)] = t[np.less_equal(np.abs(t),rho)] x[np.greater(t,rho)] = rho x[np.less(t,-rho)] = -rho return x def get_atom(G): u, s, v = svds(G, k=1, which='LM') return np.outer(u, v) def obj_fun(x, rho): return np.sum(huber(np.nan_to_num(B-x),rho)) def dFun(x,alpha,rho): grad = der_huber(np.nan_to_num(x-B), rho) S = get_atom(-grad)*alpha d = S-x.copy() return d, grad def dFun_mom(x,alpha,rho, theta,y,v, gamma): y = x * (1.-gamma) + gamma * v grady = der_huber(np.nan_to_num(y-B), rho) theta = theta * (1.-gamma) + gamma * grady v = get_atom(-theta)*alpha d = v-x return d, grady, theta,y,v # + alpha = 1000. rho = 10. T=100 def obj_fun_2(z) : return obj_fun(z, rho) # disc_type can be 'FE', 'midpoint', 'rk44', 'rk4', 'rk5' sol = FW_matfact(obj_fun_2, dFun, dFun_mom, B.shape, alpha,rho, T=T, n=T, disc_type ='FE', line_search = False, momentum = False) # + colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plt.figure(figsize=(9,3)) plt.subplot(1,2,1) plt.plot(sol[2]) plt.subplot(1,2,2) plt.plot(sol[1],sol[2]) plt.subplot(1,2,1) plt.yscale('log') plt.xscale('log') plt.xlabel('Iterations') plt.ylabel('Gap') plt.subplot(1,2,2) plt.yscale('log') plt.xscale('log') plt.xlabel('Gradient/LMO calls') plt.ylabel('Gap') plt.tight_layout() # -
Python/matfact_script.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="7UmYrQ38hy_g" # # Latent ODE for Stock Data # # # + colab={"base_uri": "https://localhost:8080/"} id="c8BMb4s2hy_h" outputId="8ec50860-e92b-4469-a9a8-3ea9858a23e7" # Install the latest version of author's repo neural ode implementation # !git clone https://github.com/rtqichen/torchdiffeq.git # !cd torchdiffeq && pip install -e . # !pip install yfinance # !ls torchdiffeq/torchdiffeq # + [markdown] id="9cSqPUFvhy_j" # # Libraries # + id="gnauJ9FBhy_k" # run_models.py import os import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot import matplotlib.pyplot as plt import time import datetime import argparse import numpy as np import pandas as pd from random import SystemRandom from sklearn import model_selection import torch import torch.nn as nn from torch.nn.functional import relu import torch.optim as optim import utils as utils from data import * # from lib.plotting import * # from lib.rnn_baselines import * # from lib.ode_rnn import * # from lib.create_latent_ode_model import create_LatentODE_model # from lib.parse_datasets import parse_datasets # from lib.ode_func import ODEFunc, ODEFunc_w_Poisson from diffeq_solver import DiffeqSolver # from mujoco_physics import HopperPhysics from utils import compute_loss_all_batches import sys # print(sys.argv[1:]) # Libraries for downloading data from pandas_datareader import data as pdr import yfinance as yf import os import matplotlib.pyplot as plt import pandas as pd import numpy as np # Libraries for parsing data from torch.distributions import uniform from torch.utils.data import DataLoader from sklearn import model_selection import random from utils import get_dict_template # Libraries for encoder_decoder.py from torch.distributions import Categorical, Normal from torch.nn.modules.rnn import LSTM, GRU from utils import get_device # Libraries for likelihood_eval.py import gc import sklearn as sk from torch.distributions.multivariate_normal import MultivariateNormal from torch.distributions.normal import Normal from torch.distributions import kl_divergence, Independent # Libraries for base_models.py from torch.nn.modules.rnn import GRUCell, LSTMCell, RNNCellBase from torch.nn.parameter import Parameter # Libraries for ode_func.py from torch.nn.utils.spectral_norm import spectral_norm # + [markdown] id="PMVN3oEthy_l" # # Parameters, Manual Seed, ExperimentID # + id="UJGcORZ0hy_l" # Generative model for noisy data based on ODE parser = argparse.ArgumentParser('Latent ODE') # n = size of the dataset parser.add_argument('-n', type=int, default=2000, help="Size of the dataset") # n_iters = 50 parser.add_argument('--niters', type=int, default=100) parser.add_argument('--lr', type=float, default=1e-3, help="Starting learning rate.") # batch_size = 50 parser.add_argument('-b', '--batch-size', type=int, default=50) parser.add_argument('--viz', action='store_true', help="Show plots while training") parser.add_argument('--save', type=str, default='experiments/', help="Path for save checkpoints") parser.add_argument('--load', type=str, default='77', help="ID of the experiment to load for evaluation. If None, run a new experiment.") parser.add_argument('-r', '--random-seed', type=int, default=1991, help="Random_seed") # dataset = stock_lag5_forecast5 parser.add_argument('--dataset', type=str, default='stock_lag5_forecast5', help="Dataset to load. Available: stock_lag5_forecast5") parser.add_argument('-s', '--sample-tp', type=float, default=None, help="Number of time points to sub-sample." "If > 1, subsample exact number of points. If the number is in [0,1], take a percentage of available points per time series. If None, do not subsample") parser.add_argument('-c', '--cut-tp', type=int, default=None, help="Cut out the section of the timeline of the specified length (in number of points)." "Used for periodic function demo.") parser.add_argument('--quantization', type=float, default=0.1, help="Quantization on the physionet dataset." "Value 1 means quantization by 1 hour, value 0.1 means quantization by 0.1 hour = 6 min") parser.add_argument('--latent-ode', default = True, action='store_true', help="Run Latent ODE seq2seq model") parser.add_argument('--z0-encoder', type=str, default='odernn', help="Type of encoder for Latent ODE model: odernn or rnn") parser.add_argument('--classic-rnn', action='store_true', help="Run RNN baseline: classic RNN that sees true points at every point. Used for interpolation only.") parser.add_argument('--rnn-cell', default="gru", help="RNN Cell type. Available: gru (default), expdecay") parser.add_argument('--input-decay', action='store_true', help="For RNN: use the input that is the weighted average of impirical mean and previous value (like in GRU-D)") parser.add_argument('--ode-rnn', action='store_true', help="Run ODE-RNN baseline: RNN-style that sees true points at every point. Used for interpolation only.") parser.add_argument('--rnn-vae', action='store_true', help="Run RNN baseline: seq2seq model with sampling of the h0 and ELBO loss.") # latents = input_dim parser.add_argument('-l', '--latents', type=int, default=10, help="Size of the latent state") # rec_dims = more than 2*input_dim parser.add_argument('--rec-dims', type=int, default=25, help="Dimensionality of the recognition model (ODE or RNN).") parser.add_argument('--rec-layers', type=int, default=3, help="Number of layers in ODE func in recognition ODE") parser.add_argument('--gen-layers', type=int, default=3, help="Number of layers in ODE func in generative ODE") # units for ODE func parser.add_argument('-u', '--units', type=int, default=300, help="Number of units per layer in ODE func") # units for GRU parser.add_argument('-g', '--gru-units', type=int, default=100, help="Number of units per layer in each of GRU update networks") parser.add_argument('--poisson', action='store_true', help="Model poisson-process likelihood for the density of events in addition to reconstruction.") parser.add_argument('--classif', action='store_true', help="Include binary classification loss -- used for Physionet dataset for hospiral mortality") parser.add_argument('--linear-classif', action='store_true', help="If using a classifier, use a linear classifier instead of 1-layer NN") # extrap = True parser.add_argument('--extrap', default = True, action='store_true', help="Set extrapolation mode. If this flag is not set, run interpolation mode.") # timesteps = lag+forecast parser.add_argument('-t', '--timepoints', type=int, default=10, help="Total number of time-points") parser.add_argument('--max-t', type=float, default=5., help="We subsample points in the interval [0, args.max_tp]") parser.add_argument('--noise-weight', type=float, default=0.01, help="Noise amplitude for generated traejctories") sys.argv = ['-f'] args = parser.parse_args() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # file_name = os.path.basename(__file__)[:-3] utils.makedirs(args.save) # saves in 'experiments/' folder # + id="gbFeze76hy_n" colab={"base_uri": "https://localhost:8080/"} outputId="efd38df0-fef6-4d44-926b-b329d378abe7" torch.manual_seed(args.random_seed) np.random.seed(args.random_seed) experimentID = args.load # None # print(f"experimentID is {experimentID}") if experimentID is None: # Make a new experiment ID experimentID = int(SystemRandom().random()*100000) # from random import SystemRandom print(f"experimentID is {experimentID}") ckpt_path = os.path.join(args.save, "experiment_" + str(experimentID) + '.ckpt') # print(f"ckpt_path is {ckpt_path}") start = time.time() # print("Sampling dataset of {} training examples".format(args.n)) # n is size of the dataset # print(f"args is {str(args)}") input_command = sys.argv # print(f"input_command is {input_command}") ind = [i for i in range(len(input_command)) if input_command[i] == "--load"] # print(f"ind is {ind}") # print(f"len(ind) is {len(ind)}") if len(ind) == 1: ind = ind[0] input_command = input_command[:ind] + input_command[(ind+2):] input_command = " ".join(input_command) # print(f"input_command is {input_command}") utils.makedirs("results/") # + [markdown] id="b8Ld41k7hy_o" # # Get Dataset # + id="zC70xR81hy_p" # # Uncomment to get the training data of stock data with lag and forecast # # 1. Get Open and Close Price of asset (o, c) for each trading day. # # libraries # dict_tickers = { # 'Apple': 'AAPL', # 'Microsoft': 'MSFT', # 'Google': 'GOOG', # 'Bitcoin': 'BTC-USD', # 'Facebook': 'FB', # 'Walmart': 'WMT', # 'Amazon': 'AMZN', # 'CVS': 'CVS', # 'Berkshire': 'BRK-B', # 'ExxonMobil': 'XOM', # 'AtandT': 'T', # 'Costco': 'COST', # 'Walgreens': 'WBA', # 'Kroger': 'KR', # 'JPMorgan': 'JPM', # 'Verizon': 'VZ', # 'FordMotor': 'F', # 'GeneralMotors': 'GM', # 'Dell': 'DELL', # 'BankOfAmerica': 'BAC', # 'Target': 'TGT', # 'GeneralElectric': 'GE', # 'JohnsonandJohnson': 'JNJ', # 'Nvidia': 'NVDA', # 'Intel': 'INTC', # } # period = '1d' # start='2000-1-1' # end='2021-8-31' # # Creating a path to save the data # path = f"raw-stock-data/data-{start.split('-')[0]}-{end.split('-')[0]}" # if not os.path.exists(path): # # https://appdividend.com/2021/07/03/how-to-create-directory-if-not-exist-in-python/ # # Create a new directory # os.makedirs(path) # print(f"{path} directory is created") # # Downloading the data # for tickerName, ticker in dict_tickers.items(): # tickerName = tickerName # ticker = ticker # filepath = f"{path}/{tickerName}.csv" # download_raw_stock_data(filepath, ticker, start, end, period) # # print('\n') # # print(f"The size of each asset") # for tickerName in dict_tickers.keys(): # df = pd.read_csv(f"{path}/{tickerName}.csv") # print(f"{tickerName} size: {len(df)}") # # 2. Get weekly data. # # 3. Transform $d_{i}$ to sequences of lag * len($d_{i}$) length. # week_sequence = {} # lag = 5 # forecast = 5 # for tickerName in dict_tickers.keys(): # filepath = f"{path}/{tickerName}.csv" # # Get the data in the required format # data = stockDataTransformer(filepath) # # # Total Data Size # data_size = data.shape[0] # # print(f"{tickerName} data.shape {data.shape}") # data_orig = series_to_supervised(data, lag, forecast).values # # print(f'{tickerName} Data Original after series to supervised on data {data_orig.shape}') # week_sequence[tickerName] = data_orig # # print('\n') # # 4. Bundle all sequences together # data = week_sequence['Apple'] # for tickerName in week_sequence.keys(): # if tickerName != 'Apple': # data1 = week_sequence[tickerName] # data = np.concatenate((data, data1)) # print(f"data.shape {data.shape}") # + id="imjYAxRYi2Xc" # training_path = 'data' # if not os.path.exists(training_path): # # https://appdividend.com/2021/07/03/how-to-create-directory-if-not-exist-in-python/ # # Create a new directory # os.makedirs(training_path) # print(f"{path} directory is created") # data_df = pd.DataFrame(data) # data_df.to_csv(f"{training_path}/data-lag{lag}-forecast{forecast}.csv") # + id="S4Tlm4XYhy_p" colab={"base_uri": "https://localhost:8080/"} outputId="2c8de4cb-ca50-4de5-89c5-3b0b6da03517" # Importing the data with index as the first column training_path = 'data' cluster = 1 lag = 5 forecast = 5 data = np.load(f"{training_path}/cluster_{cluster}.npy") data_df = pd.DataFrame(data) data_df.to_csv(f"{training_path}/cluster_{cluster}.csv") print(f"data.shape {data.shape}") # Reshape data to (data.shape[0], lag+forecast, data.shape[1]) data = data.reshape(data.shape[0], lag+forecast, 10) # print(f"data.shape {data.shape}") # Convert data to tensor data = torch.from_numpy(data).float().to(device) print(f"data.shape {data.shape}") # + [markdown] id="XkMnH9Gbhy_q" # # Parse Dataset # + id="K-Rkuecghy_q" ########################### # Latent ODEs for Stock Data # Authors: <NAME> ########################### class StockData(object): def __init__(self, root, download = True, generate=False, device = torch.device("cpu")): self.root = root if download: data = self._download() if generate: self._generate_dataset() if not self._check_exists(): raise RuntimeError('Dataset not found.' + ' You can use download=True to download it') data_file = os.path.join(self.data_folder, training_file) data = pd.read_csv(os.path.join(self.root, training_file), index_col=0).values # Reshape data to (data.shape[0], lag+forecast, data.shape[1]) data = data.reshape(data.shape[0], lag+forecast, D) # Convert data to tensor self.data = torch.from_numpy(data).float().to(device) self.data, self.data_min, self.data_max = utils.normalize_data(self.data) self.device =device def _download(self): if self._check_exists(): return if not os.path.exists(self.data_folder): os.makedirs(self.data_folder, exist_ok=True) data = pd.read_csv(os.path.join(self.root, training_file), index_col=0).values # Reshape data to (data.shape[0], lag+forecast, data.shape[1]) data = data.reshape(data.shape[0], lag+forecast, data.shape[1]) return data def _check_exists(self): return os.path.exists(os.path.join(self.data_folder, training_file)) @property def data_folder(self): return os.path.join(self.root) # def __getitem__(self, index): # return self.data[index] def get_dataset(self): return self.data def __len__(self): return len(self.data) def size(self, ind = None): if ind is not None: return self.data.shape[ind] return self.data.shape def __repr__(self): fmt_str = 'Dataset ' + self.__class__.__name__ + '\n' fmt_str += ' Number of datapoints: {}\n'.format(self.__len__()) fmt_str += ' Root Location: {}\n'.format(self.root) return fmt_str # + id="TEI5y8U2hy_r" def parse_datasets(args, device): # Parse datasets def basic_collate_fn(batch, time_steps, args = args, device = device, data_type = "train"): batch = torch.stack(batch) data_dict = { "data": batch, "time_steps": time_steps} data_dict = utils.split_and_subsample_batch(data_dict, args, data_type = data_type) return data_dict dataset_name = args.dataset n_total_tp = args.timepoints + args.extrap max_t_extrap = args.max_t / args.timepoints * n_total_tp ################################################################## # Stock Data with lag and forecast dataset if dataset_name == "stock_lag5_forecast5": dataset_obj = StockData(root='data', download=True, generate=False, device = device) dataset = dataset_obj.get_dataset() dataset = dataset.to(device) n_tp_data = dataset[:].shape[1] # Time steps that are used later on for exrapolation time_steps = torch.arange(start=0, end = n_tp_data, step=1).float().to(device) time_steps = time_steps / len(time_steps) dataset = dataset.to(device) time_steps = time_steps.to(device) if not args.extrap: # Creating dataset for interpolation # sample time points from different parts of the timeline, # so that the model learns from different parts of hopper trajectory n_traj = len(dataset) n_tp_data = dataset.shape[1] n_reduced_tp = args.timepoints # sample time points from different parts of the timeline, # so that the model learns from different parts of hopper trajectory start_ind = np.random.randint(0, high=n_tp_data - n_reduced_tp +1, size=n_traj) end_ind = start_ind + n_reduced_tp sliced = [] for i in range(n_traj): sliced.append(dataset[i, start_ind[i] : end_ind[i], :]) dataset = torch.stack(sliced).to(device) time_steps = time_steps[:n_reduced_tp] # Split into train and test by the time sequences train_y, test_y = utils.split_train_test(dataset, train_fraq = 0.8) n_samples = len(dataset) input_dim = dataset.size(-1) batch_size = min(args.batch_size, args.n) train_dataloader = DataLoader(train_y, batch_size = batch_size, shuffle=False, collate_fn= lambda batch: basic_collate_fn(batch, time_steps, data_type = "train")) test_dataloader = DataLoader(test_y, batch_size = n_samples, shuffle=False, collate_fn= lambda batch: basic_collate_fn(batch, time_steps, data_type = "test")) data_objects = {"dataset_obj": dataset_obj, "train_dataloader": utils.inf_generator(train_dataloader), "test_dataloader": utils.inf_generator(test_dataloader), "input_dim": input_dim, "n_train_batches": len(train_dataloader), "n_test_batches": len(test_dataloader)} return data_objects ################################################################## # Physionet dataset if dataset_name == "physionet": train_dataset_obj = PhysioNet('data/physionet', train=True, quantization = args.quantization, download=True, n_samples = min(10000, args.n), device = device) # Use custom collate_fn to combine samples with arbitrary time observations. # Returns the dataset along with mask and time steps test_dataset_obj = PhysioNet('data/physionet', train=False, quantization = args.quantization, download=True, n_samples = min(10000, args.n), device = device) # Combine and shuffle samples from physionet Train and physionet Test total_dataset = train_dataset_obj[:len(train_dataset_obj)] if not args.classif: # Concatenate samples from original Train and Test sets # Only 'training' physionet samples are have labels. Therefore, if we do classifiction task, we don't need physionet 'test' samples. total_dataset = total_dataset + test_dataset_obj[:len(test_dataset_obj)] # Shuffle and split train_data, test_data = model_selection.train_test_split(total_dataset, train_size= 0.8, random_state = 42, shuffle = True) record_id, tt, vals, mask, labels = train_data[0] n_samples = len(total_dataset) input_dim = vals.size(-1) batch_size = min(min(len(train_dataset_obj), args.batch_size), args.n) data_min, data_max = get_data_min_max(total_dataset) train_dataloader = DataLoader(train_data, batch_size= batch_size, shuffle=False, collate_fn= lambda batch: variable_time_collate_fn(batch, args, device, data_type = "train", data_min = data_min, data_max = data_max)) test_dataloader = DataLoader(test_data, batch_size = n_samples, shuffle=False, collate_fn= lambda batch: variable_time_collate_fn(batch, args, device, data_type = "test", data_min = data_min, data_max = data_max)) attr_names = train_dataset_obj.params data_objects = {"dataset_obj": train_dataset_obj, "train_dataloader": utils.inf_generator(train_dataloader), "test_dataloader": utils.inf_generator(test_dataloader), "input_dim": input_dim, "n_train_batches": len(train_dataloader), "n_test_batches": len(test_dataloader), "attr": attr_names, #optional "classif_per_tp": False, #optional "n_labels": 1} #optional return data_objects ################################################################## # Human activity dataset if dataset_name == "activity": n_samples = min(10000, args.n) dataset_obj = PersonActivity('data/PersonActivity', download=True, n_samples = n_samples, device = device) print(dataset_obj) # Use custom collate_fn to combine samples with arbitrary time observations. # Returns the dataset along with mask and time steps # Shuffle and split train_data, test_data = model_selection.train_test_split(dataset_obj, train_size= 0.8, random_state = 42, shuffle = True) train_data = [train_data[i] for i in np.random.choice(len(train_data), len(train_data))] test_data = [test_data[i] for i in np.random.choice(len(test_data), len(test_data))] record_id, tt, vals, mask, labels = train_data[0] input_dim = vals.size(-1) batch_size = min(min(len(dataset_obj), args.batch_size), args.n) train_dataloader = DataLoader(train_data, batch_size= batch_size, shuffle=False, collate_fn= lambda batch: variable_time_collate_fn_activity(batch, args, device, data_type = "train")) test_dataloader = DataLoader(test_data, batch_size=n_samples, shuffle=False, collate_fn= lambda batch: variable_time_collate_fn_activity(batch, args, device, data_type = "test")) data_objects = {"dataset_obj": dataset_obj, "train_dataloader": utils.inf_generator(train_dataloader), "test_dataloader": utils.inf_generator(test_dataloader), "input_dim": input_dim, "n_train_batches": len(train_dataloader), "n_test_batches": len(test_dataloader), "classif_per_tp": True, #optional "n_labels": labels.size(-1)} return data_objects ########### 1d datasets ########### # Sampling args.timepoints time points in the interval [0, args.max_t] # Sample points for both training sequence and explapolation (test) distribution = uniform.Uniform(torch.Tensor([0.0]),torch.Tensor([max_t_extrap])) time_steps_extrap = distribution.sample(torch.Size([n_total_tp-1]))[:,0] time_steps_extrap = torch.cat((torch.Tensor([0.0]), time_steps_extrap)) time_steps_extrap = torch.sort(time_steps_extrap)[0] dataset_obj = None ################################################################## # Sample a periodic function if dataset_name == "periodic": dataset_obj = Periodic_1d( init_freq = None, init_amplitude = 1., final_amplitude = 1., final_freq = None, z0 = 1.) ################################################################## if dataset_obj is None: raise Exception("Unknown dataset: {}".format(dataset_name)) dataset = dataset_obj.sample_traj(time_steps_extrap, n_samples = args.n, noise_weight = args.noise_weight) # Process small datasets dataset = dataset.to(device) time_steps_extrap = time_steps_extrap.to(device) train_y, test_y = utils.split_train_test(dataset, train_fraq = 0.8) n_samples = len(dataset) input_dim = dataset.size(-1) batch_size = min(args.batch_size, args.n) train_dataloader = DataLoader(train_y, batch_size = batch_size, shuffle=False, collate_fn= lambda batch: basic_collate_fn(batch, time_steps_extrap, data_type = "train")) test_dataloader = DataLoader(test_y, batch_size = args.n, shuffle=False, collate_fn= lambda batch: basic_collate_fn(batch, time_steps_extrap, data_type = "test")) data_objects = {#"dataset_obj": dataset_obj, "train_dataloader": utils.inf_generator(train_dataloader), "test_dataloader": utils.inf_generator(test_dataloader), "input_dim": input_dim, "n_train_batches": len(train_dataloader), "n_test_batches": len(test_dataloader)} return data_objects # + id="xvdaU1g4hy_s" colab={"base_uri": "https://localhost:8080/"} outputId="08bfb518-1472-481e-f3df-76ab6f746d2b" lag = 5 forecast = 5 T = lag+forecast print(f"T is {T}") D = 10 print(f"D is {D}") root = 'data' n_training_samples = data.shape[0] training_file = f'cluster_{cluster}.csv' data_obj = parse_datasets(args, device) input_dim = data_obj["input_dim"] print(f"input_dim is {input_dim}") classif_per_tp = False if ("classif_per_tp" in data_obj): # do classification per time point rather than on a time series as a whole classif_per_tp = data_obj["classif_per_tp"] if args.classif and (args.dataset == "hopper" or args.dataset == "periodic"): raise Exception("Classification task is not available for MuJoCo and 1d datasets") # + [markdown] id="vN8eEmH-hy_s" # # n_labels, obsrv_std, z0_prior # + id="5wMtb7FQhy_s" n_labels = 1 if args.classif: if ("n_labels" in data_obj): n_labels = data_obj["n_labels"] else: raise Exception("Please provide number of labels for classification task") ################################################################## # Create the model obsrv_std = 0.01 if args.dataset == "stock_lag5_forecast5": obsrv_std = 1e-3 obsrv_std = torch.Tensor([obsrv_std]).to(device) z0_prior = Normal(torch.Tensor([0.0]).to(device), torch.Tensor([1.]).to(device)) # + [markdown] id="58GzgLWxhy_s" # # args.latent_ode # + [markdown] id="ExKiCiHthy_s" # ## encoder_decoder.py # + id="1pKHw5pqhy_t" # GRU description: # http://www.wildml.com/2015/10/recurrent-neural-network-tutorial-part-4-implementing-a-grulstm-rnn-with-python-and-theano/ class GRU_unit(nn.Module): def __init__(self, latent_dim, input_dim, update_gate = None, reset_gate = None, new_state_net = None, n_units = 100, device = torch.device("cpu")): super(GRU_unit, self).__init__() if update_gate is None: self.update_gate = nn.Sequential( nn.Linear(latent_dim * 2 + input_dim, n_units), nn.Tanh(), nn.Linear(n_units, latent_dim), nn.Sigmoid()) utils.init_network_weights(self.update_gate) else: self.update_gate = update_gate if reset_gate is None: self.reset_gate = nn.Sequential( nn.Linear(latent_dim * 2 + input_dim, n_units), nn.Tanh(), nn.Linear(n_units, latent_dim), nn.Sigmoid()) utils.init_network_weights(self.reset_gate) else: self.reset_gate = reset_gate if new_state_net is None: self.new_state_net = nn.Sequential( nn.Linear(latent_dim * 2 + input_dim, n_units), nn.Tanh(), nn.Linear(n_units, latent_dim * 2)) utils.init_network_weights(self.new_state_net) else: self.new_state_net = new_state_net def forward(self, y_mean, y_std, x, masked_update = True): y_concat = torch.cat([y_mean, y_std, x], -1) update_gate = self.update_gate(y_concat) reset_gate = self.reset_gate(y_concat) concat = torch.cat([y_mean * reset_gate, y_std * reset_gate, x], -1) new_state, new_state_std = utils.split_last_dim(self.new_state_net(concat)) new_state_std = new_state_std.abs() new_y = (1-update_gate) * new_state + update_gate * y_mean new_y_std = (1-update_gate) * new_state_std + update_gate * y_std assert(not torch.isnan(new_y).any()) if masked_update: # IMPORTANT: assumes that x contains both data and mask # update only the hidden states for hidden state only if at least one feature is present for the current time point n_data_dims = x.size(-1)//2 mask = x[:, :, n_data_dims:] utils.check_mask(x[:, :, :n_data_dims], mask) mask = (torch.sum(mask, -1, keepdim = True) > 0).float() assert(not torch.isnan(mask).any()) new_y = mask * new_y + (1-mask) * y_mean new_y_std = mask * new_y_std + (1-mask) * y_std if torch.isnan(new_y).any(): print("new_y is nan!") print(mask) print(y_mean) print(prev_new_y) exit() new_y_std = new_y_std.abs() return new_y, new_y_std class Encoder_z0_RNN(nn.Module): def __init__(self, latent_dim, input_dim, lstm_output_size = 20, use_delta_t = True, device = torch.device("cpu")): super(Encoder_z0_RNN, self).__init__() self.gru_rnn_output_size = lstm_output_size self.latent_dim = latent_dim self.input_dim = input_dim self.device = device self.use_delta_t = use_delta_t self.hiddens_to_z0 = nn.Sequential( nn.Linear(self.gru_rnn_output_size, 50), nn.Tanh(), nn.Linear(50, latent_dim * 2),) utils.init_network_weights(self.hiddens_to_z0) input_dim = self.input_dim if use_delta_t: self.input_dim += 1 self.gru_rnn = GRU(self.input_dim, self.gru_rnn_output_size).to(device) def forward(self, data, time_steps, run_backwards = True): # IMPORTANT: assumes that 'data' already has mask concatenated to it # data shape: [n_traj, n_tp, n_dims] # shape required for rnn: (seq_len, batch, input_size) # t0: not used here n_traj = data.size(0) assert(not torch.isnan(data).any()) assert(not torch.isnan(time_steps).any()) data = data.permute(1,0,2) if run_backwards: # Look at data in the reverse order: from later points to the first data = utils.reverse(data) if self.use_delta_t: delta_t = time_steps[1:] - time_steps[:-1] if run_backwards: # we are going backwards in time with delta_t = utils.reverse(delta_t) # append zero delta t in the end delta_t = torch.cat((delta_t, torch.zeros(1).to(self.device))) delta_t = delta_t.unsqueeze(1).repeat((1,n_traj)).unsqueeze(-1) data = torch.cat((delta_t, data),-1) outputs, _ = self.gru_rnn(data) # LSTM output shape: (seq_len, batch, num_directions * hidden_size) last_output = outputs[-1] self.extra_info ={"rnn_outputs": outputs, "time_points": time_steps} mean, std = utils.split_last_dim(self.hiddens_to_z0(last_output)) std = std.abs() assert(not torch.isnan(mean).any()) assert(not torch.isnan(std).any()) return mean.unsqueeze(0), std.unsqueeze(0) class Encoder_z0_ODE_RNN(nn.Module): # Derive z0 by running ode backwards. # For every y_i we have two versions: encoded from data and derived from ODE by running it backwards from t_i+1 to t_i # Compute a weighted sum of y_i from data and y_i from ode. Use weighted y_i as an initial value for ODE runing from t_i to t_i-1 # Continue until we get to z0 def __init__(self, latent_dim, input_dim, z0_diffeq_solver = None, z0_dim = None, GRU_update = None, n_gru_units = 100, device = torch.device("cpu")): super(Encoder_z0_ODE_RNN, self).__init__() if z0_dim is None: self.z0_dim = latent_dim else: self.z0_dim = z0_dim if GRU_update is None: self.GRU_update = GRU_unit(latent_dim, input_dim, n_units = n_gru_units, device=device).to(device) else: self.GRU_update = GRU_update self.z0_diffeq_solver = z0_diffeq_solver self.latent_dim = latent_dim self.input_dim = input_dim self.device = device self.extra_info = None self.transform_z0 = nn.Sequential( nn.Linear(latent_dim * 2, 100), nn.Tanh(), nn.Linear(100, self.z0_dim * 2),) utils.init_network_weights(self.transform_z0) def forward(self, data, time_steps, run_backwards = False, save_info = False): # data, time_steps -- observations and their time stamps # IMPORTANT: assumes that 'data' already has mask concatenated to it assert(not torch.isnan(data).any()) assert(not torch.isnan(time_steps).any()) n_traj, n_tp, n_dims = data.size() if len(time_steps) == 1: prev_y = torch.zeros((1, n_traj, self.latent_dim)).to(self.device) prev_std = torch.zeros((1, n_traj, self.latent_dim)).to(self.device) xi = data[:,0,:].unsqueeze(0) last_yi, last_yi_std = self.GRU_update(prev_y, prev_std, xi) extra_info = None else: last_yi, last_yi_std, _, extra_info = self.run_odernn( data, time_steps, run_backwards = run_backwards, save_info = save_info) means_z0 = last_yi.reshape(1, n_traj, self.latent_dim) std_z0 = last_yi_std.reshape(1, n_traj, self.latent_dim) mean_z0, std_z0 = utils.split_last_dim( self.transform_z0( torch.cat((means_z0, std_z0), -1))) std_z0 = std_z0.abs() if save_info: self.extra_info = extra_info return mean_z0, std_z0 def run_odernn(self, data, time_steps, run_backwards = True, save_info = False): # IMPORTANT: assumes that 'data' already has mask concatenated to it n_traj, n_tp, n_dims = data.size() extra_info = [] t0 = time_steps[-1] if run_backwards: t0 = time_steps[0] device = get_device(data) prev_y = torch.zeros((1, n_traj, self.latent_dim)).to(device) prev_std = torch.zeros((1, n_traj, self.latent_dim)).to(device) prev_t, t_i = time_steps[-1] + 0.01, time_steps[-1] interval_length = time_steps[-1] - time_steps[0] minimum_step = interval_length / 50 #print("minimum step: {}".format(minimum_step)) assert(not torch.isnan(data).any()) assert(not torch.isnan(time_steps).any()) latent_ys = [] # Run ODE backwards and combine the y(t) estimates using gating time_points_iter = range(0, len(time_steps)) if run_backwards: time_points_iter = reversed(time_points_iter) for i in time_points_iter: if (prev_t - t_i) < minimum_step: time_points = torch.stack((prev_t, t_i)) inc = self.z0_diffeq_solver.ode_func(prev_t, prev_y) * (t_i - prev_t) assert(not torch.isnan(inc).any()) ode_sol = prev_y + inc ode_sol = torch.stack((prev_y, ode_sol), 2).to(device) assert(not torch.isnan(ode_sol).any()) else: n_intermediate_tp = max(2, ((prev_t - t_i) / minimum_step).int()) time_points = utils.linspace_vector(prev_t, t_i, n_intermediate_tp) ode_sol = self.z0_diffeq_solver(prev_y, time_points) assert(not torch.isnan(ode_sol).any()) if torch.mean(ode_sol[:, :, 0, :] - prev_y) >= 0.001: print("Error: first point of the ODE is not equal to initial value") print(torch.mean(ode_sol[:, :, 0, :] - prev_y)) exit() #assert(torch.mean(ode_sol[:, :, 0, :] - prev_y) < 0.001) yi_ode = ode_sol[:, :, -1, :] xi = data[:,i,:].unsqueeze(0) yi, yi_std = self.GRU_update(yi_ode, prev_std, xi) prev_y, prev_std = yi, yi_std prev_t, t_i = time_steps[i], time_steps[i-1] latent_ys.append(yi) if save_info: d = {"yi_ode": yi_ode.detach(), #"yi_from_data": yi_from_data, "yi": yi.detach(), "yi_std": yi_std.detach(), "time_points": time_points.detach(), "ode_sol": ode_sol.detach()} extra_info.append(d) latent_ys = torch.stack(latent_ys, 1) assert(not torch.isnan(yi).any()) assert(not torch.isnan(yi_std).any()) return yi, yi_std, latent_ys, extra_info class Decoder(nn.Module): def __init__(self, latent_dim, input_dim): super(Decoder, self).__init__() # decode data from latent space where we are solving an ODE back to the data space decoder = nn.Sequential( nn.Linear(latent_dim, input_dim),) utils.init_network_weights(decoder) self.decoder = decoder def forward(self, data): return self.decoder(data) # + [markdown] id="5MtrsGDjhy_t" # ## likelihood_eval.py # + id="YPhI4WBuhy_u" def gaussian_log_likelihood(mu_2d, data_2d, obsrv_std, indices = None): n_data_points = mu_2d.size()[-1] if n_data_points > 0: gaussian = Independent(Normal(loc = mu_2d, scale = obsrv_std.repeat(n_data_points)), 1) log_prob = gaussian.log_prob(data_2d) log_prob = log_prob / n_data_points else: log_prob = torch.zeros([1]).to(get_device(data_2d)).squeeze() return log_prob def poisson_log_likelihood(masked_log_lambdas, masked_data, indices, int_lambdas): # masked_log_lambdas and masked_data n_data_points = masked_data.size()[-1] if n_data_points > 0: log_prob = torch.sum(masked_log_lambdas) - int_lambdas[indices] #log_prob = log_prob / n_data_points else: log_prob = torch.zeros([1]).to(get_device(masked_data)).squeeze() return log_prob def compute_binary_CE_loss(label_predictions, mortality_label): #print("Computing binary classification loss: compute_CE_loss") mortality_label = mortality_label.reshape(-1) if len(label_predictions.size()) == 1: label_predictions = label_predictions.unsqueeze(0) n_traj_samples = label_predictions.size(0) label_predictions = label_predictions.reshape(n_traj_samples, -1) idx_not_nan = ~torch.isnan(mortality_label) if len(idx_not_nan) == 0.: print("All are labels are NaNs!") ce_loss = torch.Tensor(0.).to(get_device(mortality_label)) label_predictions = label_predictions[:,idx_not_nan] mortality_label = mortality_label[idx_not_nan] if torch.sum(mortality_label == 0.) == 0 or torch.sum(mortality_label == 1.) == 0: print("Warning: all examples in a batch belong to the same class -- please increase the batch size.") assert(not torch.isnan(label_predictions).any()) assert(not torch.isnan(mortality_label).any()) # For each trajectory, we get n_traj_samples samples from z0 -- compute loss on all of them mortality_label = mortality_label.repeat(n_traj_samples, 1) ce_loss = nn.BCEWithLogitsLoss()(label_predictions, mortality_label) # divide by number of patients in a batch ce_loss = ce_loss / n_traj_samples return ce_loss def compute_multiclass_CE_loss(label_predictions, true_label, mask): #print("Computing multi-class classification loss: compute_multiclass_CE_loss") if (len(label_predictions.size()) == 3): label_predictions = label_predictions.unsqueeze(0) n_traj_samples, n_traj, n_tp, n_dims = label_predictions.size() # assert(not torch.isnan(label_predictions).any()) # assert(not torch.isnan(true_label).any()) # For each trajectory, we get n_traj_samples samples from z0 -- compute loss on all of them true_label = true_label.repeat(n_traj_samples, 1, 1) label_predictions = label_predictions.reshape(n_traj_samples * n_traj * n_tp, n_dims) true_label = true_label.reshape(n_traj_samples * n_traj * n_tp, n_dims) # choose time points with at least one measurement mask = torch.sum(mask, -1) > 0 # repeat the mask for each label to mark that the label for this time point is present pred_mask = mask.repeat(n_dims, 1,1).permute(1,2,0) label_mask = mask pred_mask = pred_mask.repeat(n_traj_samples,1,1,1) label_mask = label_mask.repeat(n_traj_samples,1,1,1) pred_mask = pred_mask.reshape(n_traj_samples * n_traj * n_tp, n_dims) label_mask = label_mask.reshape(n_traj_samples * n_traj * n_tp, 1) if (label_predictions.size(-1) > 1) and (true_label.size(-1) > 1): assert(label_predictions.size(-1) == true_label.size(-1)) # targets are in one-hot encoding -- convert to indices _, true_label = true_label.max(-1) res = [] for i in range(true_label.size(0)): pred_masked = torch.masked_select(label_predictions[i], pred_mask[i].bool()) labels = torch.masked_select(true_label[i], label_mask[i].bool()) pred_masked = pred_masked.reshape(-1, n_dims) if (len(labels) == 0): continue ce_loss = nn.CrossEntropyLoss()(pred_masked, labels.long()) res.append(ce_loss) ce_loss = torch.stack(res, 0).to(get_device(label_predictions)) ce_loss = torch.mean(ce_loss) # # divide by number of patients in a batch # ce_loss = ce_loss / n_traj_samples return ce_loss def compute_masked_likelihood(mu, data, mask, likelihood_func): # Compute the likelihood per patient and per attribute so that we don't priorize patients with more measurements n_traj_samples, n_traj, n_timepoints, n_dims = data.size() res = [] for i in range(n_traj_samples): for k in range(n_traj): for j in range(n_dims): data_masked = torch.masked_select(data[i,k,:,j], mask[i,k,:,j].bool()) #assert(torch.sum(data_masked == 0.) < 10) mu_masked = torch.masked_select(mu[i,k,:,j], mask[i,k,:,j].bool()) log_prob = likelihood_func(mu_masked, data_masked, indices = (i,k,j)) res.append(log_prob) # shape: [n_traj*n_traj_samples, 1] res = torch.stack(res, 0).to(get_device(data)) res = res.reshape((n_traj_samples, n_traj, n_dims)) # Take mean over the number of dimensions res = torch.mean(res, -1) # !!!!!!!!!!! changed from sum to mean res = res.transpose(0,1) return res def masked_gaussian_log_density(mu, data, obsrv_std, mask = None): # these cases are for plotting through plot_estim_density if (len(mu.size()) == 3): # add additional dimension for gp samples mu = mu.unsqueeze(0) if (len(data.size()) == 2): # add additional dimension for gp samples and time step data = data.unsqueeze(0).unsqueeze(2) elif (len(data.size()) == 3): # add additional dimension for gp samples data = data.unsqueeze(0) n_traj_samples, n_traj, n_timepoints, n_dims = mu.size() assert(data.size()[-1] == n_dims) # Shape after permutation: [n_traj, n_traj_samples, n_timepoints, n_dims] if mask is None: mu_flat = mu.reshape(n_traj_samples*n_traj, n_timepoints * n_dims) n_traj_samples, n_traj, n_timepoints, n_dims = data.size() data_flat = data.reshape(n_traj_samples*n_traj, n_timepoints * n_dims) res = gaussian_log_likelihood(mu_flat, data_flat, obsrv_std) res = res.reshape(n_traj_samples, n_traj).transpose(0,1) else: # Compute the likelihood per patient so that we don't priorize patients with more measurements func = lambda mu, data, indices: gaussian_log_likelihood(mu, data, obsrv_std = obsrv_std, indices = indices) res = compute_masked_likelihood(mu, data, mask, func) return res def mse(mu, data, indices = None): n_data_points = mu.size()[-1] if n_data_points > 0: mse = nn.MSELoss()(mu, data) else: mse = torch.zeros([1]).to(get_device(data)).squeeze() return mse def compute_mse(mu, data, mask = None): # these cases are for plotting through plot_estim_density if (len(mu.size()) == 3): # add additional dimension for gp samples mu = mu.unsqueeze(0) if (len(data.size()) == 2): # add additional dimension for gp samples and time step data = data.unsqueeze(0).unsqueeze(2) elif (len(data.size()) == 3): # add additional dimension for gp samples data = data.unsqueeze(0) n_traj_samples, n_traj, n_timepoints, n_dims = mu.size() assert(data.size()[-1] == n_dims) # Shape after permutation: [n_traj, n_traj_samples, n_timepoints, n_dims] if mask is None: mu_flat = mu.reshape(n_traj_samples*n_traj, n_timepoints * n_dims) n_traj_samples, n_traj, n_timepoints, n_dims = data.size() data_flat = data.reshape(n_traj_samples*n_traj, n_timepoints * n_dims) res = mse(mu_flat, data_flat) else: # Compute the likelihood per patient so that we don't priorize patients with more measurements res = compute_masked_likelihood(mu, data, mask, mse) return res def compute_poisson_proc_likelihood(truth, pred_y, info, mask = None): # Compute Poisson likelihood # https://math.stackexchange.com/questions/344487/log-likelihood-of-a-realization-of-a-poisson-process # Sum log lambdas across all time points if mask is None: poisson_log_l = torch.sum(info["log_lambda_y"], 2) - info["int_lambda"] # Sum over data dims poisson_log_l = torch.mean(poisson_log_l, -1) else: # Compute likelihood of the data under the predictions truth_repeated = truth.repeat(pred_y.size(0), 1, 1, 1) mask_repeated = mask.repeat(pred_y.size(0), 1, 1, 1) # Compute the likelihood per patient and per attribute so that we don't priorize patients with more measurements int_lambda = info["int_lambda"] f = lambda log_lam, data, indices: poisson_log_likelihood(log_lam, data, indices, int_lambda) poisson_log_l = compute_masked_likelihood(info["log_lambda_y"], truth_repeated, mask_repeated, f) poisson_log_l = poisson_log_l.permute(1,0) # Take mean over n_traj #poisson_log_l = torch.mean(poisson_log_l, 1) # poisson_log_l shape: [n_traj_samples, n_traj] return poisson_log_l # + [markdown] id="O4dZh3AMhy_v" # ## base_models.py # + id="AX5bWiLXhy_v" ########################### # Latent ODEs for Irregularly-Sampled Time Series # Author: <NAME> ########################### def create_classifier(z0_dim, n_labels): return nn.Sequential( nn.Linear(z0_dim, 300), nn.ReLU(), nn.Linear(300, 300), nn.ReLU(), nn.Linear(300, n_labels),) class Baseline(nn.Module): def __init__(self, input_dim, latent_dim, device, obsrv_std = 0.01, use_binary_classif = False, classif_per_tp = False, use_poisson_proc = False, linear_classifier = False, n_labels = 1, train_classif_w_reconstr = False): super(Baseline, self).__init__() self.input_dim = input_dim self.latent_dim = latent_dim self.n_labels = n_labels self.obsrv_std = torch.Tensor([obsrv_std]).to(device) self.device = device self.use_binary_classif = use_binary_classif self.classif_per_tp = classif_per_tp self.use_poisson_proc = use_poisson_proc self.linear_classifier = linear_classifier self.train_classif_w_reconstr = train_classif_w_reconstr z0_dim = latent_dim if use_poisson_proc: z0_dim += latent_dim if use_binary_classif: if linear_classifier: self.classifier = nn.Sequential( nn.Linear(z0_dim, n_labels)) else: self.classifier = create_classifier(z0_dim, n_labels) utils.init_network_weights(self.classifier) def get_gaussian_likelihood(self, truth, pred_y, mask = None): # pred_y shape [n_traj_samples, n_traj, n_tp, n_dim] # truth shape [n_traj, n_tp, n_dim] if mask is not None: mask = mask.repeat(pred_y.size(0), 1, 1, 1) # Compute likelihood of the data under the predictions log_density_data = masked_gaussian_log_density(pred_y, truth, obsrv_std = self.obsrv_std, mask = mask) log_density_data = log_density_data.permute(1,0) # Compute the total density # Take mean over n_traj_samples log_density = torch.mean(log_density_data, 0) # shape: [n_traj] return log_density def get_mse(self, truth, pred_y, mask = None): # pred_y shape [n_traj_samples, n_traj, n_tp, n_dim] # truth shape [n_traj, n_tp, n_dim] if mask is not None: mask = mask.repeat(pred_y.size(0), 1, 1, 1) # Compute likelihood of the data under the predictions log_density_data = compute_mse(pred_y, truth, mask = mask) # shape: [1] return torch.mean(log_density_data) def compute_all_losses(self, batch_dict, n_tp_to_sample = None, n_traj_samples = 1, kl_coef = 1.): # Condition on subsampled points # Make predictions for all the points pred_x, info = self.get_reconstruction(batch_dict["tp_to_predict"], batch_dict["observed_data"], batch_dict["observed_tp"], mask = batch_dict["observed_mask"], n_traj_samples = n_traj_samples, mode = batch_dict["mode"]) # Compute likelihood of all the points likelihood = self.get_gaussian_likelihood(batch_dict["data_to_predict"], pred_x, mask = batch_dict["mask_predicted_data"]) mse = self.get_mse(batch_dict["data_to_predict"], pred_x, mask = batch_dict["mask_predicted_data"]) ################################ # Compute CE loss for binary classification on Physionet # Use only last attribute -- mortatility in the hospital device = get_device(batch_dict["data_to_predict"]) ce_loss = torch.Tensor([0.]).to(device) if (batch_dict["labels"] is not None) and self.use_binary_classif: if (batch_dict["labels"].size(-1) == 1) or (len(batch_dict["labels"].size()) == 1): ce_loss = compute_binary_CE_loss( info["label_predictions"], batch_dict["labels"]) else: ce_loss = compute_multiclass_CE_loss( info["label_predictions"], batch_dict["labels"], mask = batch_dict["mask_predicted_data"]) if torch.isnan(ce_loss): print("label pred") print(info["label_predictions"]) print("labels") print( batch_dict["labels"]) raise Exception("CE loss is Nan!") pois_log_likelihood = torch.Tensor([0.]).to(get_device(batch_dict["data_to_predict"])) if self.use_poisson_proc: pois_log_likelihood = compute_poisson_proc_likelihood( batch_dict["data_to_predict"], pred_x, info, mask = batch_dict["mask_predicted_data"]) # Take mean over n_traj pois_log_likelihood = torch.mean(pois_log_likelihood, 1) loss = - torch.mean(likelihood) if self.use_poisson_proc: loss = loss - 0.1 * pois_log_likelihood if self.use_binary_classif: if self.train_classif_w_reconstr: loss = loss + ce_loss * 100 else: loss = ce_loss # Take mean over the number of samples in a batch results = {} results["loss"] = torch.mean(loss) results["likelihood"] = torch.mean(likelihood).detach() results["mse"] = torch.mean(mse).detach() results["pois_likelihood"] = torch.mean(pois_log_likelihood).detach() results["ce_loss"] = torch.mean(ce_loss).detach() results["kl"] = 0. results["kl_first_p"] = 0. results["std_first_p"] = 0. if batch_dict["labels"] is not None and self.use_binary_classif: results["label_predictions"] = info["label_predictions"].detach() return results class VAE_Baseline(nn.Module): def __init__(self, input_dim, latent_dim, z0_prior, device, obsrv_std = 0.01, use_binary_classif = False, classif_per_tp = False, use_poisson_proc = False, linear_classifier = False, n_labels = 1, train_classif_w_reconstr = False): super(VAE_Baseline, self).__init__() self.input_dim = input_dim self.latent_dim = latent_dim self.device = device self.n_labels = n_labels self.obsrv_std = torch.Tensor([obsrv_std]).to(device) self.z0_prior = z0_prior self.use_binary_classif = use_binary_classif self.classif_per_tp = classif_per_tp self.use_poisson_proc = use_poisson_proc self.linear_classifier = linear_classifier self.train_classif_w_reconstr = train_classif_w_reconstr z0_dim = latent_dim if use_poisson_proc: z0_dim += latent_dim if use_binary_classif: if linear_classifier: self.classifier = nn.Sequential( nn.Linear(z0_dim, n_labels)) else: self.classifier = create_classifier(z0_dim, n_labels) utils.init_network_weights(self.classifier) def get_gaussian_likelihood(self, truth, pred_y, mask = None): # pred_y shape [n_traj_samples, n_traj, n_tp, n_dim] # truth shape [n_traj, n_tp, n_dim] n_traj, n_tp, n_dim = truth.size() # Compute likelihood of the data under the predictions truth_repeated = truth.repeat(pred_y.size(0), 1, 1, 1) if mask is not None: mask = mask.repeat(pred_y.size(0), 1, 1, 1) log_density_data = masked_gaussian_log_density(pred_y, truth_repeated, obsrv_std = self.obsrv_std, mask = mask) log_density_data = log_density_data.permute(1,0) log_density = torch.mean(log_density_data, 1) # shape: [n_traj_samples] return log_density def get_mse(self, truth, pred_y, mask = None): # pred_y shape [n_traj_samples, n_traj, n_tp, n_dim] # truth shape [n_traj, n_tp, n_dim] n_traj, n_tp, n_dim = truth.size() # Compute likelihood of the data under the predictions truth_repeated = truth.repeat(pred_y.size(0), 1, 1, 1) if mask is not None: mask = mask.repeat(pred_y.size(0), 1, 1, 1) # Compute likelihood of the data under the predictions log_density_data = compute_mse(pred_y, truth_repeated, mask = mask) # shape: [1] return torch.mean(log_density_data) def compute_all_losses(self, batch_dict, n_traj_samples = 1, kl_coef = 1.): # Condition on subsampled points # Make predictions for all the points pred_y, info = self.get_reconstruction(batch_dict["tp_to_predict"], batch_dict["observed_data"], batch_dict["observed_tp"], mask = batch_dict["observed_mask"], n_traj_samples = n_traj_samples, mode = batch_dict["mode"]) #print("get_reconstruction done -- computing likelihood") fp_mu, fp_std, fp_enc = info["first_point"] fp_std = fp_std.abs() fp_distr = Normal(fp_mu, fp_std) assert(torch.sum(fp_std < 0) == 0.) kldiv_z0 = kl_divergence(fp_distr, self.z0_prior) if torch.isnan(kldiv_z0).any(): print(fp_mu) print(fp_std) raise Exception("kldiv_z0 is Nan!") # Mean over number of latent dimensions # kldiv_z0 shape: [n_traj_samples, n_traj, n_latent_dims] if prior is a mixture of gaussians (KL is estimated) # kldiv_z0 shape: [1, n_traj, n_latent_dims] if prior is a standard gaussian (KL is computed exactly) # shape after: [n_traj_samples] kldiv_z0 = torch.mean(kldiv_z0,(1,2)) # Compute likelihood of all the points rec_likelihood = self.get_gaussian_likelihood( batch_dict["data_to_predict"], pred_y, mask = batch_dict["mask_predicted_data"]) mse = self.get_mse( batch_dict["data_to_predict"], pred_y, mask = batch_dict["mask_predicted_data"]) pois_log_likelihood = torch.Tensor([0.]).to(get_device(batch_dict["data_to_predict"])) if self.use_poisson_proc: pois_log_likelihood = compute_poisson_proc_likelihood( batch_dict["data_to_predict"], pred_y, info, mask = batch_dict["mask_predicted_data"]) # Take mean over n_traj pois_log_likelihood = torch.mean(pois_log_likelihood, 1) ################################ # Compute CE loss for binary classification on Physionet device = get_device(batch_dict["data_to_predict"]) ce_loss = torch.Tensor([0.]).to(device) if (batch_dict["labels"] is not None) and self.use_binary_classif: if (batch_dict["labels"].size(-1) == 1) or (len(batch_dict["labels"].size()) == 1): ce_loss = compute_binary_CE_loss( info["label_predictions"], batch_dict["labels"]) else: ce_loss = compute_multiclass_CE_loss( info["label_predictions"], batch_dict["labels"], mask = batch_dict["mask_predicted_data"]) # IWAE loss loss = - torch.logsumexp(rec_likelihood - kl_coef * kldiv_z0,0) if torch.isnan(loss): loss = - torch.mean(rec_likelihood - kl_coef * kldiv_z0,0) if self.use_poisson_proc: loss = loss - 0.1 * pois_log_likelihood if self.use_binary_classif: if self.train_classif_w_reconstr: loss = loss + ce_loss * 100 else: loss = ce_loss results = {} results['pred_y'] = pred_y results['true_y'] = batch_dict["data_to_predict"] results["loss"] = torch.mean(loss) results["likelihood"] = torch.mean(rec_likelihood).detach() results["mse"] = torch.mean(mse).detach() results["pois_likelihood"] = torch.mean(pois_log_likelihood).detach() results["ce_loss"] = torch.mean(ce_loss).detach() results["kl_first_p"] = torch.mean(kldiv_z0).detach() results["std_first_p"] = torch.mean(fp_std).detach() if batch_dict["labels"] is not None and self.use_binary_classif: results["label_predictions"] = info["label_predictions"].detach() return results # + [markdown] id="Ppm_XPFfhy_w" # ## ode_run.py # + id="BBD0-pmThy_w" class ODE_RNN(Baseline): def __init__(self, input_dim, latent_dim, device = torch.device("cpu"), z0_diffeq_solver = None, n_gru_units = 100, n_units = 100, concat_mask = False, obsrv_std = 0.1, use_binary_classif = False, classif_per_tp = False, n_labels = 1, train_classif_w_reconstr = False): Baseline.__init__(self, input_dim, latent_dim, device = device, obsrv_std = obsrv_std, use_binary_classif = use_binary_classif, classif_per_tp = classif_per_tp, n_labels = n_labels, train_classif_w_reconstr = train_classif_w_reconstr) ode_rnn_encoder_dim = latent_dim self.ode_gru = Encoder_z0_ODE_RNN( latent_dim = ode_rnn_encoder_dim, input_dim = (input_dim) * 2, # input and the mask z0_diffeq_solver = z0_diffeq_solver, n_gru_units = n_gru_units, device = device).to(device) self.z0_diffeq_solver = z0_diffeq_solver self.decoder = nn.Sequential( nn.Linear(latent_dim, n_units), nn.Tanh(), nn.Linear(n_units, input_dim),) utils.init_network_weights(self.decoder) def get_reconstruction(self, time_steps_to_predict, data, truth_time_steps, mask = None, n_traj_samples = None, mode = None): if (len(truth_time_steps) != len(time_steps_to_predict)) or (torch.sum(time_steps_to_predict - truth_time_steps) != 0): raise Exception("Extrapolation mode not implemented for ODE-RNN") # time_steps_to_predict and truth_time_steps should be the same assert(len(truth_time_steps) == len(time_steps_to_predict)) assert(mask is not None) data_and_mask = data if mask is not None: data_and_mask = torch.cat([data, mask],-1) _, _, latent_ys, _ = self.ode_gru.run_odernn( data_and_mask, truth_time_steps, run_backwards = False) latent_ys = latent_ys.permute(0,2,1,3) last_hidden = latent_ys[:,:,-1,:] #assert(torch.sum(int_lambda[0,0,-1,:] <= 0) == 0.) outputs = self.decoder(latent_ys) # Shift outputs for computing the loss -- we should compare the first output to the second data point, etc. first_point = data[:,0,:] outputs = utils.shift_outputs(outputs, first_point) extra_info = {"first_point": (latent_ys[:,:,-1,:], 0.0, latent_ys[:,:,-1,:])} if self.use_binary_classif: if self.classif_per_tp: extra_info["label_predictions"] = self.classifier(latent_ys) else: extra_info["label_predictions"] = self.classifier(last_hidden).squeeze(-1) # outputs shape: [n_traj_samples, n_traj, n_tp, n_dims] return outputs, extra_info # + [markdown] id="PDnVAqzWhy_w" # ## latent_ode.py # + id="WF67TleQhy_x" class LatentODE(VAE_Baseline): def __init__(self, input_dim, latent_dim, encoder_z0, decoder, diffeq_solver, z0_prior, device, obsrv_std = None, use_binary_classif = False, use_poisson_proc = False, linear_classifier = False, classif_per_tp = False, n_labels = 1, train_classif_w_reconstr = False): super(LatentODE, self).__init__( input_dim = input_dim, latent_dim = latent_dim, z0_prior = z0_prior, device = device, obsrv_std = obsrv_std, use_binary_classif = use_binary_classif, classif_per_tp = classif_per_tp, linear_classifier = linear_classifier, use_poisson_proc = use_poisson_proc, n_labels = n_labels, train_classif_w_reconstr = train_classif_w_reconstr) self.encoder_z0 = encoder_z0 self.diffeq_solver = diffeq_solver self.decoder = decoder self.use_poisson_proc = use_poisson_proc def get_reconstruction(self, time_steps_to_predict, truth, truth_time_steps, mask = None, n_traj_samples = 1, run_backwards = True, mode = None): if isinstance(self.encoder_z0, Encoder_z0_ODE_RNN) or \ isinstance(self.encoder_z0, Encoder_z0_RNN): truth_w_mask = truth if mask is not None: truth_w_mask = torch.cat((truth, mask), -1) first_point_mu, first_point_std = self.encoder_z0( truth_w_mask, truth_time_steps, run_backwards = run_backwards) means_z0 = first_point_mu.repeat(n_traj_samples, 1, 1) sigma_z0 = first_point_std.repeat(n_traj_samples, 1, 1) first_point_enc = utils.sample_standard_gaussian(means_z0, sigma_z0) else: raise Exception("Unknown encoder type {}".format(type(self.encoder_z0).__name__)) first_point_std = first_point_std.abs() assert(torch.sum(first_point_std < 0) == 0.) if self.use_poisson_proc: n_traj_samples, n_traj, n_dims = first_point_enc.size() # append a vector of zeros to compute the integral of lambda zeros = torch.zeros([n_traj_samples, n_traj,self.input_dim]).to(get_device(truth)) first_point_enc_aug = torch.cat((first_point_enc, zeros), -1) means_z0_aug = torch.cat((means_z0, zeros), -1) else: first_point_enc_aug = first_point_enc means_z0_aug = means_z0 assert(not torch.isnan(time_steps_to_predict).any()) assert(not torch.isnan(first_point_enc).any()) assert(not torch.isnan(first_point_enc_aug).any()) # Shape of sol_y [n_traj_samples, n_samples, n_timepoints, n_latents] sol_y = self.diffeq_solver(first_point_enc_aug, time_steps_to_predict) if self.use_poisson_proc: sol_y, log_lambda_y, int_lambda, _ = self.diffeq_solver.ode_func.extract_poisson_rate(sol_y) assert(torch.sum(int_lambda[:,:,0,:]) == 0.) assert(torch.sum(int_lambda[0,0,-1,:] <= 0) == 0.) pred_x = self.decoder(sol_y) all_extra_info = { "first_point": (first_point_mu, first_point_std, first_point_enc), "latent_traj": sol_y.detach() } if self.use_poisson_proc: # intergral of lambda from the last step of ODE Solver all_extra_info["int_lambda"] = int_lambda[:,:,-1,:] all_extra_info["log_lambda_y"] = log_lambda_y if self.use_binary_classif: if self.classif_per_tp: all_extra_info["label_predictions"] = self.classifier(sol_y) else: all_extra_info["label_predictions"] = self.classifier(first_point_enc).squeeze(-1) return pred_x, all_extra_info def sample_traj_from_prior(self, time_steps_to_predict, n_traj_samples = 1): # input_dim = starting_point.size()[-1] # starting_point = starting_point.view(1,1,input_dim) # Sample z0 from prior starting_point_enc = self.z0_prior.sample([n_traj_samples, 1, self.latent_dim]).squeeze(-1) starting_point_enc_aug = starting_point_enc if self.use_poisson_proc: n_traj_samples, n_traj, n_dims = starting_point_enc.size() # append a vector of zeros to compute the integral of lambda zeros = torch.zeros(n_traj_samples, n_traj,self.input_dim).to(self.device) starting_point_enc_aug = torch.cat((starting_point_enc, zeros), -1) sol_y = self.diffeq_solver.sample_traj_from_prior(starting_point_enc_aug, time_steps_to_predict, n_traj_samples = 3) if self.use_poisson_proc: sol_y, log_lambda_y, int_lambda, _ = self.diffeq_solver.ode_func.extract_poisson_rate(sol_y) return self.decoder(sol_y) # + [markdown] id="w7EhkS2Uhy_x" # ## ode_func.py # + id="ard2Qg5chy_x" class ODEFunc(nn.Module): def __init__(self, input_dim, latent_dim, ode_func_net, device = torch.device("cpu")): """ input_dim: dimensionality of the input latent_dim: dimensionality used for ODE. Analog of a continous latent state """ # print(f"Inside ODEFunc class") super(ODEFunc, self).__init__() self.input_dim = input_dim # print(f"input_dim is {input_dim}") # print(f"latent_dim is {latent_dim}") self.device = device utils.init_network_weights(ode_func_net) self.gradient_net = ode_func_net def forward(self, t_local, y, backwards = False): """ Perform one step in solving ODE. Given current data point y and current time point t_local, returns gradient dy/dt at this time point t_local: current time point y: value at the current time point """ grad = self.get_ode_gradient_nn(t_local, y) if backwards: grad = -grad return grad def get_ode_gradient_nn(self, t_local, y): return self.gradient_net(y) def sample_next_point_from_prior(self, t_local, y): """ t_local: current time point y: value at the current time point """ return self.get_ode_gradient_nn(t_local, y) ##################################################################################################### class ODEFunc_w_Poisson(ODEFunc): def __init__(self, input_dim, latent_dim, ode_func_net, lambda_net, device = torch.device("cpu")): """ input_dim: dimensionality of the input latent_dim: dimensionality used for ODE. Analog of a continous latent state """ super(ODEFunc_w_Poisson, self).__init__(input_dim, latent_dim, ode_func_net, device) self.latent_ode = ODEFunc(input_dim = input_dim, latent_dim = latent_dim, ode_func_net = ode_func_net, device = device) self.latent_dim = latent_dim self.lambda_net = lambda_net # The computation of poisson likelihood can become numerically unstable. #The integral lambda(t) dt can take large values. In fact, it is equal to the expected number of events on the interval [0,T] #Exponent of lambda can also take large values # So we divide lambda by the constant and then multiply the integral of lambda by the constant self.const_for_lambda = torch.Tensor([100.]).to(device) def extract_poisson_rate(self, augmented, final_result = True): y, log_lambdas, int_lambda = None, None, None assert(augmented.size(-1) == self.latent_dim + self.input_dim) latent_lam_dim = self.latent_dim // 2 if len(augmented.size()) == 3: int_lambda = augmented[:,:,-self.input_dim:] y_latent_lam = augmented[:,:,:-self.input_dim] log_lambdas = self.lambda_net(y_latent_lam[:,:,-latent_lam_dim:]) y = y_latent_lam[:,:,:-latent_lam_dim] elif len(augmented.size()) == 4: int_lambda = augmented[:,:,:,-self.input_dim:] y_latent_lam = augmented[:,:,:,:-self.input_dim] log_lambdas = self.lambda_net(y_latent_lam[:,:,:,-latent_lam_dim:]) y = y_latent_lam[:,:,:,:-latent_lam_dim] # Multiply the intergral over lambda by a constant # only when we have finished the integral computation (i.e. this is not a call in get_ode_gradient_nn) if final_result: int_lambda = int_lambda * self.const_for_lambda # Latents for performing reconstruction (y) have the same size as latent poisson rate (log_lambdas) assert(y.size(-1) == latent_lam_dim) return y, log_lambdas, int_lambda, y_latent_lam def get_ode_gradient_nn(self, t_local, augmented): y, log_lam, int_lambda, y_latent_lam = self.extract_poisson_rate(augmented, final_result = False) dydt_dldt = self.latent_ode(t_local, y_latent_lam) log_lam = log_lam - torch.log(self.const_for_lambda) return torch.cat((dydt_dldt, torch.exp(log_lam)),-1) # + [markdown] id="98sA9jVlhy_y" # ## create_latent_ode_model.py # + id="kv36UrKvhy_y" def create_LatentODE_model(args, input_dim, z0_prior, obsrv_std, device, classif_per_tp = False, n_labels = 1): dim = args.latents if args.poisson: lambda_net = utils.create_net(dim, input_dim, n_layers = 1, n_units = args.units, nonlinear = nn.Tanh) # ODE function produces the gradient for latent state and for poisson rate ode_func_net = utils.create_net(dim * 2, args.latents * 2, n_layers = args.gen_layers, n_units = args.units, nonlinear = nn.Tanh) gen_ode_func = ODEFunc_w_Poisson( input_dim = input_dim, latent_dim = args.latents * 2, ode_func_net = ode_func_net, lambda_net = lambda_net, device = device).to(device) else: dim = args.latents ode_func_net = utils.create_net(dim, args.latents, n_layers = args.gen_layers, n_units = args.units, nonlinear = nn.Tanh) gen_ode_func = ODEFunc( input_dim = input_dim, latent_dim = args.latents, ode_func_net = ode_func_net, device = device).to(device) z0_diffeq_solver = None n_rec_dims = args.rec_dims enc_input_dim = int(input_dim) * 2 # we concatenate the mask gen_data_dim = input_dim z0_dim = args.latents if args.poisson: z0_dim += args.latents # predict the initial poisson rate if args.z0_encoder == "odernn": ode_func_net = utils.create_net(n_rec_dims, n_rec_dims, n_layers = args.rec_layers, n_units = args.units, nonlinear = nn.Tanh) rec_ode_func = ODEFunc( input_dim = enc_input_dim, latent_dim = n_rec_dims, ode_func_net = ode_func_net, device = device).to(device) z0_diffeq_solver = DiffeqSolver(enc_input_dim, rec_ode_func, "euler", args.latents, odeint_rtol = 1e-3, odeint_atol = 1e-4, device = device) encoder_z0 = Encoder_z0_ODE_RNN(n_rec_dims, enc_input_dim, z0_diffeq_solver, z0_dim = z0_dim, n_gru_units = args.gru_units, device = device).to(device) elif args.z0_encoder == "rnn": encoder_z0 = Encoder_z0_RNN(z0_dim, enc_input_dim, lstm_output_size = n_rec_dims, device = device).to(device) else: raise Exception("Unknown encoder for Latent ODE model: " + args.z0_encoder) decoder = Decoder(args.latents, gen_data_dim).to(device) diffeq_solver = DiffeqSolver(gen_data_dim, gen_ode_func, 'dopri5', args.latents, odeint_rtol = 1e-3, odeint_atol = 1e-4, device = device) model = LatentODE( input_dim = gen_data_dim, latent_dim = args.latents, encoder_z0 = encoder_z0, decoder = decoder, diffeq_solver = diffeq_solver, z0_prior = z0_prior, device = device, obsrv_std = obsrv_std, use_poisson_proc = args.poisson, use_binary_classif = args.classif, linear_classifier = args.linear_classif, classif_per_tp = classif_per_tp, n_labels = n_labels, train_classif_w_reconstr = (args.dataset == "physionet") ).to(device) return model # + id="KzYUKIc9hy_z" if args.latent_ode: model = create_LatentODE_model(args, input_dim, z0_prior, obsrv_std, device, classif_per_tp = classif_per_tp, n_labels = n_labels) else: raise Exception("Model not specified") # + [markdown] id="afWXMKznhy_z" # # Training # + id="NYyCKxi5NxMf" # train_lr_list = [] # kl_coef_list = [] # train_pred_y_list = [] # train_true_y_list = [] # train_loss_list = [] # ELBO # train_likelihood_list = [] # Rec Likelihood # train_mse_list = [] # train_kl_first_p_list = [] # KL Divergence between z0 # train_std_first_p_list = [] # test_pred_y_list = [] # test_true_y_list = [] # test_loss_list = [] # ELBO # test_likelihood_list = [] # Rec Likelihood # test_mse_list = [] # test_kl_first_p_list = [] # KL Divergence between z0 # test_std_first_p_list = [] # + colab={"base_uri": "https://localhost:8080/"} id="y99JVbgThy_z" outputId="93ef98df-29c3-4b28-e8b8-4d89ca3a4ba2" # #Load checkpoint and evaluate the model # if args.load is not None: # utils.get_ckpt_model(ckpt_path, model, device) # # exit() # else: # file_name = os.path.abspath('') # log_path = "logs/" + file_name + "_" + str(experimentID) + ".log" # if not os.path.exists("logs/"): # utils.makedirs("logs/") # logger = utils.get_logger(logpath=log_path, filepath=os.path.abspath('')) # logger.info(input_command) # optimizer = optim.Adamax(model.parameters(), lr=args.lr) # # print(f"optimizer is {optimizer}") # num_batches = data_obj["n_train_batches"] # print(f"num_batches is {num_batches}") # for itr in range(1, num_batches * (args.niters + 1)): # optimizer.zero_grad() # utils.update_learning_rate(optimizer, decay_rate = 0.999, lowest = args.lr / 10) # wait_until_kl_inc = 10 # if itr // num_batches < wait_until_kl_inc: # kl_coef = 0. # else: # kl_coef = (1-0.99** (itr // num_batches - wait_until_kl_inc)) # kl_coef_list.append(kl_coef) # batch_dict = utils.get_next_batch(data_obj["train_dataloader"]) # train_res = model.compute_all_losses(batch_dict, n_traj_samples = 1, kl_coef = kl_coef) # train_loss_list.append(train_res['loss'].cpu().item()) # train_likelihood_list.append(train_res['likelihood'].cpu().item()) # train_mse_list.append(train_res['mse'].cpu().item()) # train_kl_first_p_list.append(train_res['kl_first_p'].cpu().item()) # train_std_first_p_list.append(train_res['std_first_p'].cpu().item()) # train_res["loss"].backward() # optimizer.step() # n_iters_to_viz = 1 # if itr % (n_iters_to_viz * num_batches) == 0: # with torch.no_grad(): # test_res = compute_loss_all_batches(model, # data_obj["test_dataloader"], args, # n_batches = data_obj["n_test_batches"], # experimentID = experimentID, # device = device, # n_traj_samples = 1, kl_coef = kl_coef) # test_loss_list.append(test_res['loss'].cpu().item()) # test_likelihood_list.append(test_res['likelihood'].cpu().item()) # test_mse_list.append(test_res['mse'].cpu().item()) # test_kl_first_p_list.append(test_res['kl_first_p'].cpu().item()) # test_std_first_p_list.append(test_res['std_first_p'].cpu().item()) # message = 'Epoch {:04d} [Test seq (cond on sampled tp)] | Loss {:.6f} | Likelihood {:.6f} | KL fp {:.4f} | FP STD {:.4f}|'.format( # itr//num_batches, # test_res["loss"].detach(), test_res["likelihood"].detach(), # test_res["kl_first_p"], test_res["std_first_p"]) # logger.info("Experiment " + str(experimentID)) # logger.info(message) # logger.info("KL coef: {}".format(kl_coef)) # logger.info("Train loss (one batch): {}".format(train_res["loss"].detach())) # logger.info("Train CE loss (one batch): {}".format(train_res["ce_loss"].detach())) # if "auc" in test_res: # logger.info("Classification AUC (TEST): {:.4f}".format(test_res["auc"])) # if "mse" in test_res: # logger.info("Test MSE: {}".format(test_res["mse"])) # if "accuracy" in train_res: # logger.info("Classification accuracy (TRAIN): {:.4f}".format(train_res["accuracy"])) # if "accuracy" in test_res: # logger.info("Classification accuracy (TEST): {:.4f}".format(test_res["accuracy"])) # if "pois_likelihood" in test_res: # logger.info("Poisson likelihood: {}".format(test_res["pois_likelihood"])) # if "ce_loss" in test_res: # logger.info("CE loss: {}".format(test_res["ce_loss"])) # torch.save({ # 'args': args, # 'state_dict': model.state_dict(), # }, ckpt_path) # # Plotting # if args.viz: # with torch.no_grad(): # test_dict = utils.get_next_batch(data_obj["test_dataloader"]) # print("plotting....") # if isinstance(model, LatentODE) and (args.dataset == "periodic"): #and not args.classic_rnn and not args.ode_rnn: # plot_id = itr // num_batches // n_iters_to_viz # viz.draw_all_plots_one_dim(test_dict, model, # plot_name = file_name + "_" + str(experimentID) + "_{:03d}".format(plot_id) + ".png", # experimentID = experimentID, save=True) # plt.pause(0.01) # # train_pred_y_list.append(train_res['pred_y'].cpu().numpy()) # # train_true_y_list.append(train_res['true_y'].cpu().numpy()) # # test_pred_y_list.append(test_res['pred_y'].cpu().numpy()) # # test_true_y_list.append(test_res['true_y'].cpu().numpy()) # torch.save({ # 'args': args, # 'state_dict': model.state_dict(), # }, ckpt_path) # + id="nKJFAZ7A9B5h" utils.get_ckpt_model(ckpt_path, model, device) # + colab={"base_uri": "https://localhost:8080/"} id="MKSDMcut9DyL" outputId="a08e2f2e-de79-4e59-825d-60a7659d880f" kl_coef = np.load(f"results/kl_coef_cluster_{cluster}.npy") kl_coef_last = kl_coef[-1] kl_coef_last # + colab={"base_uri": "https://localhost:8080/"} id="0uM3mwl79Uyn" outputId="3900c868-73a3-4f49-f649-aafc78983ed5" test_res = compute_loss_all_batches(model, data_obj["test_dataloader"], args, n_batches = data_obj["n_test_batches"], experimentID = experimentID, device = device, n_traj_samples = 1, kl_coef = kl_coef_last) # + colab={"base_uri": "https://localhost:8080/"} id="1dZyy6zdARJe" outputId="6594f0d5-7db2-43f5-cb3d-868e052d785f" test_res['pred_y'][0][0].shape # + id="GZh61Dji9v35" test_pred_y_list = test_res['pred_y'] # + id="xfWim6o0ABUH" # train_pred_y_list = [] # train_true_y_list = [] # with torch.no_grad(): # train_pred_y_list.append(train_res['pred_y'].cpu().numpy()) # train_true_y_list.append(train_res['true_y'].cpu().numpy()) # test_pred_y_list = test_res['pred_y'] # test_true_y_list = test_res['true_y'] # + id="vmGOoPDQAxtt" # train_pred_y_list[0][0].shape # + id="xXfq6eEnmA4l" def plot_train_loss(train_loss_list): plt.plot(train_loss_list) plt.title(f"Train ELBO Loss") plt.ylabel('Train ELBO Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/ELBO Train Loss cluster_{cluster}.pdf", dpi = 150) plt.show() def plot_test_loss(test_loss_list): plt.plot(test_loss_list) plt.title(f"Test ELBO Loss") plt.ylabel('Test ELBO Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/ELBO Test Loss cluster_{cluster}.pdf", dpi = 150) plt.show() def plot_train_likelihood(train_likelihood_list): plt.plot(train_likelihood_list) plt.title(f"Train Likelihood") plt.ylabel('Train Likelihood') plt.xlabel('#Batches') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/Likelihood Train cluster_{cluster}.pdf", dpi = 150) plt.show() def plot_test_likelihood(test_likelihood_list): plt.plot(test_likelihood_list) plt.title(f"Test Likelihood") plt.ylabel('Test Likelihood') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/Likelihood Test cluster_{cluster}.pdf", dpi = 150) plt.show() def plot_train_mse(train_mse_list): plt.plot(train_mse_list) plt.title(f"Train MSE Loss") plt.ylabel('Train MSE Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/MSE Loss Train cluster_{cluster}.pdf", dpi = 150) plt.show() def plot_test_mse(test_mse_list): plt.plot(test_mse_list) plt.title(f"test MSE Loss") plt.ylabel('test MSE Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/MSE Loss Test cluster_{cluster}.pdf", dpi = 150) plt.show() # + [markdown] id="TzhnA8xU_wHT" # ## Plots # + id="NjfsNJEyYeLJ" plot_train_loss(train_loss_list) # + id="AZPkaJI0_vqv" plot_test_loss(test_loss_list) # + id="7k4P_ep7BQa9" plot_train_likelihood(train_likelihood_list) # + id="3WvrTlxvBSif" plot_test_likelihood(test_likelihood_list) # + id="hx6k654gBUj5" plot_train_mse(train_mse_list) # + id="IuViIrJzBWd-" plot_test_mse(test_mse_list) # + [markdown] id="7QJJVSCfCQEs" # ## Save Train Pred_y, Test_y, kl_first_p, std_first_p, kl_coeff_list # + id="VumeLhaSBYRy" # np.save(f"train pred y cluster_{cluster}.npy", train_pred_y_list[0][0]) # + colab={"base_uri": "https://localhost:8080/"} id="5Gwjaw_yCs0I" outputId="4d7d2560-1702-4610-d46e-9dc2289889b6" # np.load(f"train pred y cluster_{cluster}.npy").shape # + id="fcS5F20MCvsQ" np.save(f"test_pred_y_cluster_{cluster}.npy", test_pred_y_list[0][0]) # + colab={"base_uri": "https://localhost:8080/"} id="nSDfgsxeDS-B" outputId="e64faafc-0442-40ac-e1c7-11c1e547866e" # train_true_y_list[0].shape # + id="ppolIJF2C_qD" # np.save(f"train_true_y_cluster_{cluster}.npy", train_true_y_list[0]) # + colab={"base_uri": "https://localhost:8080/"} id="xqLOllPQDk41" outputId="f30f086a-9432-47fe-e967-90dc99df4efc" # test_true_y_list[0].shape # + id="m4ZwraTvDeVC" # np.save(f"test_true_y_cluster_{cluster}.npy", test_true_y_list[0]) # + colab={"base_uri": "https://localhost:8080/"} id="4FOsakfVD73-" outputId="11ef28b2-b467-4bba-bfa8-24e686985d5a" # train_loss_list # + id="K8iM1vIvDoCk" # np.save(f"train_elboloss_cluster_{cluster}.npy", train_loss_list) # + colab={"base_uri": "https://localhost:8080/"} id="xAlIUPE5EHPv" outputId="0cff1309-4065-455f-aa59-9189c7d5ca3a" # len(test_loss_list) # + id="ZtuSPHpT-MjN" test_loss_list = np.load(f"test_elboloss_cluster_{cluster}.npy") # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="T2dVE07rEJFA" outputId="889c2509-748f-4399-e609-254d6c35b3fd" # %matplotlib inline plt.plot(test_loss_list) plt.title(f"Test ELBO Loss") plt.ylabel('Test ELBO Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/ELBO Test Loss cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="1lWIEN6XEmxa" outputId="c7f3dd47-c548-448f-99c0-a03b32a836a5" plt.plot(train_loss_list) plt.title(f"Train ELBO Loss") plt.ylabel('Train ELBO Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/ELBO Train Loss cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="ILPUH3qsE2ZX" outputId="d2c646c0-8419-4f5b-a16a-44d5eecd12b2" plt.plot(train_likelihood_list) plt.title(f"Train Likelihood") plt.ylabel('Train Likelihood') plt.xlabel('#Batches') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/Likelihood Train cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="vX3R8sncFI90" outputId="155e90b6-fdb5-446c-cdab-526801a76910" plt.plot(test_likelihood_list) plt.title(f"Test Likelihood") plt.ylabel('Test Likelihood') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/Likelihood Test cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="yerz5IScFW7u" outputId="38d9a048-8513-4a34-882e-0d7d1c6b1511" plt.plot(train_mse_list) plt.title(f"Train MSE Loss") plt.ylabel('Train MSE Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/MSE Loss Train cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="WpGef5KWFdfT" outputId="e74e26c5-dd0f-4a47-8e05-9b91e67a78a8" plt.plot(test_mse_list) plt.title(f"test MSE Loss") plt.ylabel('test MSE Loss') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/MSE Loss Test cluster_{cluster}.pdf", dpi = 150) plt.show() # + id="Oj6OnGfKFoFG" np.save(f"test_elboloss_cluster_{cluster}.npy", test_loss_list) # + id="orWx90auGH9n" np.save(f"train_likelihood_cluster_{cluster}.npy", train_likelihood_list) np.save(f"test_likelihood_cluster_{cluster}.npy", test_likelihood_list) np.save(f"train_mse_cluster_{cluster}.npy", train_mse_list) np.save(f"test_mse_cluster_{cluster}.npy", test_mse_list) np.save(f"train_kl_first_p_cluster_{cluster}.npy", train_kl_first_p_list) np.save(f"test_kl_first_p_cluster_{cluster}.npy", test_kl_first_p_list) np.save(f"train_std_first_p_cluster_{cluster}.npy", train_std_first_p_list) np.save(f"test_std_first_p_cluster_{cluster}.npy", test_std_first_p_list) # + id="pXNcWkhqGR-0" np.save(f"kl_coef_cluster_{cluster}.npy", kl_coef_list) # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="BEt3CIogHfUY" outputId="de442765-5626-4341-a91b-ed68a2efccdd" plt.plot(train_kl_first_p_list) plt.title(f"Train KL divergence") plt.ylabel('Train KL divergence') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/KL Divergence Train cluster_{cluster}.pdf", dpi = 150) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 295} id="k2ahGKdFK6B9" outputId="6b6e3b4e-137d-4687-f189-9c2b6d4f5b65" plt.plot(test_kl_first_p_list) plt.title(f"Test KL divergence") plt.ylabel('Test KL divergence') plt.xlabel('Epochs') if not os.path.exists("plots/"): utils.makedirs("plots/") plt.savefig(f"plots/KL Divergence Test cluster_{cluster}.pdf", dpi = 150) plt.show() # + id="TpqpbziS66_X" np.save(f"data_max_cluster_{cluster}.npy", data_obj['dataset_obj'].data_max.cpu().numpy()) np.save(f"data_min_cluster_{cluster}.npy", data_obj['dataset_obj'].data_min.cpu().numpy()) # + [markdown] id="m53FVmQ-6fNW" # ## Pred and True Y # + id="wkbMiOy8LRym" colab={"base_uri": "https://localhost:8080/"} outputId="d5e9b73f-92f9-4b39-f443-a077188c0f82" train_pred_y = np.load(f"train pred y cluster_{cluster}.npy") print(f"Train Predicted Y shape: {train_pred_y.shape}") train_true_y = np.load(f"train_true_y_cluster_{cluster}.npy") print(f"Train True Y shape: {train_true_y.shape}") test_pred_y = np.load(f"test_pred_y_cluster_{cluster}.npy") print(f"Test Predicted Y shape: {test_pred_y.shape}") test_true_y = np.load(f"test_true_y_cluster_{cluster}.npy") print(f"Test True Y shape: {test_true_y.shape}") # + colab={"base_uri": "https://localhost:8080/"} id="gE-zloX5-0WV" outputId="9b415223-6f9f-4f43-fca7-63d8133ead96" train_pred_y = np.load(f"train pred y cluster_{cluster}.npy") train_pred_y.shape # + colab={"base_uri": "https://localhost:8080/"} id="fpHiY3EB_kxq" outputId="11424aff-2464-4168-d28f-a89549f5384d" train_true_y = np.load(f"train_true_y_cluster_{cluster}.npy") train_true_y.shape # + colab={"base_uri": "https://localhost:8080/"} id="ASkgSpw8_MzV" outputId="47a9d4d0-8613-4e79-c40b-9089642d1f32" test_pred_y = np.load(f"test_pred_y_cluster_{cluster}.npy") test_pred_y.shape # + colab={"base_uri": "https://localhost:8080/"} id="UQ2oSCI8_jR_" outputId="3fe060e5-cbee-4b1e-f55e-db2994e15d87" test_true_y = np.load(f"test_true_y_cluster_{cluster}.npy") test_true_y.shape # + id="YLIM3mX8iOGs" colab={"base_uri": "https://localhost:8080/"} outputId="6b1d7d3e-2c13-49ad-b266-762bad63bfef" train_pred_median = [] for i in range(train_pred_y.shape[0]): arr = np.median(train_pred_y[i], axis = 1).reshape(1, train_pred_y.shape[1]) train_pred_median.append(arr) train_pred_median = np.dstack(train_pred_median) print(train_pred_median.shape) train_pred_median = np.rollaxis(train_pred_median, -1) print(train_pred_median.shape) # + id="_8Fvo5pL6ld3" colab={"base_uri": "https://localhost:8080/"} outputId="f9ab2a69-bcc4-47e4-aaaf-9603256d3b89" train_true_median = [] for i in range(train_pred_y.shape[0]): arr = np.median(train_true_y[i], axis = 1).reshape(1, train_true_y.shape[1]) train_true_median.append(arr) train_true_median = np.dstack(train_true_median) print(train_true_median.shape) train_true_median = np.rollaxis(train_true_median, -1) print(train_true_median.shape) # + id="VH1XVcA56qaD" colab={"base_uri": "https://localhost:8080/"} outputId="466bf046-4e77-4dd8-9511-22cd03d722e0" test_pred_median = [] for i in range(test_pred_y.shape[0]): arr = np.median(test_pred_y[i], axis = 1).reshape(1, test_pred_y.shape[1]) test_pred_median.append(arr) test_pred_median = np.dstack(test_pred_median) print(test_pred_median.shape) test_pred_median = np.rollaxis(test_pred_median, -1) print(test_pred_median.shape) # + id="FGMBWZ7x6sYL" colab={"base_uri": "https://localhost:8080/"} outputId="46e66aa0-9cb0-48c6-fdcd-a51126a5346c" test_true_median = [] for i in range(test_pred_y.shape[0]): arr = np.median(test_true_y[i], axis = 1).reshape(1, test_true_y.shape[1]) test_true_median.append(arr) test_true_median = np.dstack(test_true_median) print(test_true_median.shape) test_true_median = np.rollaxis(test_true_median, -1) print(test_true_median.shape) # + id="CcKKkGIk6uUA" colab={"base_uri": "https://localhost:8080/"} outputId="6ee12fc6-5685-439b-c512-dad8f59f37c9" data_max = np.load(f"data_max_cluster_{cluster}.npy") data_max_median = np.median(data_max) print(f"data_max_median is {data_max_median}") data_min = np.load(f"data_min_cluster_{cluster}.npy") data_min_median = np.median(data_min) print(f"data_min_median is {data_min_median}") # + id="r_hifMsl6vny" train_true_median = train_true_median * data_max_median + data_min_median train_pred_median = train_pred_median * data_max_median + data_min_median test_true_median = test_true_median * data_max_median + data_min_median test_pred_median = test_pred_median * data_max_median + data_min_median # + id="1dkDr1q16xAJ" def plot_train_extrapol(i, train_true_median, train_pred_median): t_ = torch.linspace(1., train_true_median.shape[0], train_true_median.shape[0]) plt.figure() plt.plot(t_.numpy(), train_true_median[:, :, i-1-lag], 'g', label = f"orig_week{i}") rmse = np.sqrt(((train_true_median[:, :, i-1-lag] - train_pred_median[:, :, i-1-lag]) ** 2).mean()) plt.plot(t_.numpy(), train_pred_median[:, :, i-1-lag], '--', label = f"extrapol_week{i}") plt.title(f"Train Extrapol: Median Stock price for week{i}: RMSE {rmse}") plt.legend(framealpha=1, frameon=True); plt.savefig(f"plots-results/Train Extrapol: Median Stock price for week{i} Cluster {cluster}.pdf", dpi = 150) plt.show() def plot_test_extrapol(i, train_true_median, train_pred_median): t_ = torch.linspace(1., train_true_median.shape[0], train_true_median.shape[0]) plt.figure() plt.plot(t_.numpy(), train_true_median[:, :, i-1-lag], 'g', label = f"orig_week{i}") rmse = np.sqrt(((train_true_median[:, :, i-1-lag] - train_pred_median[:, :, i-1-lag]) ** 2).mean()) plt.plot(t_.numpy(), train_pred_median[:, :, i-1-lag], '--', label = f"extrapol_week{i}") plt.title(f"Test Extrapol: Median Stock price for week{i}: RMSE {rmse}") plt.legend(framealpha=1, frameon=True); plt.savefig(f"plots-results/Test Extrapol: Median Stock price for week{i} Cluster {cluster}.pdf", dpi = 150) plt.show() # + id="FsKd0bgJ6ysb" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="dcb78f30-094e-4d6f-ccd0-721346c646bd" for i in range(lag, lag+forecast+1): plot_train_extrapol(i, train_true_median, train_pred_median) plot_test_extrapol(i, test_true_median, test_pred_median) # + id="chSmUGO1Ad1p"
latent-ode-irregular-stockdata/latentode_irregular_stockdata_cluster1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="UEBilEjLj5wY" # Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks. # - Author: <NAME> # - GitHub Repository: https://github.com/rasbt/deeplearning-models # + id="1Aaa78eDlbVo" colab_type="code" colab={} # !pip install -q IPython # !pip install -q ipykernel # !pip install -q watermark # !pip install -q matplotlib # !pip install -q sklearn # !pip install -q pandas # !pip install -q pydot # !pip install -q hiddenlayer # !pip install -q graphviz # + colab_type="code" id="GOzuY8Yvj5wb" colab={"base_uri": "https://localhost:8080/", "height": 121} outputId="58f393a0-7082-48cb-9d3d-a37745b901c0" # %load_ext watermark # %watermark -a '<NAME>' -v -p torch # + [markdown] colab_type="text" id="rH4XmErYj5wm" # # Model Zoo -- ResNet-18 MNIST Digits Classifier with Data Parallelism # + [markdown] id="BBsPbOpUlXyu" colab_type="text" # ### Network Architecture # + [markdown] id="s9YYYnW8lXyu" colab_type="text" # The network in this notebook is an implementation of the ResNet-18 [1] architecture on the MNIST digits dataset (http://yann.lecun.com/exdb/mnist/) to train a handwritten digit classifier. # # # References # # - [1] <NAME>., <NAME>., <NAME>., & <NAME>. (2016). Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 770-778). ([CVPR Link](https://www.cv-foundation.org/openaccess/content_cvpr_2016/html/He_Deep_Residual_Learning_CVPR_2016_paper.html)) # # - [2] http://yann.lecun.com/exdb/mnist/ # + [markdown] id="X2Qut7r-lXyv" colab_type="text" # The following figure illustrates residual blocks with skip connections such that the input passed via the shortcut matches the dimensions of the main path's output, which allows the network to learn identity functions. # # ![](https://github.com/DeepSE/deeplearning-models/blob/master/pytorch_ipynb/images/resnets/resnet-ex-1-1.png?raw=1) # # # The ResNet-18 architecture actually uses residual blocks with skip connections such that the input passed via the shortcut matches is resized to dimensions of the main path's output. Such a residual block is illustrated below: # # ![](https://github.com/DeepSE/deeplearning-models/blob/master/pytorch_ipynb/images/resnets/resnet-ex-1-2.png?raw=1) # + [markdown] id="5bUUK_aOlXyv" colab_type="text" # For a more detailed explanation see the other notebook, [resnet-ex-1.ipynb](resnet-ex-1.ipynb). # + [markdown] colab_type="text" id="MkoGLH_Tj5wn" # ## Imports # + colab_type="code" id="ORj09gnrj5wp" colab={} import os import time import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms import matplotlib.pyplot as plt from PIL import Image if torch.cuda.is_available(): torch.backends.cudnn.deterministic = True # + [markdown] colab_type="text" id="I6hghKPxj5w0" # ## Model Settings # + colab_type="code" id="NnT0sZIwj5wu" colab={} ########################## ### SETTINGS ########################## # Hyperparameters RANDOM_SEED = 1 LEARNING_RATE = 0.001 BATCH_SIZE = 128 NUM_EPOCHS = 10 # Architecture NUM_FEATURES = 28*28 NUM_CLASSES = 10 # Other DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") GRAYSCALE = True # + [markdown] id="QlumT-MjlXy2" colab_type="text" # ### MNIST Dataset # + id="_zAvMhZmlXy2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 441, "referenced_widgets": ["fb116836ee8e43d98c01517ce3c6bf55", "f963909691ed44c19cd1d961024a37e8", "3c7a7d130e7743f3b4a53450af99e594", "0f0bf3896136445b8c6336db8a20bcd0", "97fed581c2f64a6d8ef94804208145a6", "abe84a0ecf454f8d897a3a7a37f8d304", "f7808f0de2204b4eb891e1bb6ee08603", "<KEY>", "a5a911fa9d0344a8984e0b8e68a676ef", "745ec1c6e99044c9b08a6174f581a18a", "feddc949df7d4eebbe5fe54a49719c18", "<KEY>", "15cdc2881ee54842afdf28d90937e39a", "<KEY>", "4a9d624827224f2bb4e44be436015958", "1dce1df751d04bf682a876d974c96058", "62223304a6df42b89e331149045e2d7d", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "09e83eaa6fe9472e95c18fbeeb477510", "8b96b8c4605e4d18aa9a82d730a96cba", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "eeb77e10d04746a4b6bda725749aee1b", "<KEY>", "<KEY>", "<KEY>"]} outputId="6b882db4-c08d-4bcf-8400-6d89ed0e418a" ########################## ### MNIST DATASET ########################## # Note transforms.ToTensor() scales input images # to 0-1 range train_dataset = datasets.MNIST(root='data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = datasets.MNIST(root='data', train=False, transform=transforms.ToTensor()) train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False) # Checking the dataset for images, labels in train_loader: print('Image batch dimensions:', images.shape) print('Image label dimensions:', labels.shape) break # + id="awWDVI9BlXy5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 52} outputId="4aa65033-7ccc-4e0a-c9f2-3ec416aec5ac" device = torch.device(DEVICE) torch.manual_seed(0) for epoch in range(2): for batch_idx, (x, y) in enumerate(train_loader): print('Epoch:', epoch+1, end='') print(' | Batch index:', batch_idx, end='') print(' | Batch size:', y.size()[0]) x = x.to(device) y = y.to(device) break # + [markdown] id="InUqxoJslXy8" colab_type="text" # The following code cell that implements the ResNet-34 architecture is a derivative of the code provided at https://pytorch.org/docs/0.4.0/_modules/torchvision/models/resnet.html. # + id="6L5jLjHPlXy8" colab_type="code" colab={} ########################## ### MODEL ########################## def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes, grayscale): self.inplanes = 64 if grayscale: in_dim = 1 else: in_dim = 3 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(in_dim, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, (2. / n)**.5) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) # because MNIST is already 1x1 here: # disable avg pooling #x = self.avgpool(x) x = x.view(x.size(0), -1) logits = self.fc(x) probas = F.softmax(logits, dim=1) return logits, probas def resnet18(num_classes): """Constructs a ResNet-18 model.""" model = ResNet(block=BasicBlock, layers=[2, 2, 2, 2], num_classes=NUM_CLASSES, grayscale=GRAYSCALE) return model # + colab_type="code" id="_lza9t_uj5w1" colab={} torch.manual_seed(RANDOM_SEED) model = resnet18(NUM_CLASSES) model.to(DEVICE) optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE) # + id="LQw3SPYsli54" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 332} outputId="d42c2886-a835-42a3-b599-a935038b0a2d" import hiddenlayer as hl hl.build_graph(model, torch.zeros([64, 1, 28, 28]).to(DEVICE)) # + [markdown] colab_type="text" id="RAodboScj5w6" # ## Training # + colab_type="code" id="Dzh3ROmRj5w7" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="cf0ee808-a38e-456c-db31-1e33f1d65870" def compute_accuracy(model, data_loader, device): correct_pred, num_examples = 0, 0 for i, (features, targets) in enumerate(data_loader): features = features.to(device) targets = targets.to(device) logits, probas = model(features) _, predicted_labels = torch.max(probas, 1) num_examples += targets.size(0) correct_pred += (predicted_labels == targets).sum() return correct_pred.float()/num_examples * 100 start_time = time.time() for epoch in range(NUM_EPOCHS): model.train() for batch_idx, (features, targets) in enumerate(train_loader): features = features.to(DEVICE) targets = targets.to(DEVICE) ### FORWARD AND BACK PROP logits, probas = model(features) cost = F.cross_entropy(logits, targets) optimizer.zero_grad() cost.backward() ### UPDATE MODEL PARAMETERS optimizer.step() ### LOGGING if not batch_idx % 50: print ('Epoch: %03d/%03d | Batch %04d/%04d | Cost: %.4f' %(epoch+1, NUM_EPOCHS, batch_idx, len(train_loader), cost)) model.eval() with torch.set_grad_enabled(False): # save memory during inference print('Epoch: %03d/%03d | Train: %.3f%%' % ( epoch+1, NUM_EPOCHS, compute_accuracy(model, train_loader, device=DEVICE))) print('Time elapsed: %.2f min' % ((time.time() - start_time)/60)) print('Total Training Time: %.2f min' % ((time.time() - start_time)/60)) # + [markdown] colab_type="text" id="paaeEQHQj5xC" # ## Evaluation # + colab_type="code" id="gzQMWKq5j5xE" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="64501a70-6b33-4760-d464-d8042d12e2c5" with torch.set_grad_enabled(False): # save memory during inference print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader, device=DEVICE))) # + id="6KyigbIjlXzG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="ff993d03-75cb-4409-aaa7-125f287a3dee" for batch_idx, (features, targets) in enumerate(test_loader): features = features targets = targets break nhwc_img = np.transpose(features[0], axes=(1, 2, 0)) nhw_img = np.squeeze(nhwc_img.numpy(), axis=2) plt.imshow(nhw_img, cmap='Greys'); # + id="6Ph4wKTDlXzJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="e02cba66-2f8c-483c-8cab-69a890ef4aef" model.eval() logits, probas = model(features.to(device)[0, None]) print('Probability 7 %.2f%%' % (probas[0][7]*100)) # + id="lAEICKXYlXzL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 104} outputId="7ff48dce-42f4-43f5-d609-e0ceb14ad1bc" # %watermark -iv
pytorch_ipynb/cnn/cnn-resnet18-mnist.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Exercise 3: Parallel ETL # %load_ext sql from time import time import configparser import matplotlib.pyplot as plt import pandas as pd # # STEP 1: Get the params of the created redshift cluster # - We need: # - The redshift cluster <font color='red'>endpoint</font> # - The <font color='red'>IAM role ARN</font> that give access to Redshift to read from S3 # + config = configparser.ConfigParser() config.read_file(open('dwh.cfg')) KEY=config.get('AWS','key') SECRET= config.get('AWS','secret') DWH_DB= config.get("DWH","DWH_DB") DWH_DB_USER= config.get("DWH","DWH_DB_USER") DWH_DB_PASSWORD= config.get("DWH","DWH_DB_PASSWORD") DWH_PORT = config.get("DWH","DWH_PORT") # + # FILL IN THE REDSHIFT ENPOINT HERE # e.g. DWH_ENDPOINT="redshift-cluster-1.csmamz5zxmle.us-west-2.redshift.amazonaws.com" DWH_ENDPOINT="" #FILL IN THE IAM ROLE ARN you got in step 2.2 of the previous exercise #e.g DWH_ROLE_ARN="arn:aws:iam::988332130976:role/dwhRole" DWH_ROLE_ARN="" # - # # STEP 2: Connect to the Redshift Cluster conn_string="postgresql://{}:{}@{}:{}/{}".format(DWH_DB_USER, DWH_DB_PASSWORD, DWH_ENDPOINT, DWH_PORT,DWH_DB) print(conn_string) # %sql $conn_string # + import boto3 s3 = boto3.resource('s3', region_name="us-west-2", aws_access_key_id=KEY, aws_secret_access_key=SECRET ) sampleDbBucket = s3.Bucket("udacity-labs") for obj in sampleDbBucket.objects.filter(Prefix="tickets"): print(obj) # - # # STEP 3: Create Tables # + language="sql" # DROP TABLE IF EXISTS "sporting_event_ticket"; # CREATE TABLE "sporting_event_ticket" ( # "id" double precision DEFAULT nextval('sporting_event_ticket_seq') NOT NULL, # "sporting_event_id" double precision NOT NULL, # "sport_location_id" double precision NOT NULL, # "seat_level" numeric(1,0) NOT NULL, # "seat_section" character varying(15) NOT NULL, # "seat_row" character varying(10) NOT NULL, # "seat" character varying(10) NOT NULL, # "ticketholder_id" double precision, # "ticket_price" numeric(8,2) NOT NULL # ); # - # # STEP 4: Load Partitioned data into the cluster # + # %%time qry = """ copy sporting_event_ticket from 's3://udacity-labs/tickets/split/part' credentials 'aws_iam_role={}' gzip delimiter ';' compupdate off region 'us-west-2'; """.format(DWH_ROLE_ARN) # %sql $qry # - # # STEP 4: Create Tables for the non-partitioned data # + language="sql" # DROP TABLE IF EXISTS "sporting_event_ticket_full"; # CREATE TABLE "sporting_event_ticket_full" ( # "id" double precision DEFAULT nextval('sporting_event_ticket_seq') NOT NULL, # "sporting_event_id" double precision NOT NULL, # "sport_location_id" double precision NOT NULL, # "seat_level" numeric(1,0) NOT NULL, # "seat_section" character varying(15) NOT NULL, # "seat_row" character varying(10) NOT NULL, # "seat" character varying(10) NOT NULL, # "ticketholder_id" double precision, # "ticket_price" numeric(8,2) NOT NULL # ); # - # # STEP 5: Load non-partitioned data into the cluster # - Note how it's slower than loading partitioned data # + # %%time qry = """ copy sporting_event_ticket_full from 's3://udacity-labs/tickets/full/full.csv.gz' credentials 'aws_iam_role={}' gzip delimiter ';' compupdate off region 'us-west-2'; """.format(DWH_ROLE_ARN) # %sql $qry # -
3-CloudDataWarehouses/L3-Exercise3-ParallelETL-Solution.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline from pyvista import set_plot_theme set_plot_theme('document') # Ray Tracing {#ray_trace_example} # =========== # # Single line segment ray tracing for PolyData objects. # # + import pyvista as pv # Create source to ray trace sphere = pv.Sphere(radius=0.85) # Define line segment start = [0, 0, 0] stop = [0.25, 1, 0.5] # Perform ray trace points, ind = sphere.ray_trace(start, stop) # Create geometry to represent ray trace ray = pv.Line(start, stop) intersection = pv.PolyData(points) # Render the result p = pv.Plotter() p.add_mesh(sphere, show_edges=True, opacity=0.5, color="w", lighting=False, label="Test Mesh") p.add_mesh(ray, color="blue", line_width=5, label="Ray Segment") p.add_mesh(intersection, color="maroon", point_size=25, label="Intersection Points") p.add_legend() p.show()
poly-ray-trace.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="XWLQv-VPXYGR" colab_type="code" outputId="3690b6be-cc7e-4182-edaa-8198a2eea36d" executionInfo={"status": "ok", "timestamp": 1581696895747, "user_tz": -60, "elapsed": 5458, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 272} # !pip install eli5 # + id="e7O6ssWcXbaA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 168} outputId="410d9613-555d-4328-a4ce-ff18448e7aaf" executionInfo={"status": "ok", "timestamp": 1581696898534, "user_tz": -60, "elapsed": 8239, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "09999408322042952417"}} import pandas as pd import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import cross_val_score import eli5 from eli5.sklearn import PermutationImportance from ast import literal_eval from tqdm import tqdm_notebook # + id="9hIiNgAxYIiM" colab_type="code" outputId="47791488-75c7-49cf-fe12-029fbee94ebb" executionInfo={"status": "ok", "timestamp": 1581696898535, "user_tz": -60, "elapsed": 8229, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrixv2' # + id="akB38dNrYjhX" colab_type="code" outputId="bddb0eda-cd84-4013-dce8-89fe394b74a8" executionInfo={"status": "ok", "timestamp": 1581696900500, "user_tz": -60, "elapsed": 10183, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} # ls # + id="_wey2wuJYkjo" colab_type="code" outputId="a5d1ce6b-7fba-4d3f-dcdd-93c0bde30d8a" executionInfo={"status": "ok", "timestamp": 1581696902023, "user_tz": -60, "elapsed": 11688, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} # ls data # + id="MX7h9CfdYuqg" colab_type="code" colab={} df = pd.read_csv('/content/drive/My Drive/Colab Notebooks/dw_matrixv2/data/men_shoes.csv', low_memory=False) # + id="YeQAON3gY3ZY" colab_type="code" outputId="e024d154-54ad-49c9-ea1a-99574302d7b6" executionInfo={"status": "ok", "timestamp": 1581696917859, "user_tz": -60, "elapsed": 511, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 513} df.head() # + id="JXD9jwyVZKqy" colab_type="code" colab={} def run_model(feats, model=DecisionTreeRegressor(max_depth=5)): X = df[ feats ].values y = df[ 'prices_amountmin'].values scores = cross_val_score(model, X, y, scoring = 'neg_mean_absolute_error') return np.mean(scores), np.std(scores) # + id="cmcGtR2CZ6OU" colab_type="code" outputId="e3b255ef-c67b-4d57-adfd-c50bfb261699" executionInfo={"status": "ok", "timestamp": 1581696930205, "user_tz": -60, "elapsed": 714, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} df['brand_cat'] = df['brand'].map(lambda x: str(x).lower()).factorize()[0] run_model(['brand_cat']) # + id="89jx6lAyaMMo" colab_type="code" outputId="054db722-ed9a-44cb-95e1-bc52c1f37337" executionInfo={"status": "ok", "timestamp": 1581696935480, "user_tz": -60, "elapsed": 3722, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} model = RandomForestRegressor(max_depth=5, n_estimators=100, random_state=0) run_model(['brand_cat'],model) # + id="HENYzrlMaqg6" colab_type="code" outputId="328ac173-a2d8-4eca-b438-eaeaa9bc0854" executionInfo={"status": "ok", "timestamp": 1581696936081, "user_tz": -60, "elapsed": 698, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 513} df.head() # + id="9qYfigG0cmfC" colab_type="code" outputId="35a3384b-795a-45b3-dd9b-def76ccf83b0" executionInfo={"status": "ok", "timestamp": 1581696907722, "user_tz": -60, "elapsed": 13610, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 139} df.features.head().values # + id="p69LL4eAc4H4" colab_type="code" outputId="0e8cf5f1-8f65-49fb-d7bd-e146583eee37" executionInfo={"status": "ok", "timestamp": 1581696907723, "user_tz": -60, "elapsed": 12879, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} test = {'key':'test'} test['key'] # + id="uzmluXINdMJo" colab_type="code" outputId="7914468d-7644-45ef-bed5-4366f8884320" executionInfo={"status": "ok", "timestamp": 1581696907724, "user_tz": -60, "elapsed": 12324, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} str(test) # + id="6u2POlZzdRl4" colab_type="code" colab={} str_dict = '[{"key":"Gender","value":["Men"]},{"key":"Shoe Size","value":["M"]},{"key":"Shoe Category","value":["Men\'s Shoes"]},{"key":"Color","value":["Multicolor"]},{"key":"Manufacturer Part Number","value":["8190-W-NAVY-7.5"]},{"key":"Brand","value":["Josmo"]}]' # + id="-fShcYv-d5C2" colab_type="code" outputId="0426ea3d-7a87-4897-c2ad-434ad9d5f2cf" executionInfo={"status": "ok", "timestamp": 1581696907725, "user_tz": -60, "elapsed": 11056, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 119} literal_eval(str_dict) # + id="wDybb8SQfZuj" colab_type="code" outputId="083193fd-c2e5-4626-f0eb-24af028a9d3d" executionInfo={"status": "ok", "timestamp": 1581696907725, "user_tz": -60, "elapsed": 10358, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 54} str(str_dict) # + id="b5ROzYijgcZr" colab_type="code" colab={} def parse_features(x): output_dict = {} if str(x) == 'nan' : return output_dict features = literal_eval(x.replace('\\"','"')) for item in features: key = item['key'].lower().strip() value = item['value'][0].lower().strip() output_dict[key] = value return output_dict df['features_parsed'] = df['features'].map(parse_features) # + id="G0N1esRFzcZT" colab_type="code" outputId="547c9c5d-f97d-4aff-a1da-8185a40d2d30" executionInfo={"status": "ok", "timestamp": 1581705481695, "user_tz": -60, "elapsed": 568, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} colab={"base_uri": "https://localhost:8080/", "height": 34} keys = set() df['features_parsed'].map( lambda x: keys.update(x.keys()) ) len(keys) # + id="KczoQ8yazj-h" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 66, "referenced_widgets": ["f3906080266e4bdf98f7d3c0919e0c5b", "405ba01bd2eb4c7091aac4ee63ba3f55", "1c85e69265aa4358aaacde39e0d5a16c", "5bc80ebf17b4430b859e460b7a6cc5ba", "<KEY>", "<KEY>", "a6749611a98042abb34e59cf81d2a411", "baefb1aec515431ab5c22d0ec9339a2c"]} outputId="37d739b5-4b74-4503-8c28-92d5136a77af" executionInfo={"status": "ok", "timestamp": 1581705882978, "user_tz": -60, "elapsed": 4501, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} def get_name_feat(key): return 'feat_' + key for key in tqdm_notebook(keys): df[get_name_feat(key)] = df.features_parsed.map( lambda feats: feats[key] if key in feats else np.nan ) # + id="SjtPW6QIBFsF" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 153} outputId="a3007450-29fe-45cf-e942-e85f380844ff" executionInfo={"status": "ok", "timestamp": 1581705909608, "user_tz": -60, "elapsed": 505, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "09999408322042952417"}} df.columns # + id="zaiA0ad6BNLj" colab_type="code" colab={} keys_stat = {} for key in keys: keys_stat[key] = df[ False == df[get_name_feat(key)].isnull() ].shape[0]/df.shape[0] *100 # + id="jGSfkLnbBaaE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f0a759c6-0c27-4428-f461-0c7ed28b1efe" executionInfo={"status": "ok", "timestamp": 1581705974006, "user_tz": -60, "elapsed": 571, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df.shape[0] # + id="3rf3zyNKBc40" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 102} outputId="c2465c9b-6724-4007-e713-d038e4def705" executionInfo={"status": "ok", "timestamp": 1581706277191, "user_tz": -60, "elapsed": 572, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} {k:v for k,v in keys_stat.items() if v > 30} # + id="iYvfs5sRCGGU" colab_type="code" colab={} df['feat_brand_cat'] = df['feat_brand'].factorize()[0] df['feat_color_cat'] = df['feat_color'].factorize()[0] df['feat_gender_cat'] = df['feat_gender'].factorize()[0] df['feat_manufacturer part number_cat'] = df['feat_manufacturer part number'].factorize()[0] df['feat_material_cat'] = df['feat_material'].factorize()[0] df['feat_sport_cat'] = df['feat_sport'].factorize()[0] df['feat_style_cat'] = df['feat_style'].factorize()[0] for key in keys: df[ get_name_feat(key) + '_cat'] = df[get_name_feat(key)].factorize()[0] # + id="46ygAHlMCzYr" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="99c20a64-fa9d-41fb-a35d-7fd9bb199f94" executionInfo={"status": "ok", "timestamp": 1581706670932, "user_tz": -60, "elapsed": 668, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df['brand'] = df['brand'].map(lambda x: str(x).lower() ) df[ df.brand == df.feat_brand].shape # + id="l3NeZbu1EQaq" colab_type="code" colab={} feats = [''] # + id="_DFMAhIACy9C" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="405a1bcd-dcb0-4fb3-9c61-be58d33917eb" executionInfo={"status": "ok", "timestamp": 1581706791290, "user_tz": -60, "elapsed": 3683, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} model = RandomForestRegressor(max_depth=5, n_estimators=100) run_model(['brand_cat'],model) # + id="vatsI_pHKknj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="22efe8b6-9741-4d67-dceb-4ae963292d4a" executionInfo={"status": "ok", "timestamp": 1581708408560, "user_tz": -60, "elapsed": 535, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} feats_cat = [x for x in df.columns if 'cat' in x] feats_cat # + id="Ek9RB35SEjpV" colab_type="code" colab={} feats = ['brand_cat', 'feat_metal type_cat', 'feat_brand_cat', 'feat_gender_cat', 'feat_material_cat', 'feat_style_cat', 'feat_sport_cat','feat_shape_cat'] #feats += feats_cat #feats = list(set(feats)) model = RandomForestRegressor(max_depth=5, n_estimators=100) result = run_model(feats,model) # + id="WtyXyjRVFMMd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 187} outputId="67b5a00f-7ab8-4f2a-c7e3-6f5c264096c1" executionInfo={"status": "ok", "timestamp": 1581709002714, "user_tz": -60, "elapsed": 4280, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} X = df [ feats ].values y = df['prices_amountmin'].values m = RandomForestRegressor(max_depth=5, n_estimators =100, random_state=0) m.fit(X,y) print(result) perm = PermutationImportance(m, random_state=1).fit(X,y); eli5.show_weights(perm, feature_names=feats) # + id="_IZCOjOkFsM4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="3c6ca207-dc98-4220-8f4a-02b8bfaed51c" executionInfo={"status": "ok", "timestamp": 1581707262949, "user_tz": -60, "elapsed": 378, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df['brand'].value_counts(normalize=True) # + id="YerO9CWwGU5_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 139} outputId="5049b7e2-5f8f-4200-87d5-c692b41e545f" executionInfo={"status": "ok", "timestamp": 1581707580274, "user_tz": -60, "elapsed": 645, "user": {"displayName": "<NAME>0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df [ df['brand'] == 'nike'].features_parsed.sample(5).values # + id="vs9mUCa_Gnbl" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 289} outputId="cc3d344f-4f64-4a65-d5fa-e2004b34a1ef" executionInfo={"status": "ok", "timestamp": 1581707640063, "user_tz": -60, "elapsed": 572, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df['feat_age group'].value_counts() # + id="-aZWctB_HxjY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 170} outputId="3c6524f5-f2e1-46b1-f2a8-7cd92c62b6aa" executionInfo={"status": "ok", "timestamp": 1581708832954, "user_tz": -60, "elapsed": 390, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df.columns # + id="cWNqTbDHMW5o" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 289} outputId="7cae9d38-3e64-488d-e17d-afa07e3ebcef" executionInfo={"status": "ok", "timestamp": 1581708919969, "user_tz": -60, "elapsed": 545, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} df['weight'].unique() #znormalizowaฤ‡ pozniej wage! #skonwertowac do gramรณw # + id="mc4ygrUvMacx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="8ca50ed7-9788-4ea1-95b9-34bbc25ce05c" executionInfo={"status": "ok", "timestamp": 1581709141199, "user_tz": -60, "elapsed": 1793, "user": {"displayName": "<NAME>\u0144czyk", "photoUrl": "", "userId": "09999408322042952417"}} # !git add matrix_one/day5.ipynb # + id="vaw2kReZNdwE" colab_type="code" colab={}
matrix_one/day5.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from citylearn import CityLearn, building_loader, auto_size from energy_models import HeatPump, EnergyStorage, Building import matplotlib.pyplot as plt import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import collections import gym from gym.utils import seeding from gym import core, spaces import os import ptan import time import argparse import model, common from matplotlib.pyplot import figure import numpy as np # + class AgentD4PG(ptan.agent.BaseAgent): """ Agent implementing noisy agent """ def __init__(self, net, device="cpu", epsilon=1.0): self.net = net self.device = device self.epsilon = epsilon def __call__(self, states, agent_states): states_v = ptan.agent.float32_preprocessor(states).to(self.device) mu_v = self.net(states_v) actions = mu_v.data.cpu().numpy() actions += self.epsilon * np.random.normal(size=actions.shape) actions = np.clip(actions, -1, 1) return actions, agent_states class DDPGActor(nn.Module): def __init__(self, obs_size, act_size): super(DDPGActor, self).__init__() self.net = nn.Sequential( nn.Linear(obs_size, 4), nn.ReLU(), nn.Linear(4, 4), nn.ReLU(), nn.Linear(4, act_size), nn.Tanh() ) def forward(self, x): return self.net(x) class DDPGCritic(nn.Module): def __init__(self, obs_size, act_size): super(DDPGCritic, self).__init__() self.obs_net = nn.Sequential( nn.Linear(obs_size, 8), nn.BatchNorm1d(8), nn.ReLU(), ) self.out_net = nn.Sequential( nn.Linear(8 + act_size, 6), nn.BatchNorm1d(6), nn.ReLU(), nn.Linear(6, 1) ) def forward(self, x, a): obs = self.obs_net(x) return self.out_net(torch.cat([obs, a], dim=1)) # + from pathlib import Path data_folder = Path("data/") demand_file = data_folder / "AustinResidential_TH.csv" weather_file = data_folder / 'Austin_Airp_TX-hour.csv' # - building_ids = [4, 5, 9, 16, 21, 26, 33, 36, 49, 59] # + heat_pump, heat_tank, cooling_tank = {}, {}, {} #Ref: Assessment of energy efficiency in electric storage water heaters (2008 Energy and Buildings) loss_factor = 0.19/24 buildings = {} for uid in building_ids: heat_pump[uid] = HeatPump(nominal_power = 9e12, eta_tech = 0.22, t_target_heating = 45, t_target_cooling = 10) heat_tank[uid] = EnergyStorage(capacity = 9e12, loss_coeff = loss_factor) cooling_tank[uid] = EnergyStorage(capacity = 9e12, loss_coeff = loss_factor) buildings[uid] = Building(uid, heating_storage = heat_tank[uid], cooling_storage = cooling_tank[uid], heating_device = heat_pump[uid], cooling_device = heat_pump[uid]) buildings[uid].state_space(np.array([24.0, 40.0, 1.001]), np.array([1.0, 17.0, -0.001])) buildings[uid].action_space(np.array([0.5]), np.array([-0.5])) # - building_loader(demand_file, weather_file, buildings) auto_size(buildings, t_target_heating = 45, t_target_cooling = 10) env = {} for uid in building_ids: env[uid] = CityLearn(demand_file, weather_file, buildings = {uid: buildings[uid]}, time_resolution = 1, simulation_period = (3500,6000)) env[uid](uid) # + for uid in building_ids[0]: while not env[building_ids[-1]]._terminal(): reward = env[uid].step(agent[uid]) # - if __name__ == "__main__": N_AGENTS = 2 GAMMA = 0.99 BATCH_SIZE = 5000 LEARNING_RATE_ACTOR = 1e-4 LEARNING_RATE_CRITIC = 1e-3 REPLAY_SIZE = 5000 REPLAY_INITIAL = 100 TEST_ITERS = 120 EPSILON_DECAY_LAST_FRAME = 1000 EPSILON_START = 1.2 EPSILON_FINAL = 0.02 device = torch.device("cpu") act_net, crt_net, tgt_act_net, tgt_crt_net, agent, exp_source, buffer, act_opt, crt_opt, frame_idx = {}, {}, {}, {}, {}, {}, {}, {}, {}, {} rew_last_1000, rew, track_loss_critic, track_loss_actor = {}, {}, {}, {} # for uid in buildings: # env[uid].reset() for uid in building_ids: #Create as many actor and critic nets as number of agents #Actor: states_agent_i -> actions_agent_i act_net[uid] = DDPGActor(buildings[uid].observation_spaces.shape[0], buildings[uid].action_spaces.shape[0]).to(device) #Critic: states_all_agents + actions_all_agents -> Q-value_agent_i [1] crt_net[uid] = DDPGCritic(buildings[uid].observation_spaces.shape[0], buildings[uid].action_spaces.shape[0]).to(device) tgt_act_net[uid] = ptan.agent.TargetNet(act_net[uid]) tgt_crt_net[uid] = ptan.agent.TargetNet(crt_net[uid]) agent[uid] = model.AgentD4PG(act_net[uid], device=device) exp_source[uid] = ptan.experience.ExperienceSourceFirstLast(env[uid], agent[uid], gamma=GAMMA, steps_count=1) buffer[uid] = ptan.experience.ExperienceReplayBuffer(exp_source[uid], buffer_size=REPLAY_SIZE) act_opt[uid] = optim.Adam(act_net[uid].parameters(), lr=LEARNING_RATE_ACTOR) crt_opt[uid] = optim.Adam(crt_net[uid].parameters(), lr=LEARNING_RATE_CRITIC) frame_idx[uid] = 0 rew_last_1000[uid], rew[uid], track_loss_critic[uid], track_loss_actor[uid] = [], [], [], [] batch, states_v, actions_v, rewards_v, dones_mask, last_states_v, q_v, last_act_v, q_last_v, q_ref_v, critic_loss_v, cur_actions_v, actor_loss_v = {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} cost, price_list, buffer_reward = {},{},{} for uid in buildings: cost[uid] = [] price_list[uid] = [] buffer_reward[uid] = [] while not env[building_ids[-1]]._terminal(): if frame_idx[4]%100 == 0: print(frame_idx[uid]) for uid in buildings: # print(env[uid].time_step) agent[uid].epsilon = max(EPSILON_FINAL, EPSILON_START - frame_idx[uid] / EPSILON_DECAY_LAST_FRAME) frame_idx[uid] += 1 buffer[uid].populate(1) # print(buffer[uid].buffer[-1]) # print(env[uid].buildings[uid].time_step) price = env[uid].total_electric_consumption[-1]*3e-5 + 0.045 price_list[uid].append(price) for uid in buildings: buffer_reward[uid].append(buffer[uid].buffer[-1].reward) electricity_cost = buffer[uid].buffer[-1].reward*price cost[uid].append(-electricity_cost) buffer[uid].buffer[-1] = buffer[uid].buffer[-1]._replace(reward=electricity_cost) if len(buffer[uid]) < REPLAY_INITIAL: continue for uid in buildings: for k in range(6): batch[uid] = buffer[uid].sample(BATCH_SIZE) states_v[uid], actions_v[uid], rewards_v[uid], dones_mask[uid], last_states_v[uid] = common.unpack_batch_ddqn(batch[uid], device) # TRAIN CRITIC crt_opt[uid].zero_grad() #Obtaining Q' using critic net with parameters teta_Q' q_v[uid] = crt_net[uid](states_v[uid], actions_v[uid]) #Obtaining estimated optimal actions a|teta_mu from target actor net and from s_i+1. last_act_v[uid] = tgt_act_net[uid].target_model(last_states_v[uid]) #<----- Actor to train Critic #Obtaining Q'(s_i+1, a|teta_mu) from critic net Q' q_last_v[uid] = tgt_crt_net[uid].target_model(last_states_v[uid], last_act_v[uid]) q_last_v[uid][dones_mask[uid]] = 0.0 #Q_target used to train critic net Q' q_ref_v[uid] = rewards_v[uid].unsqueeze(dim=-1) + q_last_v[uid] * GAMMA critic_loss_v[uid] = F.mse_loss(q_v[uid], q_ref_v[uid].detach()) critic_loss_v[uid].backward() crt_opt[uid].step() # TRAIN ACTOR act_opt[uid].zero_grad() #Obtaining estimated optimal current actions a|teta_mu from actor net and from s_i cur_actions_v[uid] = act_net[uid](states_v[uid]) #Actor loss = mean{ -Q_i'(s_i, a|teta_mu) } actor_loss_v[uid] = -crt_net[uid](states_v[uid], cur_actions_v[uid]) #<----- Critic to train Actor actor_loss_v[uid] = actor_loss_v[uid].mean() #Find gradient of the loss and backpropagate to perform the updates of teta_mu actor_loss_v[uid].backward() act_opt[uid].step() if frame_idx[uid] % 1 == 0: tgt_act_net[uid].alpha_sync(alpha=1 - 0.1) tgt_crt_net[uid].alpha_sync(alpha=1 - 0.1) from matplotlib.pyplot import figure #Plotting all the individual actions figure(figsize=(18, 6)) for uid in buildings: plt.plot(env[uid].action_track[uid][2300:2500]) plt.show()
docs/.ipynb_checkpoints/ptan_implementation-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + from __future__ import print_function from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM from keras.datasets import imdb from keras.utils import plot_model from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV max_features = 20000 maxlen = 80 # cut texts after this number of words (among top max_features most common words) batch_size = 32 # - from datetime import datetime print(datetime.now().strftime("%Y/%m/%d %H:%M:%S")) # + print('Loading data...') (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features) print(len(x_train), 'train sequences') print(len(x_test), 'test sequences') print('Pad sequences (samples x time)') x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_test = sequence.pad_sequences(x_test, maxlen=maxlen) x_train = sequence.pad_sequences(x_train) x_test = sequence.pad_sequences(x_test) print('x_train shape:', x_train.shape) print('x_test shape:', x_test.shape) print('Build model...') # - # try using different optimizers and different optimizer configs def create_model(activation='sigmoid', drop_out=0.2, recurrent_dropout=0.2): model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(128, dropout=drop_out, recurrent_dropout=recurrent_dropout)) model.add(Dense(1, activation=activation)) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # # plot model # plot_model(model, to_file='model.png', show_shapes=True) return model print(datetime.now().strftime("%Y/%m/%d %H:%M:%S")) # + # # train # from matplotlib import pyplot as plt # # print('Train...') # lstm = model.fit(x_train, y_train, # batch_size=batch_size, # epochs=15, # validation_data=(x_test, y_test)) # # # evaluate # score, acc = model.evaluate(x_test, y_test, # batch_size=batch_size) # print('Test score:', score) # print('Test accuracy:', acc) # # # plot acc and loss # x = range(15) # plt.plot(x, lstm.history['acc'], label="acc") # plt.plot(x, lstm.history['loss'], label="loss") # # plt.title("binary train accuracy") # plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # plt.show() # + # grid search #activations = ["softplus", "softsign", "relu", "tanh", "sigmoid", "hard_sigmoid", "linear"] activations = ["tanh", "sigmoid"] drop_outs = [0.2, 0.5] recurrent_dropouts = [0.2, 0.5] param_grid = dict(activation=activations, drop_out=drop_outs, recurrent_dropout=recurrent_dropouts) model = KerasClassifier(build_fn=create_model, nb_epoch=15, batch_size=batch_size, verbose=0) grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=4, scoring='accuracy', n_jobs=-1) grid_result = grid.fit(x_train, y_train) print(grid_result.best_score_) print(grid_result.best_params_) print(datetime.now().strftime("%Y/%m/%d %H:%M:%S")) # -
notebook/imdb_lstm_notebook.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # Introduction to Geopandas # # Geopandas (http://geopandas.org/) makes it possible to work with geospatial data in Python in a relatively easy way. Geopandas combines the capabilities of the data analysis library [pandas](https://pandas.pydata.org/pandas-docs/stable/) with other packages like [shapely](https://shapely.readthedocs.io/en/stable/manual.html) and [fiona](https://fiona.readthedocs.io/en/latest/manual.html) for managing spatial data. # # The main data structures in geopandas; `GeoSeries` and `GeoDataFrame` extend the capabilities of `Series` and `DataFrames` from pandas. This means that we can apply our pandas skills also with geopandas data structures. If you need to refresh your memory about pandas, check out week 5 and 6 lesson materials from the [Geo-Python website](geo-python.github.io). # # The main difference between geodataframes and pandas dataframes is that [a geodataframe should contain one column for geometries](http://geopandas.org/data_structures.html#geodataframe) (by default, the name of this column is `'geometry'`). The geometry column is a [geoseries](http://geopandas.org/data_structures.html#geoseries) which contains the geometries (points, lines, polygons, multipolygons etc.) for each row of data. # # ![geodataframe.png](img/geodataframe.png) # # As we learned in the Geo-Python course, it is conventional to import pandas as `pd`. Similarly,we will import geopandas as `gpd`: import geopandas as gpd # In this lesson, we will cover basics steps needed for interacting with spatial data in Python using geopandas: # # - Managing filepaths # - Reading a shapefile # - Geometry calculations # - Writing a shapefile # - Grouping and splitting spatial data into multiple layers # # Before diving deeper into geopandas functionalities, let's first acquire some input data to work with. # ## Input data: Finnish topographic database # # - [Topographic Database from the National Land Survey of Finland (NLS)](https://www.maanmittauslaitos.fi/en/maps-and-spatial-data/expert-users/product-descriptions/topographic-database). # - The data set is licensed under the NLS' [open data licence](https://www.maanmittauslaitos.fi/en/opendata-licence-cc40) (CC BY 4.0). # - Structure of the data is described in a separate Excel file ([download link](http://www.maanmittauslaitos.fi/sites/maanmittauslaitos.fi/files/attachments/2018/10/maastotietokanta_kohdemalli_eng.xlsx)). # - Further information about file naming at [fairdata.fi](https://etsin.fairdata.fi/dataset/5023ecc7-914a-4494-9e32-d0a39d3b56ae). # - We acquired the data via the [CSC open data portal](https://avaa.tdata.fi/web/paituli/latauspalvelu): # # ![Paituli data download](img/Paituli_maastotietokanta_download.png) # # # In this lesson, we will focus on **terrain objects** (Feature group: "Terrain/1") downloaded as Shapefiles. According to the [naming convention of the Topographic Database](https://etsin.fairdata.fi/dataset/5023ecc7-914a-4494-9e32-d0a39d3b56ae) for Shapefiles, all files that start with a letter `m` and end with `p` contain the objects we are interested in (Terrain/1 polygons). Furthermore, the Terrain/1 feature group contains several feature classes. **Our final task in this lesson is to save all these feature classes into separate files**. # # *Terrain/1 features in the Topographic Database:* # # | feature class | Name of feature | Feature group | # |----------------|------------------------------------------------------------|---------------| # | 32421 | Motor traffic area | Terrain/1 | # | 32200 | Cemetery | Terrain/1 | # | 34300 | Sand | Terrain/1 | # | 34100 | Rock - area | Terrain/1 | # | 34700 | Rocky area | Terrain/1 | # | 32500 | Quarry | Terrain/1 | # | 32112 | Mineral resources extraction area, fine-grained material | Terrain/1 | # | 32111 | Mineral resources extraction area, coarse-grained material | Terrain/1 | # | 32611 | Field | Terrain/1 | # | 32612 | Garden | Terrain/1 | # | 32800 | Meadow | Terrain/1 | # | 32900 | Park | Terrain/1 | # | 35300 | Paludified land | Terrain/1 | # | 35412 | Bog, easy to traverse forested | Terrain/1 | # | 35411 | Open bog, easy to traverse treeless | Terrain/1 | # | 35421 | Open fen, difficult to traverse treeless | Terrain/1 | # | 33000 | Earth fill | Terrain/1 | # | 33100 | Sports and recreation area | Terrain/1 | # | 36200 | Lake water | Terrain/1 | # | 36313 | Watercourse area | Terrain/1 | # ## Downloading data # # On Binder and CSC Notebook environment, you can use `wget` program to download the data from the command line. Let's download the data ([download link](https://github.com/AutoGIS/data/raw/master/L2_data.zip)) into the same folder with the lesson 2 notebooks (`.../notebooks/L2`): # # - Open up a new terminal window # - Navigate to the correct folder in the terminal: # # ``` # # Navigate to lesson 2 notebooks directory: # $ cd /home/jovyan/work/autogis/notebooks/notebooks/L2 # # ``` # - use `wget` utility to dowload the data from the dowload link: # # ``` # $ wget https://github.com/AutoGIS/data/raw/master/L2_data.zip # # ``` # <div class="alert alert-info"> # # **Copy-paste** # # You can copy/paste things to JupyterLab Terminal by pressing `SHIFT` + `RIGHT-CLICK` on your mouse and choosing `Paste`. # # </div> # # Once you have downloaded the `L2_data.zip` file into your home directory, you can unzip the file using `unzip` command in the Terminal (or e.g. 7zip on Windows if working with own computer). Run the following commands in the `.../notebooks/L2` -directory: # # ``` # $ unzip L2_data.zip # $ ls L2_data # # ``` # You can also check the contents of the downloaded and unzipped file in the file browser window. # # The L2_data folder contains several subfolders. After unzipping the downloaded file, you can find the data for this tutorial under: `L2_data/NLS/2018/L4/L41/L4132R.shp`. Notice that Shapefile -fileformat contains many separate files such as `.dbf` that contains the attribute information, and `.prj` -file that contains information about coordinate reference system. # ## Managing filepaths # # Built-in module `os` provides many useful functions for interacting with the operating system. One of the most useful submodules in the os package is the [os.path-module](https://docs.python.org/2/library/os.path.html) for manipulating file paths. This week, we have data in different sub-folders and we can practice how to use `os` path tools when defining filepaths. # # - Let's import `os` and see how we can construct a filepath by joining a folder path and file name: # + import os # Define path to folder input_folder = r"L2_data/NLS/2018/L4/L41/L4132R.shp" # Join folder path and filename fp = os.path.join(input_folder, "m_L4132R_p.shp") # Print out the full file path print(fp) # - # ## Reading a Shapefile # # Typically reading the data into Python is the first step of the analysis pipeline. There are various different GIS data formats available. [Shapefile](https://en.wikipedia.org/wiki/Shapefile), [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON), [KML](https://en.wikipedia.org/wiki/Keyhole_Markup_Language), and [GPKG](https://en.wikipedia.org/wiki/GeoPackage) are one of the most common vector data formats currently in use. [Geopandas](http://geopandas.org/io.html) is capable of reading data from all of these formats (plus many more). # # In geopandas, we use a generic function [.from_file()](http://geopandas.org/reference.html#geopandas.GeoDataFrame.to_file) for reading in different data formats. In the bacground, Geopandas uses [fiona.open()](https://fiona.readthedocs.io/en/latest/fiona.html#fiona.open) when reading in data. # # - When reading in a Shapefile, we only need to pass the filepath when reading data: # + import geopandas as gpd # Read file using gpd.read_file() data = gpd.read_file(fp) # - # - Let's see check the data type: # + jupyter={"outputs_hidden": false} type(data) # - # Here we see that our `data` -variable is a `GeoDataFrame`. GeoDataFrame extends the functionalities of # `pandas.DataFrame` in a way that it is possible to handle spatial data using similar approaches and datastructures as in pandas (hence the name geopandas). # # - Let's take a look at our data and print the first rows using the `head()` -function: # + jupyter={"outputs_hidden": false} print(data.head()) # - # - Check all column names: data.columns # As most of you probably notice, all the column names are in Finnish... # - Let's select only the useful columns and rename them into English: data = data[['RYHMA', 'LUOKKA', 'geometry']] # - Define new column names in a dictionary: colnames = {'RYHMA':'GROUP', 'LUOKKA':'CLASS'} # - rename the columns: data.rename(columns=colnames, inplace=True) data.columns # <div class="alert alert-info"> # # **Task** # # Figure out the following information from our input data based on your pandas-skills from the Geo-Python course: # # - Number of rows? # - Number of classes? # - Number of groups? # </div> # Solutions: print("Number of rows", len(data['CLASS'])) print("Number of classes", data['CLASS'].nunique()) print("Number of groups", data['GROUP'].nunique()) # It is always a good idea to explore your data also on a map. Creating a simple map from a `GeoDataFrame` is really easy: you can use ``.plot()`` -function from geopandas that **creates a map based on the geometries of the data**. Geopandas actually uses matplotlib for plotting which we introduced in [Lesson 7 of the Geo-Python course](https://geo-python.github.io/site/notebooks/L7/matplotlib.html). # # - Let's try it out, and plot our GeoDataFrame: # + jupyter={"outputs_hidden": false} # %matplotlib inline data.plot() # - # Voilรก! As we can see, it is really easy to produce a map out of your Shapefile with geopandas. Geopandas automatically positions your map in a way that it covers the whole extent of your data. # # *If you are living in the Helsinki region, you might recognize the shapes plotted on the map!* # ## Geometries in Geopandas # # Geopandas takes advantage of Shapely's geometric objects. Geometries are stored in a column called *geometry* that is a default column name for # storing geometric information in geopandas. # - Let's print the first 5 rows of the column 'geometry': # + jupyter={"outputs_hidden": false} # It is possible to get a specific column by specifying the column name within square brackets [] print(data['geometry'].head()) # - # As we can see the `geometry` column contains familiar looking values, namely Shapely `Polygon` -objects. Since the spatial data is stored as Shapely objects, **it is possible to use all of the functionalities of the Shapely module** when dealing with geometries in geopandas. # # Let's have a closer look at the polygons and try to apply some of the [Shapely methods we learned last week](https://automating-gis-processes.github.io/site/notebooks/L1/geometric-objects.html#Polygon). # # - Let's start by checking the area of the first polygon in the data: # print("Polygon:", data.at[0, "geometry"]) print("Area:", round(data.at[0, "geometry"].area,0), "square meters") # # Let's do the same for the first five rows in the data; # # - Iterate over the GeoDataFrame rows using the `iterrows()` -function that we learned [during the Lesson 6 of the Geo-Python course](https://geo-python.github.io/site/notebooks/L6/pandas/advanced-data-processing-with-pandas.html#Iterating-rows-and-using-self-made-functions-in-Pandas). # - For each row, print the area of the polygon (here, we'll limit the for-loop to a selection of the first five rows): # + jupyter={"outputs_hidden": false} # Iterate over rows and print the area of a Polygon for index, row in data[0:5].iterrows(): # Get the area from the shapely-object stored in the geometry-column poly_area = row['geometry'].area # Print info print("Polygon area at index {index} is: {area:.2f} m^2".format(index=index, area=poly_area)) # - # As you see from here, all the functionalities of **pandas**, such as the `iterrows()` function, are directly available in Geopandas without the need to call pandas separately because Geopandas is an **extension** for pandas. # # In practice, it is not necessary to use the iterrows()-approach to calculate the area for all features. Geodataframes and geoseries have an attribute `area` which we can use for accessing the area for each feature at once: data.area.head() # - Let's next create a new column into our GeoDataFrame where we calculate and store the areas of individual polygons: # + jupyter={"outputs_hidden": false} # Create a new column called 'area' and assign the area of the Polygons into it data['area'] = data.area # - # - Check the output: data['area'].head() # These values correspond to the ones we saw in previous step when iterating rows. # # - Let's check what is the `min`, `max` and `mean` of those areas using familiar functions from our previous Pandas lessions. # # Maximum area max_area = data['area'].max() # Minimum area min_area = data['area'].min() # Mean area mean_area = data['area'].mean() print("Max area: {maximum} square meters".format(maximum=round(max_area, 0))) print("Min area: {minimum} square meters".format(minimum=round(min_area, 0))) print("Mean area: {mean} square meters".format(mean=round(mean_area, 0))) # ## Writing a shapefile # # It is possible to export GeoDataFrames into various data formats using [gpd.to_file()](http://geopandas.org/io.html#writing-spatial-data). Here, we will first learn how to export a subset of the data into a Shapefile. # # - Let's first select one class (class number `36200`, "Lake water") from the data as a new GeoDataFrame: # # Select a class selection = data.loc[data["CLASS"]==36200] # - Check the selection: selection.plot() # - write this layer into a new Shapefile using the `gpd.to_file()` -function: # Create a output path for the data output_folder = r"L2_data/" output_fp = os.path.join(output_folder, "Class_36200.shp") # Write those rows into a new file (the default output file format is Shapefile) selection.to_file(output_fp) # <div class="alert alert-info"> # # **Task** # # Read the output Shapefile in a new geodataframe, and check that the data looks ok. # </div> # ## Grouping the Geodataframe # # One really useful function that can be used in Pandas/Geopandas is [.groupby()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) which groups data based on values on selected column(s). We saw and used this function already in [Lesson 6 of the Geo-Python course](https://geo-python.github.io/2018/notebooks/L6/pandas/advanced-data-processing-with-pandas.html#Aggregating-data-in-Pandas-by-grouping). # # Next we will automate the file export task; we will group the data based on column `CLASS` and export a shapefile for each class. # # Let's continue with the same input file we already read previously into the variable `data`. We also selected and renamed a subset of the columns. # # - Check the first rows of the data: data.head() # The `CLASS` column in the data contains information about different land use types. With `.unique()` -function we can quickly see all different values in that column: # + jupyter={"outputs_hidden": false} # Print all unique values in the column print(data['CLASS'].unique()) # - # - Now we can use that information to group our data and save all land use types into different layers: # + jupyter={"outputs_hidden": false} # Group the data by class grouped = data.groupby('CLASS') # Let's see what we have grouped # - # As we can see, `groupby` -function gives us an object called `DataFrameGroupBy` which is similar to list of keys and values (in a dictionary) that we can iterate over. For more information about grouped objects, see [Lesson 6 of the Geo-Python course](https://geo-python.github.io/2018/notebooks/L6/pandas/advanced-data-processing-with-pandas.html#Aggregating-data-in-Pandas-by-grouping). # # - Check out all group keys: grouped.groups.keys() # The group keys are unique values from the column by which we grouped the dataframe. # # - Check how many rows of data each group has: # + jupyter={"outputs_hidden": false} # Iterate over the group object for key, group in grouped: # Let's check how many rows each group has: print('Terrain class:', key) print('Number of rows:', len(group), "\n") # - # There are, for example, 56 lake polygons in the input data. # We can also check how the _last_ group looks like (we have the variables in memory from the last iteration of the for-loop): group.head() # Notice that the index numbers refer to the row numbers in the original data -GeoDataFrame. # Check also the data type of the group: type(group) # As we can see, each set of data are now grouped into separate GeoDataFrames, and we can save them into separate files. # ### Saving multiple output files # # Let's **export each class into a separate Shapefile**. While doing this, we also want to **create unique filenames for each class**. # # When looping over the grouped object, information about the class is stored in the variable `key`, and we can use this information for creating new variable names inside the for-loop. For example, we want to name the shapefile containing lake polygons as "terrain_36200.shp". # # # <div class="alert alert-info"> # # **String formatting** # # There are different approaches for formatting strings in Python. Here are a couple of different ways for putting together file-path names using two variables: # # ``` # basename = "terrain" # key = 36200 # # # OPTION 1. Concatenating using the `+` operator: # out_fp = basename + "_" + str(key) + ".shp" # # # OPTION 2. Positional formatting using `%` operator # out_fp = "%s_%s.shp" %(basename, key) # # # OPTION 3. Positional formatting using `.format()` # out_fp = "{}_{}.shp".format(basename, key) # ``` # # Read more from here: https://pyformat.info/ # </div> # # # Let's now export terrain classes into separate Shapefiles. # # - First, create a new folder for the outputs: # + # Determine output directory output_folder = r"L2_data/" # Create a new folder called 'Results' result_folder = os.path.join(output_folder, 'Results') # Check if the folder exists already if not os.path.exists(result_folder): # If it does not exist, create one os.makedirs(result_folder) # - # At this point, you can go to the file browser and check that the new folder was created successfully. # # - Iterate over groups, create a file name, and save group to file: # + jupyter={"outputs_hidden": false} # Iterate over the groups for key, group in grouped: # Format the filename output_name = "terrain_%s.shp" % str(key) # Print information about the process print("Saving file", os.path.basename(output_name)) # Create an output path outpath = os.path.join(result_folder, output_name) # Export the data group.to_file(outpath) # - # Excellent! Now we have saved those individual classes into separate Shapefiles and named the file according to the class name. These kind of grouping operations can be really handy when dealing with layers of spatial data. Doing similar process manually would be really laborious and error-prone. # ### Extra: save data to csv # We can also extract basic statistics from our geodataframe, and save this information as a text file. # # Let's summarize the total area of each group: area_info = grouped.area.sum().round() area_info # - save area info to csv using pandas: # Create an output path area_info.to_csv("terrain_class_areas.csv", header=True) # ## Summary # # In this tutorial we introduced the first steps of using geopandas. More specifically you should know how to: # # 1. Read data from Shapefile using geopandas # # 2. Access geometry information in a geodataframe # # 4. Write GeoDataFrame data from Shapefile using geopandas # # 5. Automate a task to save specific rows from data into Shapefile based on specific key using `groupby()` -function # # 6. Extra: saving attribute information to a csv file. # # #
source/notebooks/L2/geopandas-basics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: feml # language: python # name: feml # --- # ## Discretisation with Decision Trees # # # Discretisation with Decision Trees consists in using a decision tree to identify the optimal bins. When a decision tree makes a decision, it assigns an observation to one of n end leaves. Therefore, any decision tree will generate a discrete output, which values are the predictions at each of its n leaves. # # How to do discretisation with trees? # # - 1) Train a decision tree of limited depth (2, 3 or 4) using the variable we want to discretise and the target. # - 2) Replace the values by the output returned by the tree. # # # ### Advantages # # - The output returned by the decision tree is monotonically related to the target. # - The tree end nodes, or bins in the discretised variable show decreased entropy: that is, the observations within each bin are more similar among themselves than to those of other bins. # # ### Limitations # # - Prone over-fitting # - More importantly, some tuning of the tree parameters needed to obtain the optimal number of splits (e.g., tree depth, minimum number of samples in one partition, maximum number of partitions, and a minimum information gain). This it can be time consuming. # # ## In this demo # # We will learn how to perform discretisation with decision trees using the Titanic dataset. # ### Titanic dataset # + import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.model_selection import cross_val_score # + # load the numerical variables of the Titanic Dataset data = pd.read_csv('../titanic.csv', usecols = ['age', 'fare', 'survived']) data.head() # + # Let's separate into train and test set X_train, X_test, y_train, y_test = train_test_split( data[['age', 'fare']], data['survived'], test_size=0.3, random_state=0) X_train.shape, X_test.shape # - # The variables Age and Fare contain missing data, that I will fill by extracting a random sample of the variable. def impute_na(data, variable): df = data.copy() # random sampling df[variable+'_random'] = df[variable] # extract the random sample to fill the na random_sample = X_train[variable].dropna().sample(df[variable].isnull().sum(), random_state=0) # pandas needs to have the same index in order to merge datasets random_sample.index = df[df[variable].isnull()].index df.loc[df[variable].isnull(), variable+'_random'] = random_sample return df[variable+'_random'] # + # replace NA in both train and test sets X_train['age'] = impute_na(X_train, 'age') X_test['age'] = impute_na(X_test, 'age') X_train['fare'] = impute_na(X_train, 'fare') X_test['fare'] = impute_na(X_test, 'fare') # - # ### Age X_train.head() # + # example: build Classification tree using Age to predict Survived tree_model = DecisionTreeClassifier(max_depth=3) tree_model.fit(X_train['age'].to_frame(), y_train) X_train['Age_tree'] = tree_model.predict_proba(X_train['age'].to_frame())[:,1] X_train.head(10) # + # let's explore how many end points the tree created X_train['Age_tree'].unique() # - # A tree of depth 2, makes 2 splits, therefore generating 4 buckets, that is why we see 4 different probabilities in the output above. # + # monotonic relationship with target pd.concat([X_train, y_train], axis=1).groupby(['Age_tree'])['survived'].mean().plot() plt.title('Monotonic relationship between discretised Age and target') plt.ylabel('Survived') # + # number of passengers per probabilistic bucket / bin X_train.groupby(['Age_tree'])['age'].count().plot.bar() # + # median age within each bucket originated by the tree X_train.groupby(['Age_tree'])['age'].median().plot.bar() # + # let's see the Age limits buckets generated by the tree # by capturing the minimum and maximum age per each probability bucket, # we get an idea of the bucket cut-offs pd.concat( [X_train.groupby(['Age_tree'])['age'].min(), X_train.groupby(['Age_tree'])['age'].max()], axis=1) # - # Thus, the decision tree generated the buckets: 65-74, 9-44, 45-64 and 0.7-8 and 0-16-0.16, with probabilities of survival of .0, .36, .45, .52 and .1 respectively. # ### Tree visualisation # + # we can go ahead and visualise the tree by saving the model to a file, # and opening that file in the below indicated link with open("tree_model.txt", "w") as f: f = export_graphviz(tree_model, out_file=f) # go here to open the file: http://webgraphviz.com # + # this is what you should see if you do what is described in the previous cell # I saved the image you should retrieve in the server above into a png, and then load # it here to smooth the demo # the plot indicates the age cut-offs at each node, and also the number of samples at each node, and # the gini from IPython.display import Image from IPython.core.display import HTML PATH = "tree_visualisation.png" Image(filename = PATH , width=1000, height=1000) # - # **Let's expand the tree results to the test set, and explore the monotonic relationship** # + X_test['Age_tree'] = tree_model.predict_proba(X_test['age'].to_frame())[:,1] # monotonic relationship with target pd.concat([X_test, y_test], axis=1).groupby(['Age_tree'])['survived'].mean().plot() plt.title('Monotonic relationship between discretised Age and target') plt.ylabel('Survived') # - # We can see that the monotonic relationship is not maintained in the test set, which probably indicates that the tree we build was over-fitting to the train set. # ### Building the optimal decision tree # # There are a number of parameters that we could optimise to obtain the best bin split using decision trees. # # I will optimise the tree depth for this demonstration. But remember that we could also optimise the remaining parameters of the decision tree. # # Visit [sklearn website](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier) to see which other parameters can be optimised. # + # Build trees of different depths, and calculate the roc-auc of each tree # choose the depth that generates the best roc-auc score_ls = [] # here we store the roc auc score_std_ls = [] # here we store the standard deviation of the roc_auc for tree_depth in [1, 2, 3, 4]: # call the model tree_model = DecisionTreeClassifier(max_depth=tree_depth) # train the model using 3 fold cross validation scores = cross_val_score( tree_model, X_train['age'].to_frame(), y_train, cv=3, scoring='roc_auc') # save the parameters score_ls.append(np.mean(scores)) score_std_ls.append(np.std(scores)) # capture the parameters in a dataframe temp = pd.concat([pd.Series([1, 2, 3, 4]), pd.Series( score_ls), pd.Series(score_std_ls)], axis=1) temp.columns = ['depth', 'roc_auc_mean', 'roc_auc_std'] temp # - # We obtain the best roc-auc using depths of 2 (same value as depth 4 but smaller std). I will select depth of 2 to proceed. # ### Transform the feature using tree # + tree_model = DecisionTreeClassifier(max_depth=2) tree_model.fit(X_train['age'].to_frame(), y_train) X_train['Age_tree'] = tree_model.predict_proba(X_train['age'].to_frame())[:, 1] X_test['Age_tree'] = tree_model.predict_proba(X_test['age'].to_frame())[:, 1] # + # monotonic relationship with target in train set pd.concat([X_train, y_train], axis=1).groupby(['Age_tree'])['survived'].mean().plot() plt.title('Monotonic relationship between discretised Age and target') plt.ylabel('Survived') # + # and in the test set X_test['Age_tree'] = tree_model.predict_proba(X_test['age'].to_frame())[:,1] # monotonic relationship with target pd.concat([X_test, y_test], axis=1).groupby(['Age_tree'])['survived'].mean().plot() plt.title('Monotonic relationship between discretised Age and target') plt.ylabel('Survived') # - # Now the monotonic relationship is not totally maintained in the test. Probably because there are few samples in the upper buckets: # + # median age within each bucket originated by the tree X_test.groupby(['Age_tree'])['age'].count().plot.bar() # - # We could try and optimise the decision tree further to see if we can keep the monotonic relationship. Or alternatively, directly test the model performance with these engineered features and see if they add any value.
Section-08-Discretisation/08.05-Discretisation-using-Decision-Trees.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # #### Pivot # - ๋ฐ์ดํ„ฐ ํ”„๋ ˆ์ž„ ์ปฌ๋Ÿผ๋ฐ์ดํ„ฐ์—์„œ ํŠน์ • ์ปฌ๋Ÿผ์˜ ๋ฐ์ดํ„ฐ๋ฅผ index, columns, values๋ฅผ ์„ ํƒํ•˜์—ฌ ํ”„๋ ˆ์ž„์„ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. # - `df.pivot(index, columns, values)` # ํƒ€์ดํƒ€๋‹‰ ๋ฐ์ดํ„ฐ # survived : 0-no, 1-yes titanic = pd.read_csv("../train.csv") titanic.head() # ``` # ๋“ฑ๊ธ‰ 1 2 3 # ์„ฑ๋ณ„ # ----------------- # female 000 000 000 # male 000 000 000 # ``` # group by๋กœ ์ค‘๋ณต์ œ๊ฑฐ titanic_df1 = titanic.groupby(["Sex","Pclass"]).size().reset_index(name="Counts") titanic_df1 titanic_df1 = titanic_df1.pivot("Sex","Pclass","Counts") #index, column, value ์ˆœ์„œ titanic_df1 # + # ์ƒ์กด ๋ฐ์ดํ„ฐ # ์„ฑ๋ณ„์— ๋”ฐ๋ฅธ ์ƒ์กด์ž ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐ์ดํ„ฐ ํ”„๋ ˆ์ž„์„ ๋งŒ๋“œ์„ธ์š” # - # ### Pivot์€ groupby๋กœ ์ค‘๋ณต์ œ๊ฑฐํ•ด์ค˜์•ผํ•œ๋‹ค. (์ค‘์š”) # ``` # ์ƒ์กด 0 1 # ์„ฑ๋ณ„ # ----------------- # female 000 000 # male 000 000 # ``` titanic_df2 = titanic.groupby(["Sex","Survived"]).size().reset_index(name="Live_count") titanic_df2 titanic_df2 = titanic_df2.pivot("Sex","Survived","Live_count") titanic_df2 # ๊ฐ์‹ค ๋“ฑ๊ธ‰์— ๋”ฐ๋ฅธ ์ƒ์กด์ž์ˆ˜ titanic_df3 = titanic.groupby(["Pclass","Survived"]).size().reset_index(name="Live_count") titanic_df3.pivot("Pclass","Survived","Live_count") # #### pivot table # - `pivot_table(values, index, columns, aggfunc)` ์ˆœ์„œ๋กœ ์ž‘์„ฑ # - keyword parameter๋กœ ์ž…๋ ฅํ•˜๋ฉด ์‹ค์ˆ˜๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. # - fill_value : NaN ๋ฐ์ดํ„ฐ๋ฅผ ์šฐ๋ฆฌ๊ฐ€ ์„ค์ •ํ•œ ๋ฐ์ดํ„ฐ๋กœ ์น˜ํ™˜ํ•ด์ฃผ๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ์ž…๋‹ˆ๋‹ค. # - dropna : NaN ๋ฐ์ดํ„ฐ ์ปฌ๋Ÿผ์„ ๋†”๋‘˜์ง€ ์ œ๊ฑฐํ• ์ง€ ๊ฒฐ์ •ํ•  ๋•Œ ์‚ฌ์šฉ, default๋Š” True titanic["Counts"] = 1 titanic.tail() # ๊ฐ์‹ค ๋“ฑ๊ธ‰์— ๋”ฐ๋ฅธ ๋‚จ๋…€ ์Šน๊ฐ ์ˆ˜ titanic.pivot_table("Counts","Sex","Pclass", aggfunc=np.sum) # ์„ฑ๋ณ„์— ๋”ฐ๋ฅธ ์ƒ์กด์ž ์ˆ˜ titanic.pivot_table("Counts","Survived","Sex", aggfunc=np.sum) # titanic.pivot_table("Counts","Sex", "Survived", aggfunc=np.sum) # ๊ฐ์‹ค ๋“ฑ๊ธ‰์— ๋”ฐ๋ฅธ ์ƒ์กด์ž ์ˆ˜ titanic.pivot_table("Counts","Pclass","Survived", aggfunc=np.sum) titanic.pivot_table("Counts",["Sex","Pclass"], "Survived", aggfunc=np.sum) # total์„ ๋„ฃ์–ด๋ณด์ž! df = titanic.pivot_table("Counts",["Survived"],["Sex"], aggfunc=np.sum) df # column total df["Total"] = df["female"] + df["male"] df # row total df.loc["total"] = df.loc[0] + df.loc[1] df # ์‚ญ์ œ : axis=0 ์ด๋ฉด row์‚ญ์ œ df.drop("total", inplace=True) df # ์‚ญ์ œ : axis=1 ์ด๋ฉด column์‚ญ์ œ df.drop("Total", axis=1, inplace=True) df # fill_value df = titanic.pivot_table("Counts","Survived",["Parch","Pclass"], \ aggfunc=np.sum, fill_value=0) df # dropna df = titanic.pivot_table("Counts","Survived",["Parch","Pclass"], \ aggfunc=np.sum, dropna=False, fill_value=0) df
python/02_numpy_&_pandas/12_Pandas_Pivot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.5 64-bit # name: python3 # --- # + import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters from IPython.display import HTML, display import json from collections import Counter import pandas as pd import numpy as np from utilities import * register_matplotlib_converters() pd.set_option('display.float_format', '{:.0f}'.format) pd.set_option('display.max_colwidth', 100) # %matplotlib inline # + df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_rate.csv', parse_dates=['date']) def calculate_rate(df, value_col, population_col, rate_per=1000): num_per_thousand = (df[value_col]/df[population_col])*rate_per return num_per_thousand df['rate'] = calculate_rate(df, 'doac', 'population') codelist = pd.read_csv('../codelists/opensafely-mechanical-or-artificial-valves.csv') # - # ## DOAC Use in Patients with Mechanical Heart Valves # # ### Total Number # + tags=["outputPrepend"] def redact_small_numbers(df, n, numerator, denominator, rate_column): """ Takes counts df as input and suppresses low numbers. Sequentially redacts low numbers from numerator and denominator until count of redcted values >=n. Rates corresponding to redacted values are also redacted. df: input df n: threshold for low number suppression numerator: numerator column to be redacted denominator: denominator column to be redacted """ def suppress_column(column): suppressed_count = column[column<=n].sum() #if 0 dont need to suppress anything if suppressed_count == 0: pass else: column[column<=n] = np.nan while suppressed_count <=n: suppressed_count += column.min() column.iloc[column.idxmin()] = np.nan return column for column in [numerator, denominator]: df[column] = suppress_column(df[column]) df.loc[(df[numerator].isna())| (df[denominator].isna()), rate_column] = np.nan return df population = df.groupby(by='date')[['population']].sum().reset_index() events = df.groupby(by='date')[['doac']].sum().reset_index() total_df = df.groupby(by='date')[['rate']].mean().reset_index() total_df = total_df.merge(events, on='date').merge(population, on='date') redacted_dfs = [] for date in total_df['date'].unique(): sub_df = total_df.loc[total_df['date']==date, :] sub_df = redact_small_numbers(sub_df, 5, 'doac', 'population', 'rate') redacted_dfs.append(sub_df) total_df = pd.concat(redacted_dfs, axis=0) total_df.to_csv('../output/doac_rate_total.csv') # total_df = redact_small_numbers(total_df, 10, 'doac', 'population', 'rate') def plot_measures(df, title,column_to_plot, filename,category=False, y_label='Rate per 1000', interactive=True): if category: for unique_category in df[category].unique(): df_subset = df[df[category] == unique_category] plt.plot(df_subset['date'], df_subset[column_to_plot], marker='o') else: plt.plot(df['date'], df[column_to_plot]) plt.ylabel(y_label) plt.xlabel('Date') plt.ylim(bottom=0, top=df[column_to_plot].max() + df[column_to_plot].max()* 0.1) plt.xticks(rotation='vertical') plt.title(title) if category: plt.legend(df[category].unique(), bbox_to_anchor=( 1.04, 1), loc="upper left") else: pass plt.savefig(f'../output/measure_{filename}.jpeg') plt.show() plt.clf() # - plot_measures(total_df, title='DOAC prescribing in patients with a mechanical valve', column_to_plot='doac', category=False, y_label='Total number', interactive=False, filename="total") plot_measures(total_df, title='DOAC prescribing rate per 1000 patients with a mechanical valve', column_to_plot='rate', category=False, y_label='Rate per 1000', interactive=False, filename="total_rate") # ### Mechanical Valve Type # # Mechanical valve type of those with mechanical valve currently prescribed a DOAC def group_low_values_mv(df, value_col, population_col, term_col): suppressed_count = df.loc[df[value_col]<=5, value_col].sum() population_suppressed_count = df.loc[df[value_col]<=5, population_col].sum() if suppressed_count == 0: pass else: df.loc[df[value_col] <=5, value_col] = np.nan while suppressed_count <=5: suppressed_count += df[value_col].min() df.loc[df[value_col].idxmin(), value_col] = np.nan population_suppressed_count += df.loc[df[value_col].idxmin(), population_col] df = df[df[value_col].notnull()] other_row = {'mechanical_valve_code':'Other', 'doac_3_months':suppressed_count, 'population':population_suppressed_count, 'term':'-'} df = df.append(other_row, ignore_index=True) return df # + valve_type_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_valve_code_rate.csv', parse_dates=['date']) valve_type_df_now = valve_type_df[valve_type_df['date']== '2021-12-01'] valve_type_df_now = valve_type_df_now.drop('value', axis=1) valve_type_df_now = valve_type_df_now.merge(codelist, left_on='mechanical_valve_code', right_on='code', how='left') valve_type_df_now = valve_type_df_now.drop(columns=['code', 'date']) valve_type_df_now = group_low_values_mv(valve_type_df_now, 'doac_3_months', 'population', 'term') valve_type_df_now.to_csv('../output/current_doac_valve_type.csv') # - valve_type_df_now # ### Demographic breakdown # #### Sex def group_low_values_dems(df, value_col, population_col, demographic): suppressed_count = df.loc[df[value_col]<=5, value_col].sum() population_suppressed_count = df.loc[df[value_col]<=5, population_col].sum() if suppressed_count == 0: pass else: df.loc[df[value_col] <=5, value_col] = np.nan if suppressed_count <=5: suppressed_count += df[value_col].min() population_suppressed_count += df.loc[df[value_col].idxmin(), population_col] df.loc[df[value_col].idxmin(), value_col] = np.nan df = df[df[value_col].notnull()] other_row = {demographic:'Other', 'doac_3_months':suppressed_count, 'population':population_suppressed_count,} df = df.append(other_row, ignore_index=True) return df # + sex_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_sex_rate.csv', parse_dates=['date']) sex_df_now = sex_df[sex_df['date'] == '2021-12-01'] sex_df_now = sex_df_now.drop(['value', 'date'], axis=1) sex_df_now = group_low_values_dems(sex_df_now, 'doac_3_months', 'population', 'sex') sex_df_now.to_csv('../output/current_doac_sex.csv') sex_df_now # - # #### Ethnicity # + ethnicity_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_ethnicity_rate.csv', parse_dates=['date']) ethnicity_df_now = ethnicity_df[ethnicity_df['date'] == '2021-12-01'] ethnicity_df_now = ethnicity_df_now.drop(['value', 'date'], axis=1) ethnicity_df_now = group_low_values_dems(ethnicity_df_now, 'doac_3_months', 'population', 'eth2001') ethnicity_df_now.to_csv('../output/current_doac_ethnicity.csv') ethnicity_df_now # - # #### Age Band # + age_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_age_rate.csv', parse_dates=['date']) age_df_now = age_df[age_df['date'] == '2021-12-01'] age_df_now = age_df_now.drop(['value', 'date'], axis=1) age_df_now = group_low_values_dems(age_df_now, 'doac_3_months', 'population', 'age_band') age_df_now.to_csv('../output/current_doac_age.csv') age_df_now # - # ## AF af_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_af_rate.csv', parse_dates=['date']) af_df_now = af_df[af_df['date'] == '2021-12-01'] af_df_now = af_df_now.drop(['value', 'date'], axis=1) af_df_now = group_low_values_dems(af_df_now, 'doac_3_months', 'population', 'atrial_fib') af_df_now.to_csv('../output/current_doac_af.csv') af_df_now # ## IMD imd_df = pd.read_csv('../output/measure_doac_rx_mechanical_valve_3_month_imd_rate.csv', parse_dates=['date']) imd_df_now = imd_df[imd_df['date'] == '2021-12-01'] imd_df_now = imd_df_now.drop(['value', 'date'], axis=1) imd_df_now = group_low_values_dems(imd_df_now, 'doac_3_months', 'population', 'imd') imd_df_now.to_csv('../output/current_doac_imd.csv') imd_df_now # ## Self Monitoring # + self_monitoring_df = pd.read_csv('../output/measure_monitoring_mechanical_valve_rate.csv') blood_monitoring_df = pd.read_csv('../output/measure_monitoring_blood_testing_mechanical_valve_rate.csv') self_monitoring_df.loc[self_monitoring_df["date"]=="2021-12-01",:].to_csv('../output/self_monitoring_current.csv') blood_monitoring_df.loc[blood_monitoring_df["date"]=="2021-12-01",:].to_csv('../output/blood_monitoring_current.csv')
analysis/notebook.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as pathces from PIL import Image # %matplotlib inline # + Sample_raw_x = 32 Sample_raw_y = 32 rpn_stride = 8 Feature_size_X = Sample_raw_x/rpn_stride Feature_size_Y = Sample_raw_y/rpn_stride scales = [1,2,4] ratios =[0.5,1,2] # - fx = np.arange(Feature_size_X) fy = np.arange(Feature_size_Y) FX,FY = np.meshgrid(fx,fy) FX.flatten() FY.flatten() scales,ratios = np.meshgrid(scales,ratios)
05_objectDetection/Faster_rcnn_resnet/.ipynb_checkpoints/meshgrid-checkpoint.ipynb