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 # --- # + id="rEBLmBmC1TaC" colab={"base_uri": "https://localhost:8080/", "height": 989} executionInfo={"status": "ok", "timestamp": 1596790208049, "user_tz": -420, "elapsed": 4383, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="dcb4eda2-c33e-4e60-8e95-de6415521f24" # !pip install qiskit # + id="UzQq8US51GkR" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596790218072, "user_tz": -420, "elapsed": 7571, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="bbf40a76-e96d-4737-e17d-f110751b869a" from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.circuit.library import EfficientSU2 from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import CompleteMeasFitter from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise IBMQ.save_account('<KEY>') provider = IBMQ.load_account() import numpy as np import matplotlib.pyplot as plt from functools import partial import pandas as pd import json from matplotlib import pyplot as plt from google.colab import drive drive.mount('/content/drive') # + id="h_WG99PHiTwv" def save_result(file_name, result): dir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/' with open(dir + file_name, 'w') as f: f.write(json.dumps(result)) def load_result(file_name): # Now read the file back into a Python list object dir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/' with open(dir + file_name, 'r') as f: a = json.loads(f.read()) return a # + [markdown] id="2UmAqLYv1Gkc" # # Qiskit Summer School Final Project: VQE # # #### For this optional final challenge, you will be designing your own implementation of a variational quantum eigensolver (VQE) algorithm that simulates the ground state energy of the Lithium Hydride (LiH) molecule. Through out this challenge, you will be able to make choices on how you want to compose your simulation and what is the final deliverable that you want to showcase to your classmates and friends. # + [markdown] id="WuJOce1A1Gke" # # Defining your molecule: # In this challenge we will focus on LiH using the sto3g basis with the PySCF driver, which can be described in Qiskit as follows, where 'inter_dist' is the interatomic distance. # + id="KvJoA8Ua1Gki" inter_dist = 1.6 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # + [markdown] id="4Q13IH1z1Gko" # We also setup the molecular orbitals to be considered and can reduce the problem size when we map to the qubit Hamiltonian so the amount of time required for the simulations are reasonable for a laptop computer. # + id="EFjO0-OT1Gkr" # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order # + [markdown] id="Jhhzl1oe1Gkx" # #### Once you have computed the qubit operations for LiH, you can use the following function to classical solve for the exact solution. This is used just to compare how well your VQE approximation is performing. # + id="An8fcs1H1Gkz" #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref # + [markdown] id="dZYT8uOx1Gk4" # Here we ask you to use the `statevector_simulator` as the simulation backend for your VQE algorithm. # + id="yuldfa8F1Gk5" backend = BasicAer.get_backend('statevector_simulator') # + [markdown] id="ehFvMXBf1GlB" # ### Now you can start choosing the components that make up your VQE algorithm! # # #### 1. Optimizers # The most commonly used optimizers are `COBYLA`, `L_BFGS_B`, `SLSQP` and `SPSA`. # # #### 2. Qubit mapping # There are several different mappings for your qubit Hamiltonian, `parity`, `bravyi_kitaev`, `jordan_wigner`, which in some cases can allow you to further reduce the problem size. # # #### 3. Initial state # There are different initial state that you can choose to start your simulation. Typically people choose from the zero state # `init_state = Zero(qubitOp.num_qubits)` # and the UCCSD initial state # `HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction)` # # #### 4. Parameterized circuit # There are different choices you can make on the form of variational forms of your parameterized circuit. # # `UCCSD_var_form = UCCSD(num_qubits, depth=depth, num_orbitals=num_spin_orbitals, num_particles=num_particles)` # # `RY_var_form = RY(num_qubits, depth=depth)` # # `RYRZ_var_form = RYRZ(num_qubits, depth=depth)` # # `swaprz_var_form = SwapRZ(num_qubits, depth=depth)` # # #### 5. Simulation backend # There are different simulation backends that you can use to perform your simulation # # `backend = BasicAer.get_backend('statevector_simulator')` # # `backend=Aer.get_backend('qasm_simulator')` # + [markdown] id="UCNNmdpZ1GlC" # ### Compare the convergence of different choices for building your VQE algorithm # # Among the above choices, which combination do you think would out perform others and give you the lowest estimation of LiH ground state energy with the quickest convergence? Compare the results of different combinations against each other and against the classically computed exact solution at a fixed interatomic distance, for example `inter_dist=1.6`. # # To access the intermediate data during the optimization, you would need to utilize the `callback` option in the VQE function: # # `def store_intermediate_result(eval_count, parameters, mean, std): # counts.append(eval_count) # values.append(mean) # params.append(parameters) # deviation.append(std)` # # `algo = VQE(qubitOp, var_form, optimizer, callback=store_intermediate_result)` # # `algo_result = algo.run(quantum_instance)` # # An example of comparing the performance of different optimizers while using the RY variational ansatz could like the following: # ![RY_error.png](attachment:RY_error.png) # ![RY_convergence.png](attachment:RY_convergence.png) # + [markdown] id="RzMK8AZ21GlD" # ### Compute the ground state energy of LiH at various different interatomic distances # By changing the parameter `inter_dist`, you can use your VQE algorithm to calculate the ground state energy of LiH at various interatomic distances, and potentially produce a plot as you are seeing here. Note that the VQE results are very close to the exact results, and so the exact energy curve is hidden by the VQE curve. # <img src="attachment:VQE_dist.png" width="600"> # + [markdown] id="NYDRYCaR1GlE" # ### How does your VQE algorithm perform in the presence of noise? # Trying importing the noise model and qubit coupling map of a real IBM quantum device into your simulation. You can use the imported noise model in your simulation by passing it into your quantum instance. You can also try enabling error mitigation in order to lower the effect of noise on your simulation results. # + id="bUUaDZlW1GlF" colab={"base_uri": "https://localhost:8080/", "height": 75} executionInfo={"status": "ok", "timestamp": 1596790221889, "user_tz": -420, "elapsed": 1216, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="bbc3ab05-dc60-4cf9-d498-80f2e2bafb5c" #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # + [markdown] id="FHlGayJ71GlJ" # An example of comparing the energy convergence of using SPSA and COBYLA with the ibmq_essex noise model could look like the following # ![noise.png](attachment:noise.png) # + [markdown] id="LBAeKGkz1GlK" # ### Now given the choices you have made above, try writing your own VQE algorithm in Qiskit. You can find an example of using Qiskit to simuate molecules with VQE [here](https://qiskit.org/textbook/ch-applications/vqe-molecules.html). # + id="50jm1wzs1GlL" # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] #print('Reference value: {}'.format(ref)) return ref # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 #print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) #print("# of electrons: {}".format(num_particles)) #print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] # Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type=map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp qubitOp.chop(10**-10) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, energy_shift, nuclear_repulsion_energy def test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type): qubitOp, num_spin_orbitals, num_particles, qubit_reduction = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance) print("Orbitals: ", num_spin_orbitals) print("Particles: ", num_particles) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state if init_type == 'HF': init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True) elif init_type == 'Zero': init_state = Zero(qubitOp.num_qubits) elif init_type == 'None': init_state = None # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. if param_type == 'UCCSD': var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, initial_state=init_state, two_qubit_reduction=True) elif param_type == 'RY': var_form = RY(num_qubits=qubitOp.num_qubits, entanglement="linear", initial_state=init_state, depth=1) elif param_type == 'RYRZ': var_form = RYRZ(num_qubits=qubitOp.num_qubits, entanglement="linear", initial_state=init_state) elif param_type == 'SwapRZ': var_form = SwapRZ(num_qubits=qubitOp.num_qubits, entanglement="linear", initial_state=init_state) elif param_type == 'ESU2': var_form = EfficientSU2(qubitOp.num_qubits, entanglement="linear", initial_state=init_state) # Choose where to run/simulate our circuit if backend_type == 'qasm': backend = Aer.get_backend('qasm_simulator') elif backend_type == 'statevector': backend = BasicAer.get_backend('statevector_simulator') # Choose whether to use noise or not if use_noise == False: quantum_instance = backend elif use_noise == True: backend = Aer.get_backend('qasm_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates quantum_instance = QuantumInstance(backend=backend, shots=1000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) # measurement_error_mitigation_cls=CompleteMeasFitter # cals_matrix_refresh_period=30 # Choose the classical optimizer if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=100) elif optimizer_type == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun=100, maxiter=1500) elif optimizer_type == 'SLSQP': optimizer = SLSQP(maxiter=100) elif optimizer_type == 'SPSA': optimizer = SPSA(max_trials=100) # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer) # Now compare the results of different compositions of your VQE algorithm! ret = vqe.run(quantum_instance) vqe_result = np.real(ret['eigenvalue']) return abs(vqe_result - ref) #print("VQE Result:", vqe_result) mapping_list = ['parity', 'bravyi_kitaev', 'jordan_wigner'] init_state_list = ['HF', 'Zero'] backend_list = ['statevector', 'qasm'] optimizer_list = ['COBYLA', 'L_BFGS_B', 'SLSQP', 'SPSA'] param_list = ['UCCSD', 'RY', 'RYRZ', 'SwapRZ'] # + id="O2uaUflNh5vk" def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) #params.append(parameters) deviation.append(std) # + id="brc82WHM59lj" # + id="gSlfU2_eoKJU" colab={"base_uri": "https://localhost:8080/", "height": 55} executionInfo={"status": "ok", "timestamp": 1596798918521, "user_tz": -420, "elapsed": 905, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="d0c541ec-0adf-4234-fc17-99096158f9e0" a = np.array([[0, 0, 0], [0,0,0]]) b = [1, 2, 3] a[0,:] = np.array(b) a # + id="imtwBFJZi_LV" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596800384769, "user_tz": -420, "elapsed": 791864, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="3774e323-eb4d-4e21-b3b2-56f5a738a7f3" def convergence_test(mapping_type, optimizer_type, inter_distance): qubitOp, num_spin_orbitals, num_particles, qubit_reduction = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance) print("Orbitals: ", num_spin_orbitals) print("Particles: ", num_particles) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = RY(num_qubits=qubitOp.num_qubits, entanglement="linear", initial_state=init_state) backend = Aer.get_backend('qasm_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates quantum_instance = QuantumInstance(backend=backend, shots=1000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) # Choose the classical optimizer if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=100) elif optimizer_type == 'SPSA': optimizer = SPSA(max_trials=100) # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer, callback=store_intermediate_result) # Now compare the results of different compositions of your VQE algorithm! ret = vqe.run(quantum_instance) vqe_result = np.real(ret['eigenvalue']) err = abs(vqe_result - ref) #print("Abs error: ", err) mapping_type = 'parity' optimizer_type = 'COBYLA' #inter_distance = 1.6 dist_list = [0.25, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] values_all = np.zeros((len(dist_list), 100)) counts_all = np.zeros((len(dist_list), 100)) deviation_all = np.zeros((len(dist_list), 100)) for i in range (len(dist_list)): counts = [] values = [] deviation = [] convergence_test(mapping_type, optimizer_type, dist_list[i]) counts_all[i,:] = np.array(counts) values_all[i,:] = np.array(values) deviation_all[i,:] = np.array(deviation) # + id="MndTNWPoj4jG" cobyla_counts = counts cobyla_values = values cobyla_deviation = deviation cobyla_params = params # + id="R5LiqfJUl8Hg" spsa_counts = counts spsa_values = values spsa_deviation = deviation spsa_params = params # + id="dwrzYYkMsSEG" colab={"base_uri": "https://localhost:8080/", "height": 532} executionInfo={"status": "ok", "timestamp": 1596800810718, "user_tz": -420, "elapsed": 1728, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="d6a4ee6f-c191-4186-c202-3b91872e0117" color_list = ['red', 'blue', 'green', 'purple', 'black', 'yellow', 'brown'] for i in range (len(dist_list)): plt.errorbar(counts_all[i,:], values_all[i,:], deviation_all[i,:], linestyle='--', marker='o', color=color_list[i], label='distance = ' + str(dist_list[i])) plt.title('COBYLA Optimizer at Several Distance (convergence is achieved after 40-50 iterations for all distances)') plt.xlabel('Iterations') plt.ylabel('Evaluated Mean') plt.legend() # + id="XgtZ7PgVjIRh" colab={"base_uri": "https://localhost:8080/", "height": 532} executionInfo={"status": "ok", "timestamp": 1596800386608, "user_tz": -420, "elapsed": 1822, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="597fe67a-645d-49ff-cc6a-acda18aae198" fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 20 fig_size[1] = 8 plt.rcParams["figure.figsize"] = fig_size plt.errorbar(cobyla_counts, cobyla_values, cobyla_deviation, linestyle='None', marker='o', color='red', label='Optimizer: COBYLA (converge faster)') plt.errorbar(spsa_counts, spsa_values, spsa_deviation, linestyle='None', marker='o', color='blue', label='Optimizer: SPSA') plt.title('Optimizer Convergence at distance = 1.6') plt.xlabel('Iterations') plt.ylabel('Evaluated Mean') plt.legend() # + id="NnwisU0Wv5Jd" def depth_test(mapping_type, inter_distance, num_depth): qubitOp, num_spin_orbitals, num_particles, qubit_reduction, eshift, erepulsion = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance) print("Orbitals: ", num_spin_orbitals) print("Particles: ", num_particles) # Classically solve for the exact solution and use that as your reference value #ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = RY(num_qubits=qubitOp.num_qubits, entanglement="linear", initial_state=init_state, depth=num_depth) backend = Aer.get_backend('qasm_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates quantum_instance = QuantumInstance(backend=backend, shots=1000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) # Choose the classical optimizer optimizer = COBYLA(maxiter=50) # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer) # Now compare the results of different compositions of your VQE algorithm! ret = vqe.run(quantum_instance) vqe_result = np.real(ret['eigenvalue']) #err = abs(vqe_result - ref) return (vqe_result+eshift+erepulsion) #print("Abs error: ", err) # + id="jEhQkG8UHspC" # + id="29eSzjdBykm8" mapping_type = 'parity' depth_list = [1, 3, 5, 7] dist_list = np.linspace(0.5, 3.0, 21) ref_all = np.zeros((len(depth_list), len(dist_list))) vqe_all = np.zeros((len(depth_list), len(dist_list))) # + id="HJQSZfX6yXZG" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596807579148, "user_tz": -420, "elapsed": 1310950, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="e5ea777a-3842-445a-da3d-9c0766864689" num_depth = 7 row = 3 for i in range (len(dist_list)): result = depth_test(mapping_type, dist_list[i], num_depth) #ref_all[row, i] = ref vqe_all[row, i] = result np.savetxt('/content/drive/My Drive/Projects/Qiskit Global Summer School/vqe_result.txt', vqe_all, delimiter=',') #np.savetxt('/content/drive/My Drive/Projects/Qiskit Global Summer School/ref_result.txt', ref_all, delimiter=',') print("Dist: " + str(dist_list[i])) # + id="GvhyaDSq0lYY" row = 0 for i in range (len(dist_list)): qubitOp, num_spin_orbitals, num_particles, qubit_reduction, eshift, erepulsion = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=dist_list[i]) ref_all[row, i] += (eshift + erepulsion) vqe_all[row, i] += (eshift + erepulsion) #print(eshift, erepulsion) # + id="WD8uMVb37prj" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596808022027, "user_tz": -420, "elapsed": 901, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="b0872456-6f96-4f2d-b934-eeb0a4914d23" # exact ground state energy ref_all[0, 8] abs(mitigated[8]-ref_all[0,8]) # + id="hf-kmBbMLHsi" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596808005813, "user_tz": -420, "elapsed": 864, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="4d2d0508-5cf4-4066-d8ba-1a8bb431c858" abs(mitigated[8]-ref_all[0,8]) # + id="g1g-ELV3LNJE" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596808156942, "user_tz": -420, "elapsed": 837, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="a93cb8bc-1cb3-4d17-b0a2-b06c08cbfa3c" abs(mitigated[8]-ref_all[0,8]) # + id="8KoXKenqGZve" import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt from scipy import stats import pandas as pd # + id="OLFubHupGafb" def f(x, a, b): return a*x+b # + id="2viMYSBfHf7U" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596807745931, "user_tz": -420, "elapsed": 546, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="7270c577-9e13-4bc6-a5e9-beee95b7a344" depth_list # + id="lL-HF0jFC5Cv" colab={"base_uri": "https://localhost:8080/", "height": 56} executionInfo={"status": "ok", "timestamp": 1596808151393, "user_tz": -420, "elapsed": 811, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="7a97bd2e-5325-4858-bf5c-316f74f22f84" mitigated = [] x = np.array([1,3,5,7]) for i in range(len(dist_list)): y = vqe_all[:, i] popt, pcov = curve_fit(f, x, y) a = popt[0] b = popt[1] mitigated += [0*a + b] print(mitigated) # + id="MHCUwbnnDHhk" # + id="lpL_M3cO1Ynh" colab={"base_uri": "https://localhost:8080/", "height": 533} executionInfo={"status": "ok", "timestamp": 1596808213187, "user_tz": -420, "elapsed": 1315, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="67c32c60-5394-431b-c843-056ef5ebeed2" plt.plot(dist_list, ref_all[0,:], color='blue', linestyle='-', label='Exact') plt.plot(dist_list, vqe_all[0,:], color='yellow', linestyle='-', label='VQE, RY depth = 1') plt.plot(dist_list, vqe_all[1,:], color='cyan', linestyle='-', label='VQE, RY depth = 3') plt.plot(dist_list, vqe_all[2,:], color='green', linestyle='-', label='VQE, RY depth = 5') plt.plot(dist_list, vqe_all[3,:], color='purple', linestyle='-', label='VQE, RY depth = 7') plt.plot(dist_list, mitigated, color='red', linestyle='-', label='VQE + error mitigation by simple extrapolation') plt.title('LiH Ground State Energy Simulation') plt.xlabel('Interatomic Distance (ร…)') plt.ylabel('Energy (Hartree)') plt.legend() # + id="GyFFr2zh-qUU" # + id="TkPqTjf1L5yW" # + id="Sq3PL-0hwzpf" colab={"base_uri": "https://localhost:8080/", "height": 74} executionInfo={"status": "ok", "timestamp": 1596801425621, "user_tz": -420, "elapsed": 1218, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="4d951fd4-9280-4e2a-8f86-b677f5a15b11" np.linspace(0.5, 3.0, 21) # + id="0FLznAUfhgNE" colab={"base_uri": "https://localhost:8080/", "height": 399} executionInfo={"status": "ok", "timestamp": 1596796788447, "user_tz": -420, "elapsed": 238851, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="1a0ff466-9cbb-42a8-fd18-4452211052ed" mapping_list = ['parity'] backend_list = ['qasm'] init_state_list = ['HF'] optimizer_list = ['COBYLA', 'SPSA'] param_list = ['RY'] score_noisefree = np.zeros((len(mapping_list)*len(init_state_list)*len(backend_list)*len(optimizer_list)*len(param_list), 6)).tolist() inter_distance = 1.6 use_noise=True count = 0 for i in range (len(backend_list)): for j in range (len(mapping_list)): for k in range (len(init_state_list)): for l in range (len(optimizer_list)): for m in range (len(param_list)): score_noisefree[count][0] = backend_list[i] score_noisefree[count][1] = mapping_list[j] score_noisefree[count][2] = init_state_list[k] score_noisefree[count][3] = optimizer_list[l] score_noisefree[count][4] = param_list[m] backend_type = backend_list[i] mapping_type = mapping_list[j] init_type = init_state_list[k] optimizer_type = optimizer_list[l] param_type = param_list[m] err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type) score_noisefree[count][5] = err count += 1 save_result('final_result_noisy3.txt', score_noisefree) print("Run " + str(count) + ": absolute error = ", err) # + id="nGtUVGTNjEve" # + id="d_kYXB4QfD8F" 0.7650321937608426 0.8486693939154499 # + id="klrRdwh5cop8" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596796418293, "user_tz": -420, "elapsed": 864, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="b55d1c72-273d-4aaa-fab4-6e0150864da9" (0.28978775069959495+0.18632168429111617)/2 # + id="htXhoarOgXm4" colab={"base_uri": "https://localhost:8080/", "height": 55} executionInfo={"status": "ok", "timestamp": 1596796799043, "user_tz": -420, "elapsed": 757, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="01d71a1a-354c-40c3-c17b-329b913cac66" score_noisefree # + id="r34fix9Uefxe" colab={"base_uri": "https://localhost:8080/", "height": 93} executionInfo={"status": "ok", "timestamp": 1596796357587, "user_tz": -420, "elapsed": 832, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="f98bcb27-9e8b-46e0-c2c1-a77956de55a8" score_noisefree # + id="B03Mj3lVZ6zf" colab={"base_uri": "https://localhost:8080/", "height": 93} executionInfo={"status": "ok", "timestamp": 1596795761180, "user_tz": -420, "elapsed": 954, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="1158c6de-2c88-47ef-bc8d-9af20f6b731c" score_noisefree # + id="OVxhoNnwQw3d" colab={"base_uri": "https://localhost:8080/", "height": 245} executionInfo={"status": "ok", "timestamp": 1596794591185, "user_tz": -420, "elapsed": 976, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="f5e8c03d-4eef-4d9c-83f8-8589473701f6" score_noisefree # + id="tmOP8uIAVV1e" ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.2875017011823] ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.3021503647689735] ['qasm', 'parity', 'None', 'COBYLA', 'RY', 0.29940355507681604] ['qasm', 'parity', 'None', 'SPSA', 'RY', 0.36287466634206145] ['qasm', 'parity', 'Zero', 'SPSA', 'ESU2', 0.3455366683455622] # + id="Nmp_XgPUKnO8" colab={"base_uri": "https://localhost:8080/", "height": 208} executionInfo={"status": "ok", "timestamp": 1596791590082, "user_tz": -420, "elapsed": 182431, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="a7cc0183-3cfe-4d43-d115-1b3c82b0f524" backend_type = 'qasm' mapping_type = 'parity' optimizer_type = 'SPSA' init_type = 'none' param_type = 'RY' err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type) # + id="AJk8oQycM-Ct" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596791712375, "user_tz": -420, "elapsed": 633, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="bb5f9156-f314-4d44-e58c-eede2869ca10" err # + id="yflUctyMNEwW" colab={"base_uri": "https://localhost:8080/", "height": 208} executionInfo={"status": "ok", "timestamp": 1596791834048, "user_tz": -420, "elapsed": 68409, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="265876d3-9001-40eb-c411-d92e05b4471c" backend_type = 'qasm' mapping_type = 'parity' optimizer_type = 'COBYLA' init_type = 'none' param_type = 'RY' err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type) # + id="82oyGWCHNNC-" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596791835136, "user_tz": -420, "elapsed": 1078, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="4b138e21-e055-47f4-f14a-7b24c39c77ee" err # + id="ymfkOiBlNwgt" colab={"base_uri": "https://localhost:8080/", "height": 227} executionInfo={"status": "ok", "timestamp": 1596792331249, "user_tz": -420, "elapsed": 90773, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="e45d313a-70c4-41de-85cd-991e1feffe0a" backend_type = 'qasm' mapping_type = 'parity' optimizer_type = 'COBYLA' use_noise = True init_type = 'none' param_type = 'RY' err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type) err # + id="0Bzc3DQJLHjw" none + RY Zero + ESU2 HF + RY # + id="j0glXlMHHm7a" colab={"base_uri": "https://localhost:8080/", "height": 74} executionInfo={"status": "ok", "timestamp": 1596790878724, "user_tz": -420, "elapsed": 584, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="7c9734ef-4992-417c-ca4c-5e6c90490f74" score_noisefree # + id="d7mOZPLGGd6o" colab={"base_uri": "https://localhost:8080/", "height": 55} executionInfo={"status": "ok", "timestamp": 1596790009238, "user_tz": -420, "elapsed": 741, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="914174e3-1182-4c76-fc1c-ecbc087189c5" score_noisefree # + id="G64E85R5-c_c" colab={"base_uri": "https://localhost:8080/", "height": 131} executionInfo={"status": "ok", "timestamp": 1596788652580, "user_tz": -420, "elapsed": 926, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="edd84a0d-fba6-457b-f5c5-2e183e8bd1e9" score_noisefree # + id="XQZ6S_b454Bb" colab={"base_uri": "https://localhost:8080/", "height": 55} executionInfo={"status": "ok", "timestamp": 1596789456872, "user_tz": -420, "elapsed": 801, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="57279338-e5a4-40f6-a40f-a3ee39a1ca60" score_noisefree # + id="0FFgZIC_1TDY" # + id="05oXPFL3DB9Z" # + id="0rwByHCCsJHX" 0.5244282569636363 # + id="sTaBstrAwuFa" # + id="cr15sJminkJW" # + id="90v_VwgmeaNY" # + id="Bua5wxrilXM1" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596771646477, "user_tz": -420, "elapsed": 2172269, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="83d4f92d-d3a6-482a-abc2-bafc921ac778" backend_list = ['qasm'] mapping_list = ['bravyi_kitaev', 'jordan_wigner'] init_state_list = ['HF', 'Zero'] optimizer_list = ['COBYLA', 'L_BFGS_B', 'SLSQP', 'SPSA'] param_list = ['UCCSD', 'RY', 'RYRZ', 'SwapRZ'] score_noisefree = np.zeros((len(mapping_list)*len(init_state_list)*len(backend_list)*len(optimizer_list)*len(param_list), 6)).tolist() inter_distance = 1.6 use_noise=False count = 0 for i in range (len(backend_list)): for j in range (len(mapping_list)): for k in range (len(init_state_list)): for l in range (len(optimizer_list)): for m in range (len(param_list)): score_noisefree[count][0] = backend_list[i] score_noisefree[count][1] = mapping_list[j] score_noisefree[count][2] = init_state_list[k] score_noisefree[count][3] = optimizer_list[l] score_noisefree[count][4] = param_list[m] backend_type = backend_list[i] mapping_type = mapping_list[j] init_type = init_state_list[k] optimizer_type = optimizer_list[l] param_type = param_list[m] err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type) score_noisefree[count][5] = err count += 1 save_result('result_noise-free_new.txt') print("Run " + str(count) + ": absolute error = ", err) # + id="QgBSTsCwnGXZ" a = load_result('result_noise-free.txt') # + id="LqDhMSa5DR-O" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596772880425, "user_tz": -420, "elapsed": 581, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="c45b8df6-c4b0-4118-c907-212c9f4254bb" a # + id="fYkjuTHdEgaS" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596772885750, "user_tz": -420, "elapsed": 849, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="8b376ff5-5019-4375-ed33-695ccb2f11fa" b = load_result('result_noise-free_new.txt') b # + id="rnPIjTJ4Dwmg" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1596772899584, "user_tz": -420, "elapsed": 882, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="079d12e4-23d2-42a0-a65f-cc1382e038e8" for i in range (len(a)): if a[i][0] == b[0][0] and a[i][1] == b[0][1] and a[i][2] == b[0][2] and a[i][3] == b[0][3] and a[i][4] == b[0][4]: for j in range(len(b)): a[i+j][0] = b[j][0] a[i+j][1] = b[j][1] a[i+j][2] = b[j][2] a[i+j][3] = b[j][3] a[i+j][4] = b[j][4] a[i+j][5] = b[j][5] break a # + id="E7pbLTvbFYmz" save_result('final_result_noise-free.txt', a) # + id="RTuWJ-omFtp0" final_result = pd.DataFrame(a).rename(columns={0: "backend", 1: "qubit mapping", 2: "initial state", 3: "optimizer", 4: "variational form", 5: "absolute error"}) dir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/' final_result.to_csv(dir + 'final_result_noise-free.csv') # + id="YsbYs4BtHg8-" # + id="JLoUufOyQrLr" # + id="fyVes2RvZ1PW" # + id="kx-pGcHdQffN" colab={"base_uri": "https://localhost:8080/", "height": 36} executionInfo={"status": "ok", "timestamp": 1596747883248, "user_tz": -420, "elapsed": 1258, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Ggpw7xw-lyk6u6l92QjpI7MlI7qjJuuciCpwrUd=s64", "userId": "03770692095188133952"}} outputId="2b8c0756-2ca9-4e86-ba28-38bb38f917fa" counter = 0 for i in range (len(score_noisefree)): if score_noisefree[i][0] == 'statevector' or score_noisefree[i][0] == 'qasm': counter += 1 counter # + id="YWHCJkMQC7y0" # + id="xaAdwz6WL6hM" # + id="jqAYbaZKGwlu" ref -1.0770597457346915 -1.07702902531249 -1.06453928070638 # + id="UzIYAC40HVjK" # + id="U5Byfwxc1GlQ" outputId="00d8457b-3fa1-48b2-8f0b-59fbc08dc47b" import qiskit.tools.jupyter # %qiskit_version_table # %qiskit_copyright
Qiskit Global Summer School 2020/Qiskit Summer School Final Project VQE.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 # --- # # ...in Python # ## Transforming Data in Python # by <NAME> # # These recipe examples were tested on January 24, 2022. # ## 1. JSON data to Pandas DataFrane # The [pandas library](https://pandas.pydata.org/) makes it easier to work with data in Python. There are many types of data that can be loaded into pandas. This tutorial is going to show how to parse JSON data (a common data type used for scholarly web APIs) into a pandas DataFrame. We're going to use a sample dataset from [PubChem](https://pubchemdocs.ncbi.nlm.nih.gov/pug-rest) that can be found using this [link](https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/1,2,3,4,5/property/IUPACName,MolecularFormula,MolecularWeight,InChIKey/JSON). Copy the data and save it to a json file, named `molecular_data.json`. # ### Import libraries import pandas as pd import json from pandas.io.json import json_normalize # To parse JSON data into pandas, we read the data into a Python dictionary, as shown below. # ### Read JSON data with open('molecular_data.json', 'r') as infile: data = json.loads(infile.read()) data # As you can see from the displayed data above, our dictionary contains nested dictionaries, which means that if we try to create a DataFrame, we will get a single value that consists of our nested dictionaries: # ### Create a DataFrame df = pd.DataFrame(data) df # To unpack this into a DataFrame with pandas, we first index into the DataFrame. # ### Index nested data data2 = df.iloc[0,0] data2 # ### Normalize # use json_normalize() to unpack the nested dictionaries into a flat table DataFrame mol_data = pd.json_normalize(data2) mol_data # ### Transpose # transpose the DataFrame if desired mol_data2 = mol_data.transpose() mol_data2
docs/_sources/content/tutorials/python/python_transforming.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 # --- # * load book data # * time same col, two different aggs # * time same col, aggs as a single operation # * time same col, aggs via namedagg # # * numba on wap? # + import os import pandas as pd import matplotlib.pyplot as plt #from pprint import pprint import numpy as np import random #import memory_profiler #import altair as alt #from tqdm import tqdm import datetime #import ipython_memory_usage # #%ipython_memory_usage_start from utility import ROOT, TEST_CSV, TRAIN_CSV #df_train_all = pd.read_csv(TRAIN_CSV) #df_train_all = df_train_all.set_index(['stock_id', 'time_id']) # - filename = 'book_train.parquet' stock_id = 1 assert isinstance(stock_id, int) df_book_train_stock_X = pd.read_parquet( os.path.join(ROOT, f"{filename}/stock_id={stock_id}") ) df_book_train_stock_X["stock_id"] = stock_id df_book_train_stock_X = df_book_train_stock_X.set_index(['stock_id', 'time_id']) display(df_book_train_stock_X.shape) df_book_train_stock_X.reset_index().time_id.unique() df_book_train_stock_X.reset_index().info() # %timeit df_book_train_stock_X.groupby('time_id').mean() # %timeit df_book_train_stock_X.groupby('time_id').agg('mean') # %timeit df_book_train_stock_X.groupby('time_id').agg('median') # %timeit df_book_train_stock_X.groupby('time_id').agg('max') # %timeit df_book_train_stock_X.groupby('time_id').agg('count') # %timeit df_book_train_stock_X.groupby('time_id').agg('size') # %%timeit res1 = df_book_train_stock_X.groupby('time_id').agg('mean') res2 = df_book_train_stock_X.groupby('time_id').agg('median') pd.concat((res1, res2), axis=1) # %timeit df_book_train_stock_X.groupby('time_id').agg(['mean', 'median']) # %timeit df_book_train_stock_X.groupby('time_id').agg(['mean', 'median']) df_book_train_stock_X_noidx = df_book_train_stock_X.reset_index() df_book_train_stock_X_noidx.head(2) # %timeit df_book_train_stock_X_noidx.groupby('time_id').mean() df_book_train_stock_X_noidx['time_id_cat'] = df_book_train_stock_X_noidx['time_id'].astype('category') df_book_train_stock_X_noidx.head(2) # %timeit df_book_train_stock_X_noidx.groupby('time_id_cat').mean() df_book_train_stock_X_noidx['stock_id_cat'] = df_book_train_stock_X_noidx['stock_id'].astype('category') df_book_train_stock_X_idx_cat = df_book_train_stock_X_noidx.set_index(['stock_id_cat', 'time_id_cat']) df_book_train_stock_X_idx_cat.head(2) # %timeit df_book_train_stock_X_idx_cat.groupby('time_id_cat').mean() def make_features_stats(df_book, agg_type, cols): features_var1 = df_book.groupby(['stock_id', 'time_id'])[cols].agg(agg_type) #print(type(features_var1)) if isinstance(features_var1, pd.Series): # .size yields a series not a df #features_var1.name = str(agg_type) features_var1 = pd.DataFrame(features_var1, columns=[agg_type]) #pass else: features_var1_col_names = [f"{col}_{agg_type}" for col in cols] features_var1.columns = features_var1_col_names return features_var1 df_book_train_stock_X.groupby('time_id').mean() # %timeit make_features_stats(df_book_train_stock_X, 'mean', df_book_train_stock_X.columns.values)
notebooks/20210825_timings.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.4.0 # language: julia # name: julia-1.4 # --- # # Benders Decomposition # **Originally Contributed by**: <NAME> # This notebook describes how to implement Benders decomposition in JuMP, which is a large scale optimization scheme. # We only discuss the classical approach (using loops) here. # The approach using lazy constraints is showed in the correponding notebook. # To illustrate an implementation of the Benders decomposition in JuMP, # we apply it to the following general mixed integer problem: # \begin{align*} # & \text{maximize} \quad &&c_1^T x+c_2^T v \\ # & \text{subject to} \quad &&A_1 x+ A_2 v \preceq b \\ # & &&x \succeq 0, x \in \mathbb{Z}^n \\ # & &&v \succeq 0, v \in \mathbb{R}^p \\ # \end{align*} # where $b \in \mathbb{R}^m$, $A_1 \in \mathbb{R}^{m \times n}$, $A_2 \in \mathbb{R}^{m \times p}$ and # \mathbb{Z} is the set of integers. # Here the symbol $\succeq$ ($\preceq$) stands for element-wise greater (less) than or equal to. # Any mixed integer programming problem can be written in the form above. # We want to write the Benders decomposition algorithm for the problem above. # Consider the polyhedron $\{u \in \mathbb{R}^m| A_2^T u \succeq 0, u \succeq 0\}$. # Assume the set of vertices and extreme rays of the polyhedron is denoted by $P$ and $Q$ respectively. # Assume on the $k$th iteration the subset of vertices of the polyhedron mentioned is denoted by # $T(k)$ and the subset of extreme rays are denoted by $Q(k)$, # which will be generated by the Benders decomposition problem below. # ### Benders decomposition algorithm # **Step 1 (Initialization)** # We start with $T(1)=Q(1)=\emptyset$. # Let $f_m^{(1)}$ be arbitrarily large and $x^{(1)}$ be any non-negative integer vector and go to Step 2. # **Step 2 (Solving the master problem)** # Solve the master problem, $f_\text{m}^{(k)}$ = # \begin{align*} # &\text{maximize} &&\quad t \\ # &\text{subject to} \quad &&\forall \bar{u} \in T(k) \qquad t + (A_1^T \bar{u} - c_1)^T x \leq b^T \bar{u} \\ # & && \forall \bar{y} \in Q(k) \qquad (A_1 ^T \bar{y})^T x \leq b^T \bar{y} \\ # & && \qquad \qquad \qquad \; x \succeq 0, x \in \mathbb{Z}^n # \end{align*} # Let the maximizer corresponding to the objective value $f_\text{m}^{(k)}$ be denoted by $x^{(k)}$. # Now there are three possibilities: # - If $f_\text{m}^{(k)}=-\infty$, i.e., the master problem is infeasible, # then the original proble is infeasible and sadly, we are done. # # - If $f_\text{m}^{(k)}=\infty$, i.e. the master problem is unbounded above, # then we take $f_\text{m}^{(k)}$ to be arbitrarily large and $x^{(k)}$ to be a corresponding feasible solution. # Go to Step 3 # # - If $f_\text{m}^{(k)}$ is finite, then we collect $t^{(k)}$ and $x^{(k)}$ and go to Step 3. # **Step 3 (Solving the subproblem and add Benders cut when needed)** # Solve the subproblem, $f_s(x^{(k)})$ = # \begin{align*} # c_1^T x^{(k)} + & \text{minimize} && (b-A_1 x^{(k)})^T u \\ # & \text{subject to} && A_2^T u \succeq c_2 \\ # & && u \succeq 0, u \in \mathbb{R}^m # \end{align*} # Let the minimizer corresponding to the objective value $f_s(x^{(k)})$ be denoted by $u^{(k)}$. There are three possibilities: # - If $f_s(x^{(k)}) = \infty$, the original problem is either infeasible or unbounded. # We quit from Benders algorithm and use special purpose algorithm to find a feasible solution if there exists one. # # - If $f_s(x^{(k)}) = - \infty$, we arrive at an extreme ray $y^{(k)}$. # We add the Benders cut corresponding to this extreme ray $(A_1 ^T y^{(k)})^T x \leq b^T y^{(k)}$ to the master problem # i.e., $Q(k+1):= Q(k) \cup \{y^{(k)}\}$. Take $k:=k+1$ and go to Step 3. # # - If $f_s(x^{(k)})$ is finite, then # # * If $f_s(x^{(k)})=f_m^{(k)}$ we arrive at the optimal solution. # The optimum objective value of the original problem is $f_s(x^{(k)})=f_m^{(k)}$, # an optimal $x$ is $x^{(k)}$ and an optimal $v$ is the dual values for the second constraints of the subproblem. We are happily done! # # * If $f_s(x^{(k)}) < f_m^{(k)}$ we get an suboptimal vertex $u^{(k)}$. # We add the corresponding Benders cut $u_0 + (A_1^T u^{(k)} - c_1)^T x \leq b^T u^{(k)}$ to the master problem, i.e., $T(k+1) := T(k) \cup \{u^{(k)}\}$. Take $k:=k+1$ and go to Step 3. # For a more general approach to Bender's Decomposition you can have a look at # [<NAME>'s blog](https://matbesancon.github.io/post/2019-05-08-simple-benders/). # ## Data for the problem # The input data is from page 139, Integer programming by Garfinkel and Nemhauser[[1]](#c1). # + c1 = [-1; -4] c2 = [-2; -3] dim_x = length(c1) dim_u = length(c2) b = [-2; -3] A1 = [1 -3; -1 -3] A2 = [1 -2; -1 -1] M = 1000; # - # ## How to implement the Benders decomposition algorithm in JuMP # There are two ways we can implement Benders decomposition in JuMP: # - *Classical approach:* Adding the Benders cuts in a loop, and # - *Modern approach:* Adding the Benders cuts as lazy constraints. # The classical approach might be inferior to the modern one, as the solver # - might revisit previously eliminated solution, and # - might discard the optimal solution to the original problem in favor of a better but # ultimately infeasible solution to the relaxed one. # For more details on the comparison between the two approaches, see [Pa<NAME>in's blog on Benders Decomposition](http://orinanobworld.blogspot.ca/2011/10/benders-decomposition-then-and-now.html). # ## Classical Approach: Adding the Benders Cuts in a Loop # Let's describe the master problem first. Note that there are no constraints, which we will added later using Benders decomposition. # + # Loading the necessary packages #------------------------------- using JuMP using GLPK using LinearAlgebra using Test # Master Problem Description # -------------------------- master_problem_model = Model(GLPK.Optimizer) # Variable Definition # ---------------------------------------------------------------- @variable(master_problem_model, 0 <= x[1:dim_x] <= 1e6, Int) @variable(master_problem_model, t <= 1e6) # Objective Setting # ----------------- @objective(master_problem_model, Max, t) global iter_num = 1 print(master_problem_model) # - # Here is the loop that checks the status of the master problem and the subproblem and # then adds necessary Benders cuts accordingly. # + iter_num = 1 while(true) println("\n-----------------------") println("Iteration number = ", iter_num) println("-----------------------\n") println("The current master problem is") print(master_problem_model) optimize!(master_problem_model) t_status = termination_status(master_problem_model) p_status = primal_status(master_problem_model) if p_status == MOI.INFEASIBLE_POINT println("The problem is infeasible :-(") break end (fm_current, x_current) = if t_status == MOI.INFEASIBLE_OR_UNBOUNDED (M, M * ones(dim_x)) elseif p_status == MOI.FEASIBLE_POINT (value(t), value.(x)) else error("Unexpected status: $((t_status, p_status))") end println("Status of the master problem is ", t_status, "\nwith fm_current = ", fm_current, "\nx_current = ", x_current) sub_problem_model = Model(GLPK.Optimizer) c_sub = b - A1 * x_current @variable(sub_problem_model, u[1:dim_u] >= 0) @constraint(sub_problem_model, constr_ref_subproblem[j = 1:size(A2, 2)], dot(A2[:, j], u) >= c2[j]) # The second argument of @constraint macro, # constr_ref_subproblem[j=1:size(A2,2)] means that the j-th constraint is # referenced by constr_ref_subproblem[j]. @objective(sub_problem_model, Min, dot(c1, x_current) + dot(c_sub, u)) print("\nThe current subproblem model is \n", sub_problem_model) optimize!(sub_problem_model) t_status_sub = termination_status(sub_problem_model) p_status_sub = primal_status(sub_problem_model) fs_x_current = objective_value(sub_problem_model) u_current = value.(u) ฮณ = dot(b, u_current) println("Status of the subproblem is ", t_status_sub, "\nwith fs_x_current = ", fs_x_current, "\nand fm_current = ", fm_current) if p_status_sub == MOI.FEASIBLE_POINT && fs_x_current == fm_current # we are done println("\n################################################") println("Optimal solution of the original problem found") println("The optimal objective value t is ", fm_current) println("The optimal x is ", x_current) println("The optimal v is ", dual.(constr_ref_subproblem)) println("################################################\n") break end if p_status_sub == MOI.FEASIBLE_POINT && fs_x_current < fm_current println("\nThere is a suboptimal vertex, add the corresponding constraint") cv = A1' * u_current - c1 @constraint(master_problem_model, t + dot(cv, x) <= ฮณ) println("t + ", cv, "แต€ x <= ", ฮณ) end if t_status_sub == MOI.INFEASIBLE_OR_UNBOUNDED println("\nThere is an extreme ray, adding the corresponding constraint") ce = A1'* u_current @constraint(master_problem_model, dot(ce, x) <= ฮณ) println(ce, "แต€ x <= ", ฮณ) end global iter_num += 1 end @test value(t) โ‰ˆ -4 # - # ### References # <a id='c1'></a> # 1. <NAME>. & <NAME>. Integer programming. (Wiley, 1972).
notebook/optimization_concepts/benders_decomposition.ipynb
# + """ You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: """ """Question 19 Level 3 Question: You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. The priority is that name > age > score. If the following tuples are given as input to the program: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85 Then, the output of the program should be: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. """
pset_challenging_ext/exercises/nb/p19.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 # --- # + _cell_guid="a3cb0ee3-7bca-4b2b-8a27-be198d18818e" _uuid="075ab0f3fc310e293828b3681f1d80642f88c106" language="html" # <style> # .h1_cell, .just_text { # box-sizing: border-box; # padding-top:5px; # padding-bottom:5px; # font-family: "Times New Roman", Georgia, Serif; # font-size: 125%; # line-height: 22px; /* 5px +12px + 5px */ # text-indent: 25px; # background-color: #fbfbea; # padding: 10px; # } # # hr { # display: block; # margin-top: 0.5em; # margin-bottom: 0.5em; # margin-left: auto; # margin-right: auto; # border-style: inset; # border-width: 2px; # } # </style> # - # <h1> # <center> # Module 6 - from bag to matrix # </center> # </h1> # <div class=h1_cell> # <p> # This week I want to head in a slightly different direction than the bag of words approach. I want you to consider (and program) a co-occurrence matrix (comat). The comat can lead toward some very cool NLP methods. # </div> # <h2> # Here's the idea # </h2> # <div class=h1_cell> # <p> # With bag of words, we threw away context information. If I look up bag_of_words['fawn'], I can see how many times fawn appeared but I don't know anything about what context it appeared in. The context I will be interested to start with are the two words on either side of fawn, i.e., one word on left and one word on right. If fawn is at beginning or end of sentence, then we will only count one word. # <p> # To get this new information about context, I will have to go through all the sentences again, and for each word I will update what word is on either side of it. Let me try a small example. Pretend we only have 3 sentences. # <p> # <pre> # I love programming. I love Math. I tolerate Biology. # </pre> # <p> # Check out the comat I would build from these sentences. # <p> # <img src='https://cdn-images-1.medium.com/max/1600/1*1p0geczj9KbJvwYi25B2Jg.png'> # <p> # You should notice that the row names and column names are symmetric. They are made up of the unique words in all the sentences. You should also note that sentences matter. For instance, if you remove the periods, then you would get `Math` coming right before `I`. So should be an entry for `[Math, I]` of `1`. But it is zero. We do not cross sentence boundaries to check for co-occurrences. # <p> # Also note that we are looking at either side of a word for co-occurrences. Hence, `I` shows up with `love` twice and `love` shows up with `I` twice. # <p> # Finally note that the above matrix is counting a period as a word. I think that is interesting, using punctuation instead of throwing it out, but I did not do it. To match my results, use your sentence_wrangler, which throws out punctuation among other things. # </div> # <h2> # There is one parameter # </h2> # <div class=h1_cell> # <p> # The parameter for a comat is how far from the target word we check. In the example above, the parameter value is 1 - check 1 word on either side. But I could set it to a larger integer. If I make it big enough, I'll likely get most of the sentence as the context. # <p> # Reminder: parameters like this in data science are often called hyper-parameters. The "K" in KNN is a hyper-parameter. # <p> # I won't ask you to parameterize your algorithm for the main assignment: you can assume it is a constant 1. If anyone needs make-up points for past homework, I'll give you extra credit points if you can parameterize your algorithm to use a parameter. So look 2 words out or 3 words out, etc. The larger the parameter, the more context you are picking up. # </div> # <h2> # Doing things a little differently # </h2> # <div class=h1_cell> # <p> # Normally I would guide you through main steps and have you fill in pieces. I am going to cut you loose for this assignment. You can solve the problem in any way you want as long as you match my results. # <p> # What you will need to get started: # <ul> # <li>gothic_table # <li>sentence_wrangler plus what it needs as params. # <li>cosine_similarity # </ul> # <p> # I hope you have inferred from the sample comat above that your comat will be N by N where N = 24834. Yikes. Every unique word is a row/column label. This may take a fairly big chunk of your laptop's virtual memory. Here is a piece of code that you might find useful. It tells you what percentage of memory you have remaining. # <pre> # <code> # import psutil # print(psutil.virtual_memory()) # percent is what is remaining # </code> # </pre> # <p> # I was ok on my laptop with 16GB memory. If you run into trouble on your machine, see me. # <p> # I also took time to compute various things. Did I mention we are now working on a `24834x24834 matix`? Things take time. On my slow machine, worst I got was 9 minutes. You might look at the magic-command `%time`: sometimes easier to use than setting up start and end time, e.g., `%time some_function()` will give you the elapsed time for getting a return value. # </div> # <h2> # Challenge 1 # </h2> # <div class=h1_cell> # <p> # Build the comat using sentences from gothic_table with a spread of 1, i.e., 1 word on either side of target word. Please use sorted labels on your comat. This is different than the sample comat above which uses the order the words are seen. So your matrix should have these as the first 10 rows and columns. # <p> # <pre> # 'aaem' # 'ab' # 'aback' # 'abaft' # 'abandon # 'abandoned' # 'abandoning' # 'abandonment' # 'abaout' # 'abased' # </pre> # <p> # Use any raw Python data structures you like. I am also ok with a pandas dataframe if you want. # <p> # I've given you my results to match against below. # </div> # + import pandas as pd gothic_table = pd.read_csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vQqRwyE0ceZREKqhuaOw8uQguTG6Alr5kocggvAnczrWaimXE8ncR--GC0o_PyVDlb-R6Z60v-XaWm9/pub?output=csv', encoding='utf-8') # - gothic_table.head() len(gothic_table) # <h2> # Go to it # </h2> # <div class=h1_cell> # <p> # Add your own code cells to create and test your code. # </div> #here is a starting cell - add new ones with + tab above. # <h2> # Match against my results # </h2> # <div class=h1_cell> # <p> # I don't know how you are implementing the comat so I'll just describe the results I got below. Show me that you get the same. # # <ul> # <li>The count of 0s in row 'monster' is 24765. # <li>The cosine_similarity between the rows 'frankenstein' and 'monster' is 0.07273929674533079 # <li>The sum of the 'frankenstein' row is 32. # <li>The sum of the 'monster' row is 74. # </ul> # </div> #show me your match # <h2> # Challenge 2 # </h2> # <div class=h1_cell> # <p> # Do the first part of KNN. Find all the distances from a specific word as a row in comat. Use cosine_similarity. Match my results. # <p> # BTW: this is where things slowed down and I was getting 9 minutes on my slow machine. # </div> # + def word_distances(matrix, word): # - # %time monster_distances = word_distances(matrix, 'monster') monster_distances[:10] # %time frank_distances = word_distances(matrix, 'frankenstein') frank_distances[:10] # <h2> # Closing notes # </h2> # <div class=h1_cell> # <p> # If we had more time in the quarter, I'd like to follow up on the next step we can take once we have the comax. The general idea is that the comax is a very sparse matrix, consisting of mostly 0 entries. And as you have seen, it takes time to search it. There are linear-algebra techniques for reducing a sparse matrix into a more dense matrix and hence, making them more computationally tractable to work with. One I particular wish we had time to explore is Singular-value Decomposition (or SVD): https://en.wikipedia.org/wiki/Singular-value_decomposition. This is used with the Glove algorithm to take a comax, exactly like the one you built, and reduce it: https://nlp.stanford.edu/projects/glove/. # <p> # An alternative approach is one called word-to-vec (or word2vec). This uses a shallow neural-net to reduce each word to a vector of "features". Here is a good overview: http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/. You may have seen some of the cool things they can do with these feature vectors, e.g., take the vector for 'king', subtract the vector for 'man' and add the vector for 'woman. The resulting vector is 'queen'. # <p> # If I was going to teach a follow-on course to this one, I would definitely want to follow the neural-net and deep-learning path further. If anyone is interested in doing a reading (for credit) on these topics in summer or next year, see me. # </div>
UpperDivisionClasses/Data_Science/week6/.ipynb_checkpoints/comax_handout_ref-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 (ipykernel) # language: python # name: python3 # --- # # `trim_nonpercolating_paths` # ``trim_nonpercolating_paths`` function is a filter which removes all nonpercolating paths between specified locations. import numpy as np import porespy as ps import scipy.ndimage as spim import matplotlib.pyplot as plt # ## `im` # This function works on both 2D and 3D boolean images of the pore space: # + np.random.seed(0) im = ps.generators.blobs(shape=[500, 500], porosity=0.55, blobiness=1.5) plt.figure(figsize=[6, 6]); plt.axis(False); plt.imshow(im); # - # ## `inlets` and `outlets` # Inlets and outlets are specified by creating ``boolean`` images the same shape as ``im``, with ``True`` values indicating which voxels are inlets and outlets, respectively. The function then only keeps paths which connect to *both* inlets and outlets: # + inlets = np.zeros_like(im) inlets[0, :] = True outlets = np.zeros_like(im) outlets[-1, :] = True x = ps.filters.trim_nonpercolating_paths(im=im, inlets=inlets, outlets=outlets) fig, ax = plt.subplots(1, 2, figsize=[12, 12]); ax[0].imshow(x); ax[0].set_title('Trimmed Nonpercolating Paths', fontdict={'fontsize': 18}); ax[0].axis(False); ax[1].imshow(x + (im != x)*0.5); ax[1].set_title('Showing Paths Removed', fontdict={'fontsize': 18}); ax[1].axis(False);
examples/filters/reference/trim_nonpercolating_paths.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:py35] # language: python # name: conda-env-py35-py # --- # # Informe de aportes hidrologicos para el aรฑo 2004 # Este es un ejemplo de **clase** para *manipulaciรณn* de **_archivos_** csv usando python # + item 1 # + item 2 # + item 3 help (open) # # %load Demo.txt este es un archivo par el curso de python que tanto me estรก costando, es algo muy complicado pero ahรญ vamos # %%writefile demo2.txt returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. # %ls # # %load demo2.txt returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. # !head AportesDiario_2004.csv import pandas as pd # !pip install pandas import pandas as pd pd.read_csv('AportesDiario_2004.csv', sep=';', decimal=',', thousands='.', skiprows=3) x = pd.read_csv('AportesDiario_2004.csv', sep=';', decimal=',', thousands='.', skiprows=3) x.head() x x['Fecha'] x['Region Hidrologica'] len(x[x['Region Hidrologica'] == 'ANTIOQUIA']) import statistics statistics.mean (x[x['Nombre Rio'] == ['Aportes Energia kWh']).values[:])) n = set (x['Nombre Rio']) n for y in n: z=x[x['Nombre Rio'] == y] ['Aportes Energia kWh'] if len(z) > 0: print (y, statistics.mean(x[x['Nombre Rio'] == y] ['Aportes Energia kWh'].values[:])) for y in n: z=x[x['Nombre Rio'] == y] ['Aportes Energia kWh'] if len(z) > 0: print (y, statistics.mean(x[x['Nombre Rio'] == y] ['Aportes Caudal m3/s'].values[:])) ALTOANCHICAYA 43.468715847 <NAME> 36.4666120219 PORCE II 99.2926502732 CALIMA 11.9220765027 GRANDE 27.5119672131 OTROS RIOS (ESTIMADOS) nan CONCEPCION 6.60666666667 DESV. EEPPM (NEC,PAJ,DOL) 8.31224043716 BOGOTA N.R. 28.0518032787 MAGDALENA BETANIA 374.490765027 TENCHE 3.90087431694 CHUZA 9.7424863388 PRADO 45.5972677596 GUATAPE 34.1030327869 GUADALUPE 20.1679781421 SINU URRA 284.44420765 NARE 49.7116120219 DIGUA 27.5295355191 CAUCA SALVAJINA 113.523306011 FLORIDA II 10.7124863388 <NAME> 24.9104918033 MIEL I 78.4332513661 GUAVIO 85.8845628415 BATA 95.478989071
Informe2004.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 # --- # ## Reading and writing data files # This is more generally known as 'file i/o" where "i" and "o" stand for input and output, respectively. # Why do we need to do file i/o? # # ##### File input # # The input case is more obvious. To analyze data, you need data to analyze. Unless you know magic, you access data from *data files*, which are files just like a PDF or whatever, but they are specialized to some degree for containing data. Whether from a colleague, a boss, a webpage, or a government data repository, data will come in a data file that you will need to read as input in order visualize and analyze the data. # # ##### File output # # The output case is perhaps less obvious. You read data into your Jupyter Notebook, you make pretty graphs, you do some cool analysis, and then you show it off to some people. You're done, right? But what if you want to share the numerical values of the analysis with someone else? If you can write those values to a data file and just send that, then they can read in the values on their end without having to wade through your notebook and cutting and pasting or whatever. # # Alternatively, you may have improved a data set by adding a few informative columns. If you can write the data out to a data file, then you can share it, and everybody else can use and enjoy your new improved version of the data file. # ### Let's get started! # #### Import libraries # *Libraries* are organized collections of Python code written to perform related tasks. We met some in the very first tutorial! You will hear of "Libraries", "Packages", and "Modules". Technically, Libraries contain Packages which contain modules. Modules are single files that contain useful functions, Packages are directories to a set of modules (or other packages), and Libraries are directories to a set of packages. That having been said, I tend to refer to them interchagebly as "*useful chunks of pre-written code we can use!*" # # ##### So, as always, the first thing we need to do is import the libraries we'll likely be using: # # * pandas for the i/o # * matplotlib.pyplot and... # * seaborn to plot file contents # *Remember, to run each code cell like the one below, select it and then hit **shift-return** (or shift-enter)*. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Now you should have these three libraries available to you via their standard nicknames: pd, plt, and sns. # # If 'sns' seems like a weird nickname for 'seaborn', I'll give you hint about it: It's an homage to one of the main characters in one of the best television series ever made. The show ran from 1999 until 2006 on NBC. # ### Let's read some data! # There are many ways that data can be stored, from excel files to tables on webpages. # For this tutorial, we are going to read a data file called `006DataFile.csv`, which you should have in the same folder as this notebook if you followed the ReadMe! # We read a .csv file (more on this file type in a bit) using the `pandas.read_csv()` function. But, remember, we have imported pandas as pd, so we read the .csv file, with slightly less typing, like this: myDataFromFile = pd.read_csv("datasets/006DataFile.csv") # This command will work "out of the box" if your copy of the data file is in your "*datasets*" directory, which should be a subdirectory of the one this notebook is in. # # Otherwise, you would have to change the command above to specify the path to the data file โ€“ where on the file tree the data file exists (either in '*absolute*' terms from root, or in '*relative*' terms from you current directory). # ### Let's look at what we just read. # Okay, now let's look at the file. We can take a quick peek by using the `display()` function: display(myDataFromFile) # Here, we can see that this file (like almost all data files) consists of rows and columns. The rows represent *observations* and the columns represent *variables*. This type of data file contains "tidy" data (if you have used R, you may have encountered the tidyverse). Sometimes, we will encounter data files that violate this "rows = observations, columns = variables" rule โ€“ untidy data โ€“ we will deal with this issue later in the class. # A very common genertic data file type is the comma separated values file, or .csv file. This is the type of data file we just loaded (006DataFile***.csv***). As the name implies, a file in this format consists values separated by commas to form rows, and "carriage returns" (CR) or "line feeds" (LF) marking the end of each row. # --- # **Useless Trivia Alert!**: # # These terms come from typewritters and old-old-old-school printers, respectively. Typewritters had a "carriage" that held the paper and moved to the left while you typed. When you got to the right edge of the paper, you hit the "*carriage return*" key and the whole carriage flew back (*returned*) to right with a loud clunk and advanced the paper down a line. To this day, the big fat important key on the right side of most keyboards still says "return". # # Old-school printers used long continuous "fan fold" sheets of paper (they could be literally hundreds of feet long) and had to be told to advance the paper one line with a "*line feed*" command. Once you were done printing, you ripped/cut your paper off the printer sort of like you do with aluminum foil or plastic wrap! # # --- # **Useful aside!:** # We can even copy data to the clipboard and read that in. I just copied the [population of Burkina Faso by year](https://en.wikipedia.org/wiki/Burkina_Faso) from wikibedia. And we can read that into a data frame like this: cb = pd.read_clipboard() cb # How cool is that?!?! # --- # Okay, now back to the show. In addition to display(), we use can use data frame `methods`. What is a "method"? Methods are things that an object, like a Pandas data frame, already knows how to do. They are actions that an object can perform for you without any additional coding on your part! # One thing a data frame knows how to do is show you its first few rows with the `head()` method: myDataFromFile.head() # ... or its last few rows with `tail()`: myDataFromFile.tail() # But how do you know what methods a given object has? Python's `dir()` function will give you a directory of any objects methods: dir(myDataFromFile) # HFS!!! Data frames know how to do a LOT! It's a bit overwhelming actually. We can ignore all the things that look like \_\_this\_\_ at the top. Scrolling the the others, `describe()` looks promising! Let's see what it does! myDataFromFile.describe() # OMG, that was a good find! # # I also noticed a `hist` method. Could it even be possible that data frames know how to draw histograms of themselves? myDataFromFile.hist() # ## **NO WAY!!!!!** # # #### I'm beginning to suspect our journey of learning to play with data is going to be part learning to code and part figuring how to use what's already out there! # Okay, now let's make a histogram with the Sam โ€“ oops! โ€“ I mean `seaborn` library. `Seaborn` is a library that really just calls `matplotlib` functions, but it provides a way to use those functions that is easier than using them directly. # # It also by default generally makes prettier plots. # # Here's a histogram: sns.histplot(myDataFromFile, multiple="stack") # ##### Google `seaborn.histplot()` to see what the `multiple` argument does and what other possible arguments are. Play around with these to change the appearance of the histogram! # Now let's make Kernel Density Estimate (KDE) plots of the distributions. KDEs are essentially smoothed versions of histograms (we can unpack more about exactly what these are later). They can give us a better visual represtation of the "vibe" of a distribution. # # For the KDE plot, we plot each variable in turn, and we'll use the `color` argument in the second plot to set the curves apart: sns.kdeplot(myDataFromFile["VarA"]) sns.kdeplot(myDataFromFile["VarB"], color="r") # Here we can more clearly see the difference in means as compared to the histogram. # We can make the visualization more aethetically appealing by using some of the optional arguments to `seaborn.kdeplot()` sns.kdeplot(myDataFromFile["VarA"], color="b", fill=True, alpha=0.2) sns.kdeplot(myDataFromFile["VarB"], color="r", fill=True, alpha=0.2) # The `color` argument is obvious. `fill` colors the area under the curve, and `alpha` make the fill transparent so you can see one curve through the other. Play around with these! # ### Let's see if we can write data to a file! # Now maybe we can write a summary of the original data to a file so we could potentially share it with other. What we'll do is use the `describe()` method again, but this time we'll assign it to new data frame. mySummary = myDataFromFile.describe() # Let's just quickly that `mySummary` contains what we hope it does: print(mySummary) # Now let's write it to a file! We'll use the `to_csv` method that you can see lurking the output of `dir()` above. mySummary.to_csv("mySummary.csv") # Okay, but how do we know that worked? Easy! We'll read that file back in using `pandas.read_csv()` and see what it looks like! mySumFF = pd.read_csv("mySummary.csv") # And then we can look at it using `display()`. display(mySumFF) # ### Sweet! We can now read and write data files. File I/0 handled!
tutorial006.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6.9 64-bit # name: python3 # --- # + from env import MsnDiscrete from stable_baselines3 import DQN from stable_baselines3.common.vec_env.dummy_vec_env import DummyVecEnv from stable_baselines3.common.evaluation import evaluate_policy import torch from torch import nn # - # # Use baseline3 to train and evaluate env = MsnDiscrete() env = DummyVecEnv([lambda : env]) model = DQN( "MlpPolicy", env=env, learning_rate=5e-4, batch_size=128, buffer_size=50000, learning_starts=0, target_update_interval=250, policy_kwargs={"net_arch" : [256, 256]}, verbose=1, tensorboard_log="./tensorboard/MsnDiscrete-v2/" ) model.learn(total_timesteps=1e5) # # We can use DQN class Net(nn.Module): def __init__(self, n_state): super().__init__() self.fc1 = nn.Linear(n_state, 50) self.fc2 = nn.Linear(50)
ws.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 # --- # Update sklearn to prevent version mismatches # !conda install scikit-learn # !conda update scikit-learn # !conda install joblib # !conda update joblib import pandas as pd # Import the testing csvs testing_data = pd.read_csv('test_data.csv') # Split the test data into X and y y_test = testing_data["koi_disposition"] X_test = testing_data.drop(columns=["koi_disposition"]) # scale the data if the student did from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() X_test= scaler.fit_transform(X_test) # set your x_test to match the same variables that the student chose. # Can copy/paste their feature selection code. Just be sure to set it to X_test X_test = X_test[[]] # # Testing # + # load and score the student's model import joblib # update file name with student file # filename = 'student_model.sav' filename = 'deep_learning.sav' loaded_model = joblib.load(filename) result = loaded_model.score(X_test, y_test) print(result) # - # # Deep Learning Testing # + # load and score the student's model import joblib from sklearn.preprocessing import LabelEncoder from keras.utils import to_categorical # update file name with student file filename = 'deep_learning.sav' loaded_model = joblib.load(filename) label_encoder = LabelEncoder() label_encoder.fit(y_test) encoded_y_test = label_encoder.transform(y_test) y_test_categorical = to_categorical(encoded_y_test) encoded_predictions = loaded_model.predict_classes(X_test[:10]) prediction_labels = label_encoder.inverse_transform(encoded_predictions) # Take number correct over total to get "score" for grading print(f"Predicted classes: {prediction_labels}") print(f"Actual Labels: {list(y_test[:10])}") # -
testing_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 # --- # # Scaled data widget # ipyscales also allow for front-end based scaling of array data by implementing the ipydatawidgets interfaces. This allows e.g. for sending you (large) dataset once, and then rapidly re-scaling it on the front-end side. import numpy as np from ipyscales import LinearScale, LogScale from ipyscales.datawidgets import ScaledArray from ipydatawidgets import DataImage np.random.seed(0) from ipyscales._example_helper import use_example_model_ids use_example_model_ids() # Set up some random RGBA data: data = np.array(255 * np.random.rand(200, 200, 4), dtype='uint8') # Set up two simple scales for translating each channel value, one linear, one logarithmic: linear = LinearScale(range=(0, 255), domain=(0, 255), clamp=True) # Setup log scale as alternative scale. Note the non-zero domain with clamp! log = LogScale(range=(0, 255), domain=(1, 255), clamp=True) # Set up our scaled data source. This will not transmit the scaled data back to the kernel, but if passed to a data union trait, the scaled data will be used: scaled_data = ScaledArray(data=data, scale=linear) # Pass the scaled data to a `DataImage` to visualize it: image = DataImage(data=scaled_data) image # Add some controls for selecting which scale to use, and what the range of the scales should be: # + from ipywidgets import FloatRangeSlider, jslink, HBox from ipyscales.selectors import WidgetDropdown range_selector = FloatRangeSlider(min=0, max=255, step=1, description='range', readout_format='d') jslink((linear, 'range'), (range_selector, 'value')) jslink((range_selector, 'value'), (log, 'range')) scale_selector = WidgetDropdown(options={'Linear': linear, 'Log': log}, description='Scale') jslink((scale_selector, 'value'), (scaled_data, 'scale')) HBox([scale_selector, range_selector]) # - # ## Color mapped data # Set up a 2D scalar field of floats (0-1) to act as our data. Here, a nice diagonal gradient: side_length = 200 scalar_field = np.sum(np.meshgrid( np.linspace(0, 0.5, side_length), np.linspace(0, 0.5, side_length), ), axis=0) # This time, we use a color map as the scale. Here we use named, sequential color maps: from ipyscales import NamedSequentialColorMap cmap = NamedSequentialColorMap(name='viridis') # When setting up a scaled array with a color map, we should specify the output dtype we want. If not, it will inherit the dtype of the input data. In this case, the input dtype is float, and `DataImage` expects a unsigned 8-bit integer. mapped_data = ScaledArray(data=scalar_field, scale=cmap, output_dtype='uint8') # Visualize the mapped data: mapped_image = DataImage(data=mapped_data) mapped_image # Show a drop-down selector for the color map name: cmap.edit()
examples/scaled-data.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_ext autoreload # %autoreload 2 # %cd /home/aditya/git/kaggle_pneumonia # %env PROJECT_PATH = /home/aditya/git/kaggle_pneumonia # %matplotlib inline import seaborn as sns import pandas as pd import numpy as np import pydicom from PIL import Image import multiprocessing as mp from tqdm import tqdm_notebook as tqdm from __future__ import print_function, division import os import torch import pandas as pd import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import skimage # Ignore warnings import warnings warnings.filterwarnings("ignore") # + import torch import torch.nn as nn import torch.nn.functional as F import fastai from fastai import * from fastai.vision import * # - from utils.envs import * from utils.data_load import * from utils.lr_finder import lr_plot, lr_find from utils.common import get_batch_info from utils.checkpoint import save_checkpoint, load_cp_model, load_cp_optim from utils.logger import logger from pathlib import Path p = Path(data_source_path) train_label_df = pd.read_csv(train_label_repo) train_label_df['area'] = train_label_df.width * train_label_df.height single_label_df = train_label_df.sort_values('area', ascending = False).drop_duplicates('patientId').sort_index().reset_index(drop = True).copy() single_label_df.fillna(0, inplace = True) device = torch.device('cuda:0') single_label_df.head(5) data = image_data_from_csv(p, 'train_images', csv_labels = 'label.csv', suffix='.png', valid_pct = 0.1, test='test_images') learn = ConvLearner(data, tvm.resnet18, metrics=accuracy) learn.fit_one_cycle(1) x = learn.get_preds(is_test=True) log_preds = x[0].cpu().numpy() preds = np.exp(log_preds) preds_prob = preds / np.sum(preds, axis = 1)[:, None] submission = preds_prob[:, 1] test_path = data.test_dl.dataset.x # + ##BBOX # - md = image_data_from_csv(p, 'train_images', csv_labels = 'bb.csv', suffix='.png', valid_pct = 0.1, test='test_images', continuous = True) bb_learn = ConvLearner(md, tvm.resnet34) header = nn.Sequential(Flatten(), nn.Linear(25088,4)).to(device) bb_learn = ConvLearner(md, tvm.resnet34, custom_head=header) bb_learn.crit = nn.L1Loss().to(device) head_reg4 = nn.Sequential(Flatten(), nn.Linear(25088,4)) learn = ConvLearner.pretrained(f_model, md, custom_head=head_reg4) learn.opt_fn = optim.Adam learn.crit = nn.L1Loss() bb_learn.fit_one_cycle(1) bb_learn.get_preds(is_test=True)[0]
notebooks/dev_notebooks/fastai.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 # --- # # HPC in Python with TensorFlow try: import google.colab except ImportError: pass else: # !pip install zfit numba numpy tensorflow_probability import tensorflow as tf # Depending on the CPU used and the TensorFlow binaries, what we will see (not in the Jupyter Notebook) are a bunch of messages, including the following: # `tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA` # # What could they mean? # # AVX stands for Advanced Vector Extensions and are instruction that the CPU can perform. They are specializations on vector operations (remember? SIMD, CPU inststruction set, etc.) # # Why do they appear? # # The code that we are using was not compiled with this flag on. This means, TensorFlow assumes that the CPU does not support this instructions and instead uses non-optimized ones. The reason is that this allows the binary (=compiled code) to also be run on a CPU that does not support then. While we use only some speed. # (yes, technically TensorFlow can be faster when compiled natively on your computer, but then it takes time and effort) import tensorflow_probability as tfp import zfit from zfit import z import numpy as np import numba # Let's start with a simple comparison of Numpy, an AOT compiled library, versus pure Python # + size1 = 100000 list1 = [np.random.uniform() for _ in range(size1)] list2 = [np.random.uniform() for _ in range(size1)] list_zeros = [0] * size1 ar1 = np.array(list1) ar2 = np.random.uniform(size=size1) # way more efficient! ar_zeros = np.zeros_like(ar1) # quite useful function the *_like -> like the object # we could also create the below, in general better: # ar_empty = np.empty(shape=size1, dtype=np.float64) # - # %%timeit for i in range(size1): list_zeros[i] = list1[i] + list2[i] # %%timeit ar1 + ar2 # ( _playground_ : we can also try assignements here or simliar) # ### Fast and slow # # Before we go deeper into the topic, we can draw two conclusions: # - slow Python is not "slow": it is still blazingly fast on an absolute scale, e.g if you need to loop over a few hundred points, it's still nothing. But it can add up! # - Numpy is a factor of 300 faster for this case (and: better reabable!) # # => there is _no reason_ to ever add (numerical) arrays with a for loop in Python (except for numba jit) # As mentioned, TensorFlow is basically Numpy. Let's check that out rnd1_np = np.random.uniform(size=10, low=0, high=10) rnd1_np # adding a return value on the last line without assigning it prints the value rnd1 = tf.random.uniform(shape=(10,), # notice the "shape" argument: it's more picky than Numpy minval=0, maxval=10, dtype=tf.float64) rnd2 = tf.random.uniform(shape=(10,), minval=0, maxval=10, dtype=tf.float64) rnd1 # This is in fact a "numpy array wrapped" and can explicitly be converted to an array rnd1.numpy() # Other operations act as we would expect it rnd1 + 10 # ... and it converts itself (often) to Numpy when needed. np.sqrt(rnd1) # We can slice it... rnd1[1:3] # ...expand it.... rnd1[None, :, None] # ...and broadcast with the known (maybe slightly stricter) rules matrix1 = rnd1[None, :] * rnd1[:, None] matrix1 # ## Equivalent operations # # Many operations that exist in Numpy also exist in TensorFlow, sometimes with a different name. # # The concept however is exactly the same: we have higher level objects such as Tensors (or arrays) and call operations on it with arguments. This is a "strong limitation" (theoretically) of what we can do, however, since we do math, there is only a limited set we need, and in practice this suffices for 98% of the cases. # # Therefore we won't dive too deep into the possibilities of TensorFlow/Numpy regarding operations but it is suggested to [read the API docs](https://www.tensorflow.org/versions), many are self-explanatory. It can be surprising that there is also some support for more exotic elements such as [RaggedTensors and operations](https://www.tensorflow.org/api_docs/python/tf/ragged?) and [SparseTensors and operations](https://www.tensorflow.org/api_docs/python/tf/sparse?) # # Mostly, the differences and the terminology will be introduced. tf.sqrt(rnd1) tf.reduce_sum(matrix1, axis=0) # with the axis argument to specify over which to reduce # ### DTypes # # TensorFlow is more picky on dtypes as Numpy and does not automatically cast dtypes. That's why we can often get a dtype error. Solution: make sure you add a `x = tf.cast(x, dtype=tf.float64)` (or whatever dtype we want) to cast it into the right dtype. # # One noticable difference: TensorFlow uses float32 as the default for all operations. Neural Networks function quite well with that (sometimes even with float16) but for (most) scientific use-cases, we want to use float64. So yes, [currently](https://github.com/tensorflow/tensorflow/issues/26033), we have to define this in (too) many places. # # _Sidenote_ : Also zfit uses tf.float64 throughout internally. It's an often seen problem that custom shapes will raise a dtype error. # ## What we can't do: assignements # # The idea of TensorFlow evolves around building a Graph$^{1)}$, the Eager (Numpy-like) execution is more of a "we get it for free addition", but does not lead the development ideas. This has one profound implication, namely that we cannot make an _assignement_ to a Tensor, because it is a node in a graph. The logic just does not work (exception: `tf.Variable`$^{2)}). This does not mean that TensorFlow would not perform in-place operations _behind the scenes_ - it very well does if it is save to do so. Since TensorFlow knows the whole graph with all dependencies, this can be figured out. # # Even if EagerMode, assignements could work (as for Numpy arrays), they are forbidden for consistency (one of the great plus points of TensorFlow). # # ### TensorFlow list # # an advanced structure that can also be modified is the [`tf.TensorArray`](https://www.tensorflow.org/api_docs/python/tf/TensorArray?), which acts like a list or ArrayList (in other languages). It is however advanced and not usually used, so we won't go into the details here. # # _1) if you're familiar with TensorFlow 1, this statement would suprise you as pretty obvious; but in TensorFlow 2, this is luckily more hidden. # 2) more general, `ResourceHandler`_ rnd1_np[5] = 42 try: rnd1[5] = 42 except TypeError as error: print(error) # ### Speed comparison # # Let's do the same calculation as with Numpy. The result should be comparable: both are AOT compiled libraries specialized on numerical, vectorized operations. rnd1_big = tf.random.uniform(shape=(size1,), # notice the "shape" argument: it's more picky than Numpy minval=0, maxval=10, dtype=tf.float64) rnd2_big = tf.random.uniform(shape=(size1,), minval=0, maxval=10, dtype=tf.float64) # %%timeit rnd1_big + rnd2_big # %%timeit # using numpy, same as before ar1 + ar2 # Looks like the same as Numpy. Let's compare with smaller arrays rnd1_np = rnd1.numpy() rnd2_np = rnd2.numpy() rnd1_np # %%timeit rnd1_np + rnd2_np # %%timeit rnd1 + rnd2 # ### TensorFlow is slow? # # We see now a significant difference in the runtime! This is because TensorFlow has a larger overhead than Numpy. As seen before, this is not/barely noticable for larger arrays, however for very small calculations, this is visible. # # There is more overhead because TensorFlow tries to be "smarter" about many things than Numpy and does not simply directly execute the computation. # # The cost is a slowdown on very small operations but a better scaling and improved performance with larger arrays and more complicated calculations. # relative speeds may differ, depending on the hardware used. # size_big = 10 # numpy faster size_big = 20000 # sameish # size_big = 100000 # TF faster # size_big = 1000000 # TF faster # size_big = 10000000 # TF faster # size_big = 100000000 # TF faster # %%timeit tf.random.uniform(shape=(size_big,), dtype=tf.float64) + tf.random.uniform(shape=(size_big,), dtype=tf.float64) # %%timeit np.random.uniform(size=(size_big,)) + np.random.uniform(size=(size_big,)) # ## TensorFlow kernels # # In general, TensorFlow is preciser in what input arguments are required compared to Numpy and does less automatic dtype casting and asks more explicit for shapes. For example, integers don't work in the logarithm. However, this error message illustrates very well the kernel dispatch system of TensorFlow, so lets do it! try: tf.math.log(5) except tf.errors.NotFoundError as error: print(error) # What we see here: it searches the registered kernels and does not find any that supports this operation. We find different classifications: # - GPU: normal GPU kernel # - CPU: normal CPU kernel # - XLA: [Accelerated Linear Algebra](https://www.tensorflow.org/xla) is a high-level compiler that can fuse operations, which would result in single calls to a fused kernel. # ## tf.function # # Let's see the JIT in action. Therefore, we use the example from the slides and start modifying it. def add_log(x, y): print('running Python') tf.print("running TensorFlow") x_sq = tf.math.log(x) y_sq = tf.math.log(y) return x_sq + y_sq # As seen before, we can use it like Python. To make sure that we know when the actual Python is executed, we inserted a print and a `tf.print`, the latter is a TensorFlow operation and therefore expected to be called everytime we compute something. add_log(4., 5.) add_log(42., 52.) # As we see, both the Python and TensorFlow operation execute. Now we can do the same with a decorator. Note that so far we entered pure Python numbers, not Tensors. Since we ran in eager mode, this did not matter so far. @tf.function(autograph=False) def add_log_tf(x, y): print('running Python') tf.print("running TensorFlow") x_sq = tf.math.log(x) y_sq = tf.math.log(y) return x_sq + y_sq add_log_tf(1., 2.) add_log_tf(11., 21.) # again with different numbers # As we see, Python is still run: this happens because 11. is not equal to 1., TensorFlow does not convert those to Tensors. Lets use it in the right way, with Tensors add_log_tf(tf.constant(1.), tf.constant(2.)) # first compilation add_log_tf(tf.constant(11.), tf.constant(22.)) # Now only the TensorFlow operations get executed! Everything else became static. We can illustrate this more extremely here @tf.function(autograph=False) def add_rnd(x): print('running Python') tf.print("running TensorFlow") rnd_np = np.random.uniform() rnd_tf = tf.random.uniform(shape=()) return x * rnd_np, x * rnd_tf add_rnd(tf.constant(1.)) # The first time, the numpy code was executed as well, no difference so far. However, running it a second time, only the TensorFlow parts can change add_rnd(tf.constant(1.)) add_rnd(tf.constant(2.)) # We see now clearly: TensorFlow executes the function but _only cares about the TensorFlow operations_ , everything else is regarded as static. This can be a large pitfall! If we would execute this function _without_ the decorator, we would get a different result, since Numpy is also sampling a new random variable every time. # # ### Large functions # # That having said, we can build graphs that require thousands of lines of Python code to stick them together correctly. Function calls in function calls etc are all possible. # ### Shapes # # Tensors have a shape, similar to Numpy arrays. But Tensors have two kind of shapes, a static and a dynamic shape. The static shape is what can be inferred _before_ executing the computation while the dynamic shape is only inferred during the execution of the code. The latter typically arises with random variables and masking or cuts. # # We can access the static shape with `Tensor.shape` # If the shape is known inside a graph, this will be the same. If the shape is unknown, the unknown axis will be None. @tf.function(autograph=False) def func_shape(x): print(f"static shape: {x.shape}") # static shape tf.print('dynamic shape ',tf.shape(x)) # dynamic shape x = x[x>3.5] print(f"static shape cuts applied: {x.shape}") # static shape tf.print('dynamic shape cuts applied',tf.shape(x)) # dynamic shape func_shape(rnd1) # We can access the axes by indexing rnd3 = rnd1[None, :] * rnd1[:, None] rnd3 tf.shape(rnd3) rnd3.shape[1] # ## Variables # # TensorFlow offers the possibility to have statefull objects inside a compiled graph (which e.g. is not possible with Numba). The most commonly used one is the `tf.Variable`. Technically, they are automatically captured on the function compilation and belong to it. var1 = tf.Variable(1.) @tf.function(autograph=False) def scale_by_var(x): print('running Python') tf.print("running TensorFlow") return x * var1 scale_by_var(tf.constant(1.)) scale_by_var(tf.constant(2.)) var1.assign(42.) scale_by_var(tf.constant(1.)) # As we see, the output changed. This is of course especially useful in the context of model fitting libraries, be it likelihoods or neural networks. def add_rnd(x): print('running Python') tf.print("running TensorFlow") rnd_np = np.random.uniform() rnd_tf = tf.random.uniform(shape=()) return x * rnd_np, x * rnd_tf add_rnd(tf.constant(1.)) add_rnd(tf.constant(2.)) # This means that we can use Numpy fully compatible in eager mode, but not when decorated. def try_np_sqrt(x): return np.sqrt(x) try_np_sqrt(tf.constant(5.)) try_np_sqrt_tf = tf.function(try_np_sqrt, autograph=False) # equivalent to decorator try: try_np_sqrt_tf(tf.constant(5.)) except NotImplementedError as error: print(error) # As we see, Numpy complains in the graph mode, given that it cannot handle the Symbolic Tensor. # Having the `tf.function` decorator means that we can't use any Python dynamicity. What fails when decorated but works nicely if not: def greater_python(x, y): if x > y: return True else: return False greater_python(tf.constant(1.), tf.constant(2.)) # This works again, and will fail with the graph decorator. greater_python_tf = tf.function(greater_python, autograph=False) try: greater_python_tf(tf.constant(1.), tf.constant(2.)) except Exception as error: print(error) # The error message hints at something: while this does not work now - Python does not yet now the value of the Tensors so it can't decide whether it will evaluate to True or False - there is the possibility of "autograph": it automatically converts (a subset) of Python to TensorFlow: while loops, for loops through Tensors and conditionals. However, this is usually less effective and more errorprone than using explicitly the `tf.*` functions. Lets try it! greater_python_tf_autograph = tf.function(greater_python, autograph=True) greater_python_tf_autograph(tf.constant(1.), tf.constant(2.)) # This now works neatless! But we're never sure. # # To do it explicitly, we can do that as well. code = tf.autograph.to_code(greater_python) print(code) # ## Performance # # In the end, this is what matters. And a comparison would be nice. Let's do that and see how Numpy and TensorFlow compare. nevents = 10000000 data_tf = tf.random.uniform(shape=(nevents,), dtype=tf.float64) data_np = np.random.uniform(size=(nevents,)) # + def calc_np(x): x_init = x i = 42. x = np.sqrt(np.abs(x_init * (i + 1.))) x = np.cos(x - 0.3) x = np.power(x, i + 1) x = np.sinh(x + 0.4) x = x ** 2 x = x / np.mean(x) x = np.abs(x) logx = np.log(x) x = np.mean(logx) x1 = np.sqrt(np.abs(x_init * (i + 1.))) x1 = np.cos(x1 - 0.3) x1 = np.power(x1, i + 1) x1 = np.sinh(x1 + 0.4) x1 = x1 ** 2 x1 = x1 / np.mean(x1) x1 = np.abs(x1) logx = np.log(x1) x1 = np.mean(logx) x2 = np.sqrt(np.abs(x_init * (i + 1.))) x2 = np.cos(x2 - 0.3) x2 = np.power(x2, i + 1) x2 = np.sinh(x2 + 0.4) x2 = x2 ** 2 x2 = x2 / np.mean(x2) x2 = np.abs(x2) logx = np.log(x2) x2 = np.mean(logx) return x + x1 + x2 calc_np_numba = numba.jit(nopython=True, parallel=True)(calc_np) # + def calc_tf(x): x_init = x i = 42. x = tf.sqrt(tf.abs(x_init * (tf.cast(i, dtype=tf.float64) + 1.))) x = tf.cos(x - 0.3) x = tf.pow(x, tf.cast(i + 1, tf.float64)) x = tf.sinh(x + 0.4) x = x ** 2 x = x / tf.reduce_mean(x) x = tf.abs(x) x = tf.reduce_mean(tf.math.log(x)) x1 = tf.sqrt(tf.abs(x_init * (tf.cast(i, dtype=tf.float64) + 1.))) x1 = tf.cos(x1 - 0.3) x1 = tf.pow(x1, tf.cast(i + 1, tf.float64)) x1 = tf.sinh(x1 + 0.4) x1 = x1 ** 2 x1 = x1 / tf.reduce_mean(x1) x1 = tf.abs(x1) x2 = tf.sqrt(tf.abs(x_init * (tf.cast(i, dtype=tf.float64) + 1.))) x2 = tf.cos(x2 - 0.3) x2 = tf.pow(x2, tf.cast(i + 1, tf.float64)) x2 = tf.sinh(x2 + 0.4) x2 = x2 ** 2 x2 = x2 / tf.reduce_mean(x2) x2 = tf.abs(x2) return x + x1 + x2 calc_tf_func = tf.function(calc_tf, autograph=False) # - # %%timeit -n1 -r1 # compile time, just for curiosity calc_tf_func(data_tf) # %%timeit -n1 -r1 # compile time, just for curiosity calc_np_numba(data_np) # %timeit calc_np(data_np) # not compiled # %timeit calc_tf(data_tf) # not compiled # %%timeit -n1 -r7 calc_np_numba(data_np) # %%timeit -n1 -r7 calc_tf_func(data_tf) # We can now play around with this numbers. Depending on the size (we can go up to 10 mio) and parallelizability of the problem, the numbers differ.. # # In general: # - Numpy is faster for small numbers # - TensorFlow is faster for larger arrays and well parallelizable computations. Due to the larger overhead in dispatching in eager mode, it is significantly slower for very small (1-10) sample sizes. # # => there is no free lunch # # Note: this has not run on a GPU, which would automatically happen for TensorFlow. # + def calc_tf2(x, n): sum_init = tf.zeros_like(x) for i in range(1, n + 1): x = tf.sqrt(tf.abs(x * (tf.cast(i, dtype=tf.float64) + 1.))) x = tf.cos(x - 0.3) x = tf.pow(x, tf.cast(i + 1, tf.float64)) x = tf.sinh(x + 0.4) x = x ** 2 x = x / tf.reduce_mean(x, axis=None) x = tf.abs(x) x = x - tf.reduce_mean(tf.math.log(x, name="Jonas_log"), name="Jonas_mean") # name for ops, see later ;) sum_init += x return sum_init calc_tf_func2 = tf.function(calc_tf2, autograph=False) @numba.njit(parallel=True) # njit is equal to jit(nopython=True), meaning "compile everything or raise error" def calc_numba2(x, n): sum_init = np.zeros_like(x) for i in range(1, n + 1): x = np.sqrt(np.abs(x * (i + 1.))) x = np.cos(x - 0.3) x = np.power(x, i + 1) x = np.sinh(x + 0.4) x = x ** 2 x = x / np.mean(x) x = np.abs(x) x = x - np.mean(np.log(x)) sum_init += x return sum_init # - # %%timeit -n1 -r1 #compile calc_numba2(rnd1_big.numpy(), 1) calc_numba2(rnd1_big.numpy(), 1) # %%timeit -n1 -r1 #compile calc_tf_func2(rnd1_big, 1) calc_tf_func2(rnd1_big, 1) # %%timeit calc_numba2(rnd1_big.numpy(), 1) # %%timeit calc_tf_func2(rnd1_big, 1) calc_tf_func2(rnd1_big, 10) calc_numba2(rnd1_big.numpy(), 10) # %%timeit calc_numba2(rnd1_big.numpy(), 10) # %%timeit calc_tf_func2(rnd1_big, 10) # ## Control flow # # While TensorFlow is independent of the Python control flow, it has its own functions for that, mainly: # - while_loop(): a while loop taking a body and condition function # - cond(): if-like # - case and switch_case: if/elif statements # - tf.where # + def true_fn(): return 1. def false_fn(): return 0. value = tf.cond(tf.greater(111., 42.), true_fn=true_fn, false_fn=false_fn) # - value # ### While loops # # We can create while loops in order to have some kind of repetitive task # + def cond(x, y): return x > y def body(x, y): return x / 2, y + 1 x, y = tf.while_loop(cond=cond, body=body, loop_vars=[100., 1.]) # - x, y # ### map a function # # We can also map a function on each element. While this is not very efficient, it allows for high flexibility. # %%timeit -n1 -r1 tf.map_fn(tf.math.sin, rnd1_big) # %%timeit -n1 -r1 tf.vectorized_map(tf.math.sin, rnd1_big) # can speedup things sometimes # + @tf.function(autograph=False) def do_map(func, tensor): return tf.map_fn(func, tensor) do_map(tf.math.sin, rnd1_big) # + @tf.function(autograph=False) def do_map_vec(func, tensor): return tf.vectorized_map(func, tensor) do_map_vec(tf.math.sin, rnd1_big) # - # %%timeit do_map(tf.math.sin, rnd1_big) # %%timeit do_map_vec(tf.math.sin, rnd1_big) # %%timeit tf.math.sin(rnd1_big) # As we can see, the generic mapping is surely not optimal. However, it works "always". `vectorized_map` on the other hand has a huge speedup and performs nearly as well as using the native function! However, while this works nicely for this case, it's applications are limited and depend heavily on the use-case; more complicated examples can easily result in a longer runtime and a huge memory consumption. Caution is therefore advised when using this function. # ## Gradients # # TensorFlow allows us to calculate the automatic gradients. var2 = tf.Variable(2.) with tf.GradientTape() as tape: tape.watch(var2) # actually watches all variables already by default y = var2 ** 3 y grad = tape.gradient(y, var2) grad # ## Tasks to try out # # Following are a few ideas to check whether you understand things # # - can you get the second derivative? play around ;) # - write a shape that you know as a function # - create the MC integral of it over a certain range # This allows to do many things with gradients and e.g. solve differential equations. # # # ## Bonus: the graph # # We talked about the graph back and forth, but _where is it_ ? # # The graph can be retained from a function that was already traced. concrete_func = calc_tf_func2.get_concrete_function(rnd1, 2) concrete_func graph = concrete_func.graph graph ops = graph.get_operations() ops log_op = ops[-6] log_op log_op.outputs op_inputs_mean = ops[-4].inputs op_inputs_mean log_op.outputs[0] is op_inputs_mean[0] # The output of the log operation is the input to the mean operation! We can just walk along the graph here. TensorFlow Graphs are no magic, they are simple object that store their input, their output, their operation. That's it!
tutorial1_HPC/python_hpc_TensorFlow.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.5.0 # language: julia # name: julia-0.5 # --- # # JULIA MPI First Example: pi computaton # First step was to load MPI on my mac. Seems mpich and openmpi are two reasonable choices # with probably no beginner's reason to prefer one over the other. <br> # # I did <t> brew install gcc </t> first to get the gcc compiler. I ran into problems. # The magic thing that told me what to do was <t> brew doctor </t>. It wanted me to type # <t> xcode-select --install </t> and when I did, all was good. I then typed # <t> brew install mpich </t> and mpi was just working. # My first example was to reproduce <a href="http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src/pi/C/solution.html"> # the classic mypi </a> in the notebook if !isdir(Pkg.dir("MPI")) Pkg.add("MPI"); end using MPI m = MPIManager(np=4) addprocs(m) #@mpi_do m comm = MPI.COMM_WORLD @mpi_do m comm = MPI.COMM_WORLD # # Enter number of intervals, and tell every processor # Traditional MPI would do this with a BCAST @mpi_do m n = 45 # Let's see if the processors got it @mpi_do m println(n) # my MPI id @mpi_do m myid = MPI.Comm_rank(comm) @mpi_do m println(myid) # Get the number of processors @mpi_do m np = MPI.Comm_size(comm) @mpi_do m println(np) # Compute $\int_0^1 4/(1+x^2) dx= 4 atan(x)]_0^1$ which evaluates to $\pi$ using Interact @time @mpi_do m begin n = 50_000_000 comm = MPI.COMM_WORLD s = 0.0 for i = MPI.Comm_rank(comm) + 1 : MPI.Comm_size(comm) : n x = (i - .5)/n s += 4/(1 + x^2) end mypi = s/n our_ฯ€ = MPI.Reduce(mypi, MPI.SUM, 0, comm) if myid==0 println(our_ฯ€ - ฯ€) end end @fetchfrom 4 our_ฯ€, ฯ€ # + function f_serial() n = 50_000_000 h = 1/n our_ฯ€ = 0.0 for i = 0:h:1 our_ฯ€ += 4/(1 + i^2) end our_ฯ€*h end function f_serial2(n) our_ฯ€ = 0.0 for i = 1:n x = (i - 0.5)/n our_ฯ€ += 4/(1 + x^2) end our_ฯ€/n end # - f_serial() #warmup @time f_serial() f_serial2(50_000_000) #warmup @time f_serial2(50_000_000) @time f_par(50_000_000) function f_par(n) @mpi_do m begin comm = MPI.COMM_WORLD s = 0.0 for i = MPI.Comm_rank(comm) + 1 : MPI.Comm_size(comm) : $n x = (i - .5)/$n s += 4/(1 + x^2) end mypi = s/$n our_ฯ€ = MPI.Reduce(mypi, MPI.SUM, 0, comm) #if myid==0 # println(our_ฯ€ - ฯ€) # end end @fetchfrom 2 our_ฯ€ end @mpi_do m function _pi_sum_par(n) comm = MPI.COMM_WORLD s = 0.0 for i = MPI.Comm_rank(comm) + 1 : MPI.Comm_size(comm) : n x = (i - .5)/n s += 4/(1 + x^2) end mypi = s/n our_ฯ€ = MPI.Reduce(mypi, MPI.SUM, 0, comm) return our_ฯ€ end function f_par2(n) @mpi_do m _pi_sum_par($n) @fetchfrom 2 our_ฯ€ end f_par(50_000_000) #warmup @time f_par(50_000_000) f_par2(50_000_000) #warmup @time f_par2(50_000_000) f(100) f(1000) f(10000) @manipulate for k=(3:10) f(10^k) end ฯ€ [f_par(10^k) for k=3:9]-ฯ€ rmprocs(m)
lectures/other/2.%2520Using%2520MPI%2520from%2520Julia.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 # --- # + tags=["remove-cell"] import pandas as pd from myst_nb import glue # - # # Aim # # This project explores the historical population of horses in Canada # between 1906 and 1972 for each province. # Data # # Horse population data were sourced from the [Government of Canada's Open Data website](http://open.canada.ca/en/open-data). # Specifically, (Government of Canada, 2017)1 and (Government of Canada, 2017)2. # Methods # # The R programming language (R Core Team, 2019) and the following R packages were used # to perform the analysis: knitr (Xie, 2014), tidyverse (Wickham, 2017), and # bookdown (Xie, 2016) # _Note: this report is adapted from (Timbers, 2020)._ # Results # ```{figure} ../../results/horse_pops_plot.png # --- # name: # --- # # # ``` # Fig. 1 Horse populations for all provinces in Canada from 1906 - 1972 # # We can see from Fig. 1 # that Ontario, Saskatchewan and Alberta have had the highest horse populations in Canada. # All provinces have had a decline in horse populations since 1940. # This is likely due to the rebound of the Canadian automotive # industry after the Great Depression and the Second World War. # An interesting follow-up visualisation would be car sales per year for each # Province over the time period visualised above to further support this hypothesis. # + horses_sd = pd.read_csv("../../results/horses_sd.csv") largest_sd_prov = str(horses_sd['Province'][0]) glue("largest-sd-prov", largest_sd_prov) horses_sd_noindex = horses_sd.style.hide_index() glue("horses-tbl", horses_sd_noindex) # - # Suppose we were interested in looking in more closely at the # province with the highest spread (in terms of standard deviation) # of horse populations. We present the standard deviations here: # # ```{glue:figure} horses-tbl # --- # figwidth: 500px # name: horses-tbl-fig # --- # # # ``` # Table 1: Standard deviation of number of horses for each province between 1940 - 1972 # # # Note that we define standard deviation (of a sample) as: # # $$s = sqrt{sum_{i = 1}^n(x_i - \bar{x})} / {n-1}.$$ # # Additionally, note that in Fig 2. we # consider the sample standard deviation of the number of horses # during the same time span as Fig. 1. # :::{figure-md} # <img src="../../results/horse_pop_plot_largest_sd.png" width="200px"> # # Horse populations for the province with the largest standard deviation # ::: # # In {numref}`Fig. {number} <largest-sd-province-plot>` we zoom in # on the province of ?, which had the largest spread of values in # terms of standard deviation. #
doc/jbook_example/_build/jupyter_execute/jbook_example.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 # --- help(round) round(-2281.125,-1) help(print) planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] for planet in planets: print(planet, end=' ') # + def is_leap(year): leap = False if 2100%4==0: leap=True return leap # - is_leap(2100) # + # Python Program to Print Natural Numbers from 1 to N number = int(input("Please Enter any Number: ")) print("The List of Natural Numbers from 1 to {0} are".format(number)) for i in range(1, number + 1): print (i, end = ' ') # -
notebook/python_objects.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 # --- # ## Basic types some_fraction = 0.75 num_persons = 13 some_statement = True complex_number = 2+3j greeting = "hello everybody!" # ## Printing print(greeting) print("number of persons:", num_persons) # ## Conditionals if some_statement: print("this statement is true") else: print("this statement is false") if num_persons > 10: print("many people showed up!") # ## Lists, dictionaries, and tuples # + # lists numbers = [1, 1, 2, 3, 5, 8, 13] flavors = ["vanilla", "chocolate", "lemon", "strawberry"] # dictionaries fav_icecream = {"radovan": "lemon", "alice": "chocolate", "bob": "vanilla"} print(fav_icecream["alice"]) num_electrons = {"O": 8, "Ne": 10} num_electrons["H"] = 1 # tuples coordinates = (0.0, 2.0, 1.5) # - # ## Loops for flavor in flavors: print(f"{flavor} icecream is yum") # ## Equations # # $f(x) = a x^3 + b x^2 + c x + d$ # ## Functions def myfun(x, coef): a, b, c, d = coef return a*x*x*x + b*x*x + c*x + d # ## Importing packages and functions # + import numpy as np xs = np.linspace(-10, 10, 20) print(xs) print(list(xs)) # + # also speak about version dependencies import matplotlib.pyplot as plt # make sure we see it on this notebook # %matplotlib inline coef = (-0.2, 1.0, 0.5, 1.5) ys = [] for x in xs: ys.append(myfun(x, coef)) plt.plot(xs, ys) plt.show() # - # ?np.*poly* # + # np.polyfit? # - coefficients = np.polyfit(xs, ys, 3) print(coefficients) # ## Discuss order of execution and state num_persons = 3 # ## Example with an interactive widget # + import numpy as np from ipywidgets import interact import matplotlib.pyplot as plt # %matplotlib inline def gaussian(x, a, b, c): return a * np.exp(-b * (x-c)**2) def noisy_gaussian(): # gaussian array y in interval -5 <= x <= 5 nx = 100 x = np.linspace(-5.0, 5.0, nx) y = gaussian(x, a=2.0, b=0.5, c=1.5) noise = np.random.normal(0.0, 0.2, nx) y += noise return x, y def fit(x, y, n): pfit = np.polyfit(x, y, n) yfit = np.polyval(pfit, x) return yfit def plot(x, y, yfit): plt.plot(x, y, "r", label="Data") plt.plot(x, yfit, "b", label="Fit") plt.legend() plt.ylim(-0.5, 2.5) plt.show() x, y = noisy_gaussian() @interact def slider(n=(3, 30)): yfit = fit(x, y, n) plot(x, y, yfit) # -
python-quickstart.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_ext autoreload # %autoreload 2 import numpy as np import matplotlib.pyplot as plt from matplotlib import rc from matplotlib.cm import get_cmap import pickle import os font = {'family' : 'sans-serif', 'size' : 12} rc('font', **font) import sys sys.path.insert(0,'..') from mavd.callbacks import * # + list_proms = ['Global', 'Average', 'Weighted\nsum'] list_level1 = ['car','bus','motorcycle'] list_level2 = ['engine','brakes','wheel','comp.'] list_level3 = ['car\nengine','car\nwheel', 'bus\nengine', 'bus\nbrakes','bus\ncompressor','bus\nwheel', 'motorcycle\nengine', 'motorcycle\nbrakes'] list_total1 = list_level1 + list_proms list_total2 = list_level2 + list_proms list_total3 = list_level3 + list_proms # + expfolder_RF = '../exps/RandomForest/' with open(os.path.join(expfolder_RF, 'results_evaluation.pickle'), 'rb') as fp: results_RF = pickle.load(fp, encoding='latin1') RF = {} RF['level1'] = {} RF['level2'] = {} RF['level3'] = {} RF['level1']['ER'] = np.concatenate((results_RF['nivel1']['ER'],results_RF['nivel1']['promsER'])) RF['level2']['ER'] = np.concatenate((results_RF['nivel2']['ER'],results_RF['nivel2']['promsER'])) RF['level3']['ER'] = np.concatenate((results_RF['nivel3']['ER'],results_RF['nivel3']['promsER'])) RF['level1']['F1'] = np.concatenate((results_RF['nivel1']['F1'],results_RF['nivel1']['promsF1'])) RF['level2']['F1'] = np.concatenate((results_RF['nivel2']['F1'],results_RF['nivel2']['promsF1'])) RF['level3']['F1'] = np.concatenate((results_RF['nivel3']['F1'],results_RF['nivel3']['promsF1'])) # + expfolder_CNN = '../exps/S-CNN_fine_tuning/' with open(os.path.join(expfolder_CNN, 'results.pickle'), 'rb') as fp: results_CNN = pickle.load(fp, encoding='latin1') lists_levels = [list_level1, list_level2, list_level3] levels = ['level1', 'level2', 'level3'] CNN = {} for i, level in enumerate(levels): CNN[level] = {} y = results_CNN["test"]['y'][i] predicted = results_CNN["test"]['predicted'][i] ER_classes = np.zeros((len(lists_levels[i]))) F1_classes = np.zeros((len(lists_levels[i]))) for c in range(len(lists_levels[i])): ER_classes[c] = ER(y[:,c],predicted[:,c]) F1_classes[c] = F1(y[:,c],predicted[:,c]) if c==0: ER_global = ER(y,predicted) F1_global = F1(y,predicted) ER_average = np.mean(ER_classes) F1_average = np.mean(F1_classes) # weigths for Weighted Sum w = np.sum(y,axis=0) w[w==0] = np.amin(w[np.nonzero(w)]) w = 1/w/np.sum(1/w) ER_weighted = np.sum(ER_classes*w) F1_weighted = np.sum(F1_classes*w) proms_ER = [ER_global, ER_average, ER_weighted] proms_F1 = [F1_global, F1_average, F1_weighted] CNN[level]['ER'] = np.concatenate((ER_classes,proms_ER)) CNN[level]['F1'] = np.concatenate((F1_classes,proms_F1)) # + plt.figure(figsize=(12,6)) cmap = get_cmap('viridis') c0 = cmap(0.1) c1 = cmap(0.3) c2 = cmap(0.5) c3 = cmap(0.55) c4 = cmap(0.8) ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0), colspan=2) #fig, ax1 = plt.subplots() ax1.set_title('Vehicles level') ax1.bar(np.arange(len(list_total1))-0.4, CNN['level1']['F1']*100, width=0.4,color=c1, tick_label=list_total1) ax1.bar(np.arange(len(list_total1)), RF['level1']['F1'], width=0.4,color=c3, tick_label=list_total1) ax1.set_xticks(np.arange(len(list_total1))-0.2) ax1.plot([2.3,2.3],[0,90],'k--',linewidth=2.0) rect1 = matplotlib.patches.Rectangle((2.3,0), 3.3, 90, color='gray', alpha=0.3) ax1.add_patch(rect1) ax1.set_ylabel('F1 (%)') ax1.set_ylim([0,90]) ax1.grid() ax2.set_title('Components level') ax2.bar(np.arange(len(list_total2))-0.4, CNN['level2']['F1']*100, width=0.4,color=c1, tick_label=list_total2) ax2.bar(np.arange(len(list_total2)), RF['level2']['F1'], width=0.4,color=c3, tick_label=list_total2) ax2.set_xticks(np.arange(len(list_total2))-0.2) ax2.set_ylabel('F1 (%)') ax2.plot([3.3,3.3],[0,90],'k--',linewidth=2.0) rect1 = matplotlib.patches.Rectangle((3.3,0), 3.3, 90, color='gray', alpha=0.3) ax2.add_patch(rect1) ax2.set_ylim([0,90]) ax2.grid() ax3.set_title('Subordinate level') ax3.bar(np.arange(len(list_total3))-0.4, CNN['level3']['F1']*100, width=0.4,color=c1, tick_label=list_total3, label='S-CNN (FT)') ax3.bar(np.arange(len(list_total3)), RF['level3']['F1'], width=0.4,color=c3, tick_label=list_total3, label='Random Forest') ax3.set_xticks(np.arange(len(list_total3))-0.2) ax3.set_ylabel('F1 (%)') ax3.plot([7.3,7.3],[0,90],'k--',linewidth=2.0) ax3.legend(loc='upper right') rect1 = matplotlib.patches.Rectangle((7.3,0), 4, 90, color='gray', alpha=0.3) ax3.add_patch(rect1) ax3.set_ylim([0,90]) ax3.grid() plt.tight_layout() #plt.savefig("compare_results_MAVD.png", dpi=300) plt.show() # -
notebooks/05_compare_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 # --- # + from sklearn.preprocessing import MinMaxScaler import os import numpy as np import pandas as pd import time import random import matplotlib.pyplot as plt import seaborn as sns sns.set() # - def softmax(z): assert len(z.shape) == 2 s = np.max(z, axis=1) s = s[:, np.newaxis] e_x = np.exp(z - s) div = np.sum(e_x, axis=1) div = div[:, np.newaxis] return e_x / div df = pd.read_csv('FB.csv') df.head() parameters = [df['Close'].tolist(), df['Volume'].tolist()] def get_state(parameters, t, window_size = 20): outside = [] d = t - window_size + 1 for parameter in parameters: block = ( parameter[d : t + 1] if d >= 0 else -d * [parameter[0]] + parameter[0 : t + 1] ) res = [] for i in range(window_size - 1): res.append(block[i + 1] - block[i]) for i in range(1, window_size, 1): res.append(block[i] - block[0]) outside.append(res) return np.array(outside).reshape((1, -1)) # Our output size from `get_state` is 38. In this notebook, I only use `Close` and `Volume` parameters, you can choose any parameters you want from your DataFrame. # # After that, I want to add another parameters, my `inventory` size, mean of `inventory` and `capital`. # # Let say for an example, # ``` # inventory_size = 1 # mean_inventory = 0.5 # capital = 2 # last_state = 0 # ``` # # We have 3 actions, # # 1. `0` for do nothing. # 2. `1` for buy. # 3. `2` for sell. inventory_size = 1 mean_inventory = 0.5 capital = 2 concat_parameters = np.concatenate([get_state(parameters, 20), [[inventory_size, mean_inventory, capital]]], axis = 1) input_size = concat_parameters.shape[1] input_size # + class Deep_Evolution_Strategy: inputs = None def __init__( self, weights, reward_function, population_size, sigma, learning_rate ): self.weights = weights self.reward_function = reward_function self.population_size = population_size self.sigma = sigma self.learning_rate = learning_rate def _get_weight_from_population(self, weights, population): weights_population = [] for index, i in enumerate(population): jittered = self.sigma * i weights_population.append(weights[index] + jittered) return weights_population def get_weights(self): return self.weights def train(self, epoch = 100, print_every = 1): lasttime = time.time() for i in range(epoch): population = [] rewards = np.zeros(self.population_size) for k in range(self.population_size): x = [] for w in self.weights: x.append(np.random.randn(*w.shape)) population.append(x) for k in range(self.population_size): weights_population = self._get_weight_from_population( self.weights, population[k] ) rewards[k] = self.reward_function(weights_population) rewards = (rewards - np.mean(rewards)) / (np.std(rewards) + 1e-7) for index, w in enumerate(self.weights): A = np.array([p[index] for p in population]) self.weights[index] = ( w + self.learning_rate / (self.population_size * self.sigma) * np.dot(A.T, rewards).T ) if (i + 1) % print_every == 0: print( 'iter %d. reward: %f' % (i + 1, self.reward_function(self.weights)) ) print('time taken to train:', time.time() - lasttime, 'seconds') class Model: def __init__(self, input_size, layer_size, output_size): self.weights = [ np.random.rand(input_size, layer_size) * np.sqrt(1 / (input_size + layer_size)), np.random.rand(layer_size, output_size) * np.sqrt(1 / (layer_size + output_size)), np.zeros((1, layer_size)), np.zeros((1, output_size)), ] def predict(self, inputs): feed = np.dot(inputs, self.weights[0]) + self.weights[-2] decision = np.dot(feed, self.weights[1]) + self.weights[-1] return decision def get_weights(self): return self.weights def set_weights(self, weights): self.weights = weights # - class Agent: POPULATION_SIZE = 15 SIGMA = 0.1 LEARNING_RATE = 0.03 def __init__(self, model, timeseries, skip, initial_money, real_trend, minmax): self.model = model self.timeseries = timeseries self.skip = skip self.real_trend = real_trend self.initial_money = initial_money self.es = Deep_Evolution_Strategy( self.model.get_weights(), self.get_reward, self.POPULATION_SIZE, self.SIGMA, self.LEARNING_RATE, ) self.minmax = minmax self._initiate() def _initiate(self): # i assume first index is the close value self.trend = self.timeseries[0] self._mean = np.mean(self.trend) self._std = np.std(self.trend) self._inventory = [] self._capital = self.initial_money self._queue = [] self._scaled_capital = self.minmax.transform([[self._capital, 2]])[0, 0] def reset_capital(self, capital): if capital: self._capital = capital self._scaled_capital = self.minmax.transform([[self._capital, 2]])[0, 0] self._queue = [] self._inventory = [] def trade(self, data): """ you need to make sure the data is [close, volume] """ scaled_data = self.minmax.transform([data])[0] real_close = data[0] close = scaled_data[0] if len(self._queue) >= window_size: self._queue.pop(0) self._queue.append(scaled_data) if len(self._queue) < window_size: return { 'status': 'data not enough to trade', 'action': 'fail', 'balance': self._capital, 'timestamp': str(datetime.now()), } state = self.get_state( window_size - 1, self._inventory, self._scaled_capital, timeseries = np.array(self._queue).T.tolist(), ) action, prob = self.act_softmax(state) print(prob) if action == 1 and self._scaled_capital >= close: self._inventory.append(close) self._scaled_capital -= close self._capital -= real_close return { 'status': 'buy 1 unit, cost %f' % (real_close), 'action': 'buy', 'balance': self._capital, 'timestamp': str(datetime.now()), } elif action == 2 and len(self._inventory): bought_price = self._inventory.pop(0) self._scaled_capital += close self._capital += real_close scaled_bought_price = self.minmax.inverse_transform( [[bought_price, 2]] )[0, 0] try: invest = ( (real_close - scaled_bought_price) / scaled_bought_price ) * 100 except: invest = 0 return { 'status': 'sell 1 unit, price %f' % (real_close), 'investment': invest, 'gain': real_close - scaled_bought_price, 'balance': self._capital, 'action': 'sell', 'timestamp': str(datetime.now()), } else: return { 'status': 'do nothing', 'action': 'nothing', 'balance': self._capital, 'timestamp': str(datetime.now()), } def change_data(self, timeseries, skip, initial_money, real_trend, minmax): self.timeseries = timeseries self.skip = skip self.initial_money = initial_money self.real_trend = real_trend self.minmax = minmax self._initiate() def act(self, sequence): decision = self.model.predict(np.array(sequence)) return np.argmax(decision[0]) def act_softmax(self, sequence): decision = self.model.predict(np.array(sequence)) return np.argmax(decision[0]), softmax(decision)[0] def get_state(self, t, inventory, capital, timeseries): state = get_state(timeseries, t) len_inventory = len(inventory) if len_inventory: mean_inventory = np.mean(inventory) else: mean_inventory = 0 z_inventory = (mean_inventory - self._mean) / self._std z_capital = (capital - self._mean) / self._std concat_parameters = np.concatenate( [state, [[len_inventory, z_inventory, z_capital]]], axis = 1 ) return concat_parameters def get_reward(self, weights): initial_money = self._scaled_capital starting_money = initial_money invests = [] self.model.weights = weights inventory = [] state = self.get_state(0, inventory, starting_money, self.timeseries) for t in range(0, len(self.trend) - 1, self.skip): action = self.act(state) if action == 1 and starting_money >= self.trend[t]: inventory.append(self.trend[t]) starting_money -= self.trend[t] elif action == 2 and len(inventory): bought_price = inventory.pop(0) starting_money += self.trend[t] invest = ((self.trend[t] - bought_price) / bought_price) * 100 invests.append(invest) state = self.get_state( t + 1, inventory, starting_money, self.timeseries ) invests = np.mean(invests) if np.isnan(invests): invests = 0 score = (starting_money - initial_money) / initial_money * 100 return invests * 0.7 + score * 0.3 def fit(self, iterations, checkpoint): self.es.train(iterations, print_every = checkpoint) def buy(self): initial_money = self._scaled_capital starting_money = initial_money real_initial_money = self.initial_money real_starting_money = self.initial_money inventory = [] real_inventory = [] state = self.get_state(0, inventory, starting_money, self.timeseries) states_sell = [] states_buy = [] for t in range(0, len(self.trend) - 1, self.skip): action, prob = self.act_softmax(state) print(t, prob) if action == 1 and starting_money >= self.trend[t] and t < (len(self.trend) - 1 - window_size): inventory.append(self.trend[t]) real_inventory.append(self.real_trend[t]) real_starting_money -= self.real_trend[t] starting_money -= self.trend[t] states_buy.append(t) print( 'day %d: buy 1 unit at price %f, total balance %f' % (t, self.real_trend[t], real_starting_money) ) elif action == 2 and len(inventory): bought_price = inventory.pop(0) real_bought_price = real_inventory.pop(0) starting_money += self.trend[t] real_starting_money += self.real_trend[t] states_sell.append(t) try: invest = ( (self.real_trend[t] - real_bought_price) / real_bought_price ) * 100 except: invest = 0 print( 'day %d, sell 1 unit at price %f, investment %f %%, total balance %f,' % (t, self.real_trend[t], invest, real_starting_money) ) state = self.get_state( t + 1, inventory, starting_money, self.timeseries ) invest = ( (real_starting_money - real_initial_money) / real_initial_money ) * 100 total_gains = real_starting_money - real_initial_money return states_buy, states_sell, total_gains, invest stocks = [i for i in os.listdir(os.getcwd()) if '.csv' in i and not 'TWTR' in i] stocks # I want to train on all stocks I downloaded except for Twitter. I want to use Twitter for testing. skip = 1 layer_size = 500 output_size = 3 window_size = 20 # + model = Model(input_size = input_size, layer_size = layer_size, output_size = output_size) agent = None for no, stock in enumerate(stocks): print('training stock %s'%(stock)) df = pd.read_csv(stock) real_trend = df['Close'].tolist() parameters = [df['Close'].tolist(), df['Volume'].tolist()] minmax = MinMaxScaler(feature_range = (100, 200)).fit(np.array(parameters).T) scaled_parameters = minmax.transform(np.array(parameters).T).T.tolist() initial_money = np.max(parameters[0]) * 2 if no == 0: agent = Agent(model = model, timeseries = scaled_parameters, skip = skip, initial_money = initial_money, real_trend = real_trend, minmax = minmax) else: agent.change_data(timeseries = scaled_parameters, skip = skip, initial_money = initial_money, real_trend = real_trend, minmax = minmax) agent.fit(iterations = 100, checkpoint = 10) print() # - # ### If you saw the whole training session on certain stocks are negatives (like FB), means that, that stock markets are losing very bad # + df = pd.read_csv('GOOG.csv') real_trend = df['Close'].tolist() parameters = [df['Close'].tolist(), df['Volume'].tolist()] minmax = MinMaxScaler(feature_range = (100, 200)).fit(np.array(parameters).T) scaled_parameters = minmax.transform(np.array(parameters).T).T.tolist() initial_money = np.max(parameters[0]) * 2 agent.change_data(timeseries = scaled_parameters, skip = skip, initial_money = initial_money, real_trend = real_trend, minmax = minmax) # - states_buy, states_sell, total_gains, invest = agent.buy() fig = plt.figure(figsize = (15, 5)) plt.plot(df['Close'], color='r', lw=2.) plt.plot(df['Close'], '^', markersize=10, color='m', label = 'buying signal', markevery = states_buy) plt.plot(df['Close'], 'v', markersize=10, color='k', label = 'selling signal', markevery = states_sell) plt.title('GOOG total gains %f, total investment %f%%'%(total_gains, invest)) plt.legend() plt.show() # + df = pd.read_csv('TWTR.csv') real_trend = df['Close'].tolist() parameters = [df['Close'].tolist(), df['Volume'].tolist()] minmax = MinMaxScaler(feature_range = (100, 200)).fit(np.array(parameters).T) scaled_parameters = minmax.transform(np.array(parameters).T).T.tolist() initial_money = np.max(parameters[0]) * 2 agent.change_data(timeseries = scaled_parameters, skip = skip, initial_money = initial_money, real_trend = real_trend, minmax = minmax) states_buy, states_sell, total_gains, invest = agent.buy() # - fig = plt.figure(figsize = (15, 5)) plt.plot(df['Close'], color='r', lw=2.) plt.plot(df['Close'], '^', markersize=10, color='m', label = 'buying signal', markevery = states_buy) plt.plot(df['Close'], 'v', markersize=10, color='k', label = 'selling signal', markevery = states_sell) plt.title('TWTR total gains %f, total investment %f%%'%(total_gains, invest)) plt.legend() plt.show() # + from datetime import datetime volume = df['Volume'].tolist() for i in range(100): print(agent.trade([real_trend[i], volume[i]])) # + import copy import pickle copy_model = copy.deepcopy(agent.model) with open('model.pkl', 'wb') as fopen: pickle.dump(copy_model, fopen) # -
realtime-agent/realtime-evolution-strategy.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/Dmitri9149/PyTorch-Transformer-from-scratch/blob/main/Basic_v3_Exp_PyTorch_Transformer_scratch_29_01_2021_13_01.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="7VikmcH3LPzT" outputId="c8813007-6a25-4a72-a1b0-aa2eb35707bb" # -U: Upgrade all packages to the newest available version # !pip install -U d2l # !pip install requests import requests from IPython import display from IPython.display import set_matplotlib_formats # %matplotlib inline from d2l import torch as d2l import math import torch from torch import nn from matplotlib import pyplot as plt import pandas as pd import os import time import hashlib import zipfile import collections from torch.utils import data from torch.utils.data import TensorDataset, DataLoader from torch import Tensor import torch.nn.functional as F import numpy as np from typing import Tuple, NewType, Union, Any, TypeVar from typing import Dict, List, Counter from matplotlib import pyplot as plt # + [markdown] id="7XlZJpKLsXY_" # - positional function coding_positionsA with delta = 10 shift 6 is used; FACTOR_B = 0.0 # - the dim of every of 4 heads is decreased from 64 to 16 (before concatenation). # -600 pairs, 200 epochs # + [markdown] id="ae8y13KXiiTP" # Some comments to the notebook: # - multihead attention -> separate independently formed heads # - no linear transformation for 'keys' in HeadAttention # - MultiHeadAttention module was changed # - PositionalEncoder is changed # - the notebook is for experiments, test code and comments are not # eliminated # - my comments are with 3 # -> ### mycomments # - code from d2l.ai project : https://github.com/d2l-ai/d2l-en and http://d2l.ai/index.htmlis is marked as ### from d2l.ai # - function for positional encoding : .... depend on notebook, see the code # + [markdown] id="IgoTqUjwwy-b" # Some functions to calculate the 'attention' # + id="trYktmNMoPjY" ### prediction of padding tokens should be excluded from loss calculations; ### this function mask irrelevant entries with zero values so later ### multiplication of any irrelevant prediction with zero equals to zero. ### modified code from d2l.ai def sequence_mask(X:Tensor, valid_len: Tensor, value: int = 0)-> Tensor: """Mask irrelevant entries in sequences.""" maxlen = X.size(1) mask = torch.arange((maxlen), dtype=torch.float32, device=X.device)[None, :] < valid_len[:, None] X[~mask] = value return X # + id="8kCHks3pL9N2" ### modified code from d2l.ai ### X: 3D Tensor of scores where some scores 'are not to be used', for ### example because corresponds to <pad> sequences ### or correspond to 'future' tokens in target sequenses (tokens in lang to which we translate) ### which can not be used for the prediction from the 'past' tokens to the moment ### X-> 3D Tensor : (batch_size, number of queries we use, number of key/value pairs) ### if masking is independent of a query we use to generate the sores -> valid_lens is 1D ### it happens in case of padding ### if masking depens on the query we use : valid _lens is 2D ### it happens in Decoder Blocks, where all queries have different 'past' and 'future' def masked_softmax(X: Tensor, valid_lens: Tensor) -> Tensor: """Perform softmax operation by masking elements on the last axis.""" # `X`: 3D tensor, `valid_lens`: 1D or 2D tensor if valid_lens is None: return F.softmax(X, dim=-1) else: shape = X.shape if valid_lens.dim() == 1: valid_lens = torch.repeat_interleave(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1) # On the last axis, replace masked elements with a very large negative # value, whose exponentiation outputs 0 X = sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6) return F.softmax(X.reshape(shape), dim=-1) # + id="dtVEFOMRMOTm" ### modified code from 2dl.ai class DotProductAttention(nn.Module): """Scaled dot product attention.""" def __init__(self, dropout, **kwargs): super(DotProductAttention, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) # Shape of `queries`: (`batch_size`, no. of queries, `d`) # Shape of `keys`: (`batch_size`, no. of key-value pairs, `d`) # Shape of `values`: (`batch_size`, no. of key-value pairs, value # dimension) # Shape of `valid_lens`: (`batch_size`,) or (`batch_size`, no. of queries) def forward(self, queries: Tensor, keys: Tensor, values: Tensor, valid_lens: Tensor=None) -> Tensor: d = queries.shape[-1] # Set `transpose_b=True` to swap the last two dimensions of `keys` scores = torch.bmm(queries, keys.transpose(1,2)) / math.sqrt(d) self.attention_weights = masked_softmax(scores, valid_lens) return torch.bmm(self.dropout(self.attention_weights), values) # + id="rO-UzzvFFu7I" ### to visualize the'attention' ### from d2l.ai def show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(3.5, 3.5), cmap='Reds'): d2l.use_svg_display() num_rows, num_cols = matrices.shape[0], matrices.shape[1] fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize, sharex=True, sharey=True, squeeze=False) for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)): for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)): pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap) if i == num_rows - 1: ax.set_xlabel(xlabel) if j == 0: ax.set_ylabel(ylabel) if titles: ax.set_title(titles[j]) fig.colorbar(pcm, ax=axes, shrink=0.6) # + [markdown] id="w_L77MGOy34-" # Transformer modules # + id="6FSMcqkPwzxh" ### one head module class AttentionHead(nn.Module): def __init__(self, key_size: int, query_size: int, value_size: int, dropout: float, bias: float): super().__init__() self.attention = DotProductAttention(dropout) self.W_q = nn.Linear(query_size, key_size, bias=bias) self.W_v = nn.Linear(value_size,16, bias=bias) def forward(self, queries: Tensor, keys: Tensor, values: Tensor, valid_lens: Tensor) -> Tensor: queries = self.W_q(queries) keys = keys values = self.W_v(values) return self.attention(queries, keys, values, valid_lens) # + id="kQyzdWyYmePU" ### num_hiddens : the size of the vector which represent token after the ### output from the forward function of the module; ### or in another way: size of tokens after the MultiHeadAttention module class MultiHeadAttention(nn.Module): def __init__(self, key_size: int, query_size: int, value_size: int, num_hiddens: int, num_heads: int, dropout: float, bias: float=False, **kwargs): super(MultiHeadAttention, self).__init__(**kwargs) self.num_heads = num_heads self.heads = nn.ModuleList( [AttentionHead(key_size, query_size, value_size, dropout, bias) for _ in range(num_heads)] ) self.W_o = nn.Linear(16*self.num_heads, num_hiddens,bias=bias) def forward(self, queries: Tensor, keys: Tensor, values: Tensor, valid_lens: Tensor) -> Tensor: return self.W_o( torch.cat([h(queries, keys, values, valid_lens) for h in self.heads], dim=-1) ) # + colab={"base_uri": "https://localhost:8080/"} id="VL6h0gmQQJHI" outputId="576ec821-b7eb-4f88-bb33-b8ecd7a05310" ### here the position wector is random vector of 0 and 1 (normilized) POS = ((torch.FloatTensor(10,8).uniform_() > 0.6)).float() SUM_POS = torch.sum(POS, dim =1).reshape(-1,1) SUM_POS # + colab={"base_uri": "https://localhost:8080/"} id="0fwIAk4m_giI" outputId="ea72393f-41aa-464d-d150-0dad01856f98" POS # + colab={"base_uri": "https://localhost:8080/"} id="txjxXrhQ-jac" outputId="91cbe8ed-f151-4dd0-f575-bbe4e850babd" NORMALIZED_POS = POS / SUM_POS NORMALIZED_POS # + id="bgyq3tH8KKty" ###################### end of test # + [markdown] id="rUXRpEITOptA" # Position encoding functions # + id="vU6KHdyegCJa" def indicator(x): if (x == 0): z = 0 else: z = 1 return z # + id="FJ7oSx4ZQEOn" ### we have sequence of tokens with length num_steps ### we have siz eof every token : num_hiddens ### have to make positional encoding functional with output num_hiddens ### to code positions in our sequence def coding_positionsA(factor, num_steps, num_hiddens, delta, shift): full_steps = num_hiddens //delta remainder = num_hiddens % delta ### num_hiddens = full * num_steps + reminder pos = torch.zeros(num_steps,num_hiddens).float() max_steps= full_steps + indicator(remainder) for i in range(num_steps): for j in range(i*shift, min(num_hiddens, i*shift +delta)): pos[i,j]=torch.tensor(1.) sums = torch.sum(pos, dim =1).reshape(-1,1) pos = (pos / sums)* torch.tensor(factor) return pos # + colab={"base_uri": "https://localhost:8080/"} id="LnmKmha8U47S" outputId="6fc6bb3a-8edb-44fb-c3c6-d4cdd88ddd47" coding_positionsA(1.,10,64,10,6) # + id="l39AVapt2MMa" ### STOP # + id="zmt4gA1YEIr9" ### encode positions in the sequence 0,..., max - 1 ### max correspond to max num tokens in the sentences ### here max = 10 , for 0 -> 1 and for 9 -> -1 def positions(n: int, max : int = 10) -> float: x = ((5. - n * (max)/(max -1)) / max) * 2. return x # + colab={"base_uri": "https://localhost:8080/"} id="BLfiZMQKGTBb" outputId="3c6d4cc4-9c29-4ec5-9499-ac7b44957b63" print(positions(0), positions(9)) # + id="ijxTVmyFobfq" class PositionalEncoding(nn.Module): def __init__(self, num_hiddens: int, dropout: float, max_len: int=1000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(dropout) ### create long enought 'positions' (first axis) with 0 s and 1 s in second axis ### digital parameter ->'propability' of 0 value in the sequence with length = num_hiddens ### FACTOR_A = 0. ### self.positions = ((torch.FloatTensor(max_len,num_hiddens).uniform_() > FACTOR_A)/num_hiddens).double() ### sums = torch.sum(self.positions, dim =1).reshape(-1,1) #### self.positions = (self.positions / sums) * FACTOR_B ### self.positions = torch.zeros(max_len, num_hiddens) ### for i in range(num_hiddens): ### self.positions[:,i] = positions(i) # Create a long enough `P` self.P = torch.zeros((1, max_len, num_hiddens)) ### self.P[:,:,:] = self.positions ###============================================================================== FACTOR_B = 0.0 delta, shift, num_steps = (10 , 6 , 10) ###============================================================================= for i in range(num_steps): for j in range(num_hiddens): self.P[:, i, j]= coding_positionsA(FACTOR_B,num_steps, num_hiddens, delta, shift)[i,j] def forward(self, X: Tensor)-> Tensor: ### X = X X = X + self.P[:, :X.shape[1], :].to(X.device) ### print(torch.sum(X, dim = 2)[0,0]) return self.dropout(X) # + id="KiV4lijdi9OM" ### from d2l.ai class PositionWiseFFN(nn.Module): def __init__(self, ffn_num_input, ffn_num_hiddens, ffn_num_outputs, **kwargs): super(PositionWiseFFN, self).__init__(**kwargs) self.dense1 = nn.Linear(ffn_num_input, ffn_num_hiddens) self.relu = nn.ReLU() self.dense2 = nn.Linear(ffn_num_hiddens, ffn_num_outputs) def forward(self, X): return self.dense2(self.relu(self.dense1(X))) # + id="u0-lSGi-jDK1" ### from d2l.ai class AddNorm(nn.Module): def __init__(self, normalized_shape, dropout, **kwargs): super(AddNorm, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) self.ln = nn.LayerNorm(normalized_shape) def forward(self, X, Y): return self.ln(self.dropout(Y) + X) # + id="zo-mxZGRzVUu" ### from d2l.ai class Encoder(nn.Module): """The base encoder interface for the encoder-decoder architecture.""" def __init__(self, **kwargs): super(Encoder, self).__init__(**kwargs) def forward(self, X, *args): raise NotImplementedError # + id="Pqb12RQgze7J" ### from d2l.ai class Decoder(nn.Module): """The base decoder interface for the encoder-decoder architecture.""" def __init__(self, **kwargs): super(Decoder, self).__init__(**kwargs) def init_state(self, enc_outputs, *args): raise NotImplementedError def forward(self, X, state): raise NotImplementedError # + id="V-be2vHezmyT" ### from d2l.ai class EncoderDecoder(nn.Module): """The base class for the encoder-decoder architecture.""" def __init__(self, encoder, decoder, **kwargs): super(EncoderDecoder, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder def forward(self, enc_X, dec_X, *args): enc_outputs = self.encoder(enc_X, *args) dec_state = self.decoder.init_state(enc_outputs, *args) return self.decoder(dec_X, dec_state) # + id="J0hOwoZVjH_w" ### from d2l.ai class EncoderBlock(nn.Module): def __init__(self, key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, dropout, use_bias=False, **kwargs): super(EncoderBlock, self).__init__(**kwargs) self.attention = MultiHeadAttention( key_size, query_size, value_size, num_hiddens, num_heads, dropout, use_bias) self.addnorm1 = AddNorm(norm_shape, dropout) self.ffn = PositionWiseFFN( ffn_num_input, ffn_num_hiddens, num_hiddens) self.addnorm2 = AddNorm(norm_shape, dropout) def forward(self, X, valid_lens): Y = self.addnorm1(X, self.attention(X, X, X, valid_lens)) return self.addnorm2(Y, self.ffn(Y)) # + id="9AO6AFvjjNCx" ### from d2l.ai class TransformerEncoder(Encoder): def __init__(self, vocab_size, key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, num_layers, dropout, use_bias=False, **kwargs): super(TransformerEncoder, self).__init__(**kwargs) self.num_hiddens = num_hiddens self.embedding = nn.Embedding(vocab_size, num_hiddens) self.pos_encoding = PositionalEncoding(num_hiddens, dropout) self.blks = nn.Sequential() for i in range(num_layers): self.blks.add_module("block"+str(i), EncoderBlock(key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, dropout, use_bias)) def forward(self, X, valid_lens, *args): # Since positional encoding values are between -1 and 1, the embedding # values are multiplied by the square root of the embedding dimension # to rescale before they are summed up X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens)) ### self.attention_weights = [None] * len(self.blks) for i, blk in enumerate(self.blks): X = blk(X, valid_lens) ### self.attention_weights[ ### i] = blk.attention.attention.attention_weights return X # + id="whrei-_cjT_Z" ### from d2l.ai class DecoderBlock(nn.Module): # The `i`-th block in the decoder def __init__(self, key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, dropout, i, **kwargs): super(DecoderBlock, self).__init__(**kwargs) self.i = i self.attention1 = MultiHeadAttention( key_size, query_size, value_size, num_hiddens, num_heads, dropout) self.addnorm1 = AddNorm(norm_shape, dropout) self.attention2 = MultiHeadAttention( key_size, query_size, value_size, num_hiddens, num_heads, dropout) self.addnorm2 = AddNorm(norm_shape, dropout) self.ffn = PositionWiseFFN(ffn_num_input, ffn_num_hiddens, num_hiddens) self.addnorm3 = AddNorm(norm_shape, dropout) def forward(self, X, state): enc_outputs, enc_valid_lens = state[0], state[1] # During training, all the tokens of any output sequence are processed # at the same time, so `state[2][self.i]` is `None` as initialized. # When decoding any output sequence token by token during prediction, # `state[2][self.i]` contains representations of the decoded output at # the `i`-th block up to the current time step if state[2][self.i] is None: key_values = X else: key_values = torch.cat((state[2][self.i], X), axis=1) state[2][self.i] = key_values if self.training: batch_size, num_steps, _ = X.shape # Shape of `dec_valid_lens`: (`batch_size`, `num_steps`), where # every row is [1, 2, ..., `num_steps`] dec_valid_lens = torch.arange( 1, num_steps + 1, device=X.device).repeat(batch_size, 1) else: dec_valid_lens = None # Self-attention X2 = self.attention1(X, key_values, key_values, dec_valid_lens) Y = self.addnorm1(X, X2) # Encoder-decoder attention. Shape of `enc_outputs`: # (`batch_size`, `num_steps`, `num_hiddens`) Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens) Z = self.addnorm2(Y, Y2) return self.addnorm3(Z, self.ffn(Z)), state # + id="C5zz9CmWo2dm" ### from d2l.ai class AttentionDecoder(Decoder): """The base attention-based decoder interface.""" def __init__(self, **kwargs): super(AttentionDecoder, self).__init__(**kwargs) @property def attention_weights(self): raise NotImplementedError # + id="_yDk-XiYjY7k" ### modified code from d2l.ai class TransformerDecoder(AttentionDecoder): def __init__(self, vocab_size, key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, num_layers, dropout, **kwargs): super(TransformerDecoder, self).__init__(**kwargs) self.num_hiddens = num_hiddens self.num_layers = num_layers self.embedding = nn.Embedding(vocab_size, num_hiddens) self.pos_encoding = PositionalEncoding(num_hiddens, dropout) self.blks = nn.Sequential() for i in range(num_layers): self.blks.add_module("block"+str(i), DecoderBlock(key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, dropout, i)) self.dense = nn.Linear(num_hiddens, vocab_size) def init_state(self, enc_outputs, enc_valid_lens, *args): return [enc_outputs, enc_valid_lens, [None] * self.num_layers] def forward(self, X, state): X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens)) ### self._attention_weights = [[None] * len(self.blks) for _ in range (2)] for i, blk in enumerate(self.blks): X, state = blk(X, state) # Decoder self-attention weights ### self._attention_weights[0][ ### i] = blk.attention1.attention.attention_weights # Encoder-decoder attention weights ### self._attention_weights[1][ ### i] = blk.attention2.attention.attention_weights return self.dense(X), state @property def attention_weights(self): return 0 # + [markdown] id="gg4PrzYQe99n" # Data Downloading and Reading from web and then from . # # The used data are bilingual sentence pairs from Tatoeba project : # http://www.manythings.org/anki/ # + id="bjbh90-YjZ_H" ### Each line in the dataset is a tab-delimited pair of an English text ### sequence and the translated French text sequence. ### Each text sequence can be just one sentence or a paragraph of multiple sentences. DATA_HUB = dict() DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/' DATA_HUB['fra-eng'] = (DATA_URL + 'fra-eng.zip', '94646ad1522d915e7b0f9296181140edcf86a4f5') # + id="2-XZXDJgjkxq" ### from d2l.a def read_data_nmt() -> str: """Load the English-French dataset.""" data_dir = download_extract('fra-eng') with open(os.path.join(data_dir, 'fra.txt'), 'r') as f: return f.read() # + id="0EOshC7Qkxty" ### from d2l.ai def download(name, cache_dir=os.path.join('..', 'data')): """Download a file inserted into DATA_HUB, return the local filename.""" assert name in DATA_HUB, f"{name} does not exist in {DATA_HUB}." url, sha1_hash = DATA_HUB[name] os.makedirs(cache_dir, exist_ok=True) fname = os.path.join(cache_dir, url.split('/')[-1]) if os.path.exists(fname): sha1 = hashlib.sha1() with open(fname, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) if sha1.hexdigest() == sha1_hash: return fname # Hit cache print(f'Downloading {fname} from {url}...') r = requests.get(url, stream=True, verify=True) with open(fname, 'wb') as f: f.write(r.content) return fname # + id="5dBPwb8rkcx3" ### from d2l.ai def download_extract(name, folder=None): """Download and extract a zip/tar file.""" fname = download(name) base_dir = os.path.dirname(fname) data_dir, ext = os.path.splitext(fname) if ext == '.zip': fp = zipfile.ZipFile(fname, 'r') elif ext in ('.tar', '.gz'): fp = tarfile.open(fname, 'r') else: assert False, 'Only zip/tar files can be extracted.' fp.extractall(base_dir) return os.path.join(base_dir, folder) if folder else data_dir # + colab={"base_uri": "https://localhost:8080/"} id="qtHexl-Xjy8M" outputId="4e6eb3de-51dd-4c73-82be-e5a0f9133359" ### data pairs for the translation looks like this: raw_text = read_data_nmt() ### raw_text: string print(raw_text[:500]) # + [markdown] id="xyrocGYdeFHT" # Vocabulary # + id="LVs3wylwwx5O" ### modified code form d2i.ai ### Union type; Union[X, Y] means either X or Y. ### tokens : list of strings OR list of list of strings def count_corpus(tokens: Union[List[str],List[List[str]]])-> Dict[str,int]: """Count token frequencies.""" # Here `tokens` is a 1D list or 2D list if len(tokens) == 0 or isinstance(tokens[0], list): # Flatten a list of token lists into a list of tokens tokens = [token for line in tokens for token in line] return collections.Counter(tokens) # + id="1HvazpkrKbbt" ############################ test # + colab={"base_uri": "https://localhost:8080/"} id="I_33usGN2wtF" outputId="f6e4bd51-ee67-4d5d-ff32-62493cc0f2a3" count_corpus(['asd', 'sss', 'iouyio', 'huhu', 'huhu']) # + colab={"base_uri": "https://localhost:8080/"} id="xidiz2h65__s" outputId="a253ee6b-f8ae-4255-81e5-2f56dde9766e" count_corpus([['aaa', 'bbb'], ['ccc', 'ddd','aaa']]) # + id="x7odGZmjKf3A" ####################################### end of test # + id="1ZenhDmzxjug" ### modified code from d2l.ai ### Union type; Union[X, Y] means either X or Y. ### tokens : 1D list of strings or 2D list of list of strings class Vocab: """Vocabulary for text.""" def __init__(self, tokens: Union[List[List[str]],List[str]] =None, min_freq: int =0, reserved_tokens: List[str]=None): if tokens is None: tokens = [] if reserved_tokens is None: reserved_tokens = [] # Sort according to frequencies counter = count_corpus(tokens) ### the list below is sorted basing on freqs of tokens ### self.token_freqs: List[Tuple(str,int)] = sorted(counter.items(), self.token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True) # The index for the unknown token is 0 self.unk: int = 0 uniq_tokens: List[str] = ['<unk>'] + reserved_tokens uniq_tokens += [ token for token, freq in self.token_freqs if freq >= min_freq and token not in uniq_tokens] self.idx_to_token: List[str] = [] self.token_to_idx: Dict[str,int] = dict() ### self.idx_to_token, self.token_to_idx = [], dict() for token in uniq_tokens: self.idx_to_token.append(token) self.token_to_idx[token] = len(self.idx_to_token) - 1 def __len__(self) -> int: return len(self.idx_to_token) def __getitem__(self, tokens: Union[Any, List[str], Tuple[str]] ) -> Union[str, List[str]]: if not isinstance(tokens, (list, tuple)): return self.token_to_idx.get(tokens, self.unk) return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices: Union[int, List[int], Tuple[int]] )-> Union[int, List[int]]: if not isinstance(indices, (list, tuple)): return self.idx_to_token[indices] return [self.idx_to_token[index] for index in indices] # + id="EfS1b1RiKji8" ################################# test # + id="VIZXOpUaJDOT" tokens_a = [['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him'], ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and'], ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']] # + id="f46fWyNCJOjN" vocab_a = Vocab(tokens_a) # + colab={"base_uri": "https://localhost:8080/"} id="uGpzygq-Kd_W" outputId="31136351-46a4-4a90-c67d-6ae898dca22d" print(vocab_a.token_to_idx.items()) # + colab={"base_uri": "https://localhost:8080/"} id="vAcWogEnaecT" outputId="b715c975-008a-40a9-8231-9f4aa880595d" print(vocab_a.token_freqs) # + colab={"base_uri": "https://localhost:8080/"} id="jqs79Sf5Nt0X" outputId="edd09758-896a-4fe4-908c-f53d4900b0ff" for i in [0, 2]: print('words:', tokens_a[i]) ### supply list of 'keys' where 'keys' are tokens: strings print('indices:', vocab_a[tokens_a[i]]) # + colab={"base_uri": "https://localhost:8080/"} id="p8dhUEgYSE8D" outputId="85a9d811-0678-46b2-8e49-a7016bc212dd" vocab_a['time'] # + colab={"base_uri": "https://localhost:8080/"} id="jTvf7_ALSfuC" outputId="77446169-5155-46bf-fe9c-272873c2f4dd" vocab_a['jjjj'] # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="VlIwb96acpH3" outputId="b8da7381-f105-4180-d3d7-f874ae5b3923" vocab_a.to_tokens(2) # + colab={"base_uri": "https://localhost:8080/"} id="SwAHGHepc01T" outputId="e68e154c-a93a-4ed0-f69f-b6ff6e7b9b96" vocab_a.to_tokens([1,2,3]) # + id="04u3hiSLhTdf" ### vocab_a.to_tokens(2.6) -> error # + colab={"base_uri": "https://localhost:8080/"} id="R-EbPlvWdELO" outputId="1d51e3b7-b116-4909-c4f4-85054779639e" vocab_a.__getitem__(('and','ffff','the')) # + colab={"base_uri": "https://localhost:8080/"} id="AYnbqo4tgPs7" outputId="6ae13769-8bcc-48f3-f731-8d5605b6f3a2" vocab_a.__getitem__(['and','ffff','the']) # + colab={"base_uri": "https://localhost:8080/"} id="Ymn-5l5dgV6b" outputId="5ccaf303-651f-498c-bd5a-d9ed45a36ad7" vocab_a.__getitem__('and') # + colab={"base_uri": "https://localhost:8080/"} id="w168c-80gbjp" outputId="0a4bbbf9-8e29-4e2e-cc6f-e726eeaf8764" vocab_a.__getitem__(vocab_a) ### not an error !!! # + colab={"base_uri": "https://localhost:8080/"} id="uOPpkl6RVcPw" outputId="b2605cac-279d-4540-a032-7e1c8f563bbe" vocab_a.__getitem__(count_corpus) ### not an error !! # + id="nIzJ7_5l0IVj" ### vocab_a.__getitem__(count_corpus) ### not an error !! # + id="g0I-Uun70N5Z" ### vocab_a.__getitem__(dddd) ###error !! because the 'dddd' name is not defined # + id="cHU9N-yrKoSu" ################################## end of test # + [markdown] id="wqLKfZ1E73Ol" # # Text preprocessing , tokenization. # # Preprocess the text which was read from a file. Tokenize it. # + id="MdWaMa7f2i_0" #### preprocessing of the raw text as a 'one big string' ### modified code from from d2l.ai def preprocess_nmt(text: str) -> str: """Preprocess the English-French dataset.""" ### Python has no type 'char' here 'str' correspond to str of length 1 ### here 'char: str' has type we will get after enumerate(text) def no_space(char: str, prev_char: str) -> bool: return char in set(',.!?') and prev_char != ' ' # Replace non-breaking space with space, and convert uppercase letters to # lowercase ones text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower() # Insert space between words and punctuation marks out = [ ' ' + char if i > 0 and no_space(char, text[i - 1]) else char for i, char in enumerate(text)] return ''.join(out) # + id="BGBpgOPY4W13" ### tokenize the preprocessed text ### modified code form d2l.ai def tokenize_nmt(text:str, num_examples: int=None) -> Tuple[List[List[str]], List[List[str]]]: """Tokenize the English-French dataset.""" source, target = [], [] for i, line in enumerate(text.split('\n')): if num_examples and i > num_examples: break parts = line.split('\t') if len(parts) == 2: source.append(parts[0].split(' ')) target.append(parts[1].split(' ')) return source, target # + [markdown] id="RD2pf265eAvr" # Dataset for translation. # Functions for processing of arrays of tokens/indices # Truncate/pad , adding "\<eos>" token etc... # # + id="WFrF_FcN7v2Q" ### trancate and pad the list of tokens (where token is a string) ### modified code from d2l.ai def truncate_pad(line:List[int], num_steps:int, padding_token: str) -> List[int]: """Truncate or pad sequences.""" if len(line) > num_steps: return line[:num_steps] # Truncate return line + [padding_token] * (num_steps - len(line)) # Pad # + id="QrLzDXR6IeK1" ### modified code from d2l.ai ### ppend the โ€œ<eos>โ€ (end of sequence) token to the end of every sequence ### to indicate the end of the sequence. ### when a model is predicting by generating a sequence token after token, ### the generation of the โ€œ<eos>โ€ token can indicates that the output sequence is complete. ### in 'valid_len' we record the length of each text sequence excluding the padding tokens. ### after the <eos> addition we make trancate_pad(lines) def build_array_nmt(lines: List[List[str]], vocab, num_steps: int) -> Tuple[Tensor,Tensor]: """Transform text sequences of machine translation into minibatches.""" lines = [vocab[l] for l in lines] lines = [l + [vocab['<eos>']] for l in lines] array = torch.tensor( [truncate_pad(l, num_steps, vocab['<pad>']) for l in lines]) valid_len = (array != vocab['<pad>']).type(torch.int32).sum(1) return array, valid_len # + [markdown] id="g9nNf1l7wtov" # load_data_nmt : # load_data_nmt function return the data iterator, together with the vocabs for both the source language and the target language : # - 1.preprocess the text as one string # - 2.tokenize # - 3.make Vocab # - 4.truncate/pad/<eos> # - 5.build iterator # + id="hcbn2oklXw_2" ### modified code from d2l.ai T_co = TypeVar('T_co', covariant=True) def load_array(data_arrays: List[Tensor], batch_size: int, is_train: bool=True) -> DataLoader[T_co]: """Construct a PyTorch data iterator.""" dataset = data.TensorDataset(*data_arrays) return data.DataLoader(dataset, batch_size, shuffle=is_train) # + id="iK6AdwDkXQqk" ### modified code from d2l.ai def load_data_nmt(batch_size: int, num_steps: int, num_examples: int=600) -> DataLoader[T_co]: """Return the iterator and the vocabularies of the translation dataset.""" text = preprocess_nmt(read_data_nmt()) source, target = tokenize_nmt(text, num_examples) src_vocab = Vocab(source, min_freq=2, reserved_tokens=['<pad>', '<bos>', '<eos>']) tgt_vocab = Vocab(target, min_freq=2, reserved_tokens=['<pad>', '<bos>', '<eos>']) src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps) tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps) data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len) data_iter = load_array(data_arrays, batch_size) return data_iter, src_vocab, tgt_vocab # + id="dbPFJ1IOtNkh" ### the blue scores, to estimate the quality of translation ### from d2l.ai def bleu(pred_seq, label_seq, k): """Compute the BLEU.""" pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ') len_pred, len_label = len(pred_tokens), len(label_tokens) score = math.exp(min(0, 1 - len_label / len_pred)) for n in range(1, k + 1): num_matches, label_subs = 0, collections.defaultdict(int) for i in range(len_label - n + 1): label_subs[''.join(label_tokens[i:i + n])] += 1 for i in range(len_pred - n + 1): if label_subs[''.join(pred_tokens[i:i + n])] > 0: num_matches += 1 label_subs[''.join(pred_tokens[i:i + n])] -= 1 score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n)) return score # + id="EltJSzp0C2GW" ### from d2l.ai def try_gpu(i=0): """Return gpu(i) if exists, otherwise return cpu().""" if torch.cuda.device_count() >= i + 1: return torch.device(f'cuda:{i}') return torch.device('cpu') # + id="qzkDUvp1-qo6" ### from d2l.ai class MaskedSoftmaxCELoss(nn.CrossEntropyLoss): """The softmax cross-entropy loss with masks.""" # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`) # `label` shape: (`batch_size`, `num_steps`) # `valid_len` shape: (`batch_size`,) def forward(self, pred, label, valid_len): weights = torch.ones_like(label) weights = sequence_mask(weights, valid_len) self.reduction='none' unweighted_loss = super(MaskedSoftmaxCELoss, self).forward( pred.permute(0, 2, 1), label) weighted_loss = (unweighted_loss * weights).mean(dim=1) return weighted_loss # + id="wPyHQm8TkWoQ" ### regulate the value of gradient, too big gradient is not allowed ### from d2l.ai def grad_clipping(net, theta): """Clip the gradient.""" if isinstance(net, nn.Module): params = [p for p in net.parameters() if p.requires_grad] else: params = net.params norm = torch.sqrt(sum(torch.sum((p.grad**2)) for p in params)) if norm > theta: for param in params: param.grad[:] *= theta / norm # + id="AKtMLTbZk30s" ### accumulate date in training process ### from d2l.ai class Accumulator: """For accumulating sums over `n` variables.""" def __init__(self, n): self.data = [0.0] * n def add(self, *args): self.data = [a + float(b) for a, b in zip(self.data, args)] def reset(self): self.data = [0.0] * len(self.data) def __getitem__(self, idx): return self.data[idx] # + id="o_tFmOBLuQfb" ### from d2l.ai def use_svg_display(): """Use the svg format to display a plot in Jupyter.""" display.set_matplotlib_formats('svg') # + id="U0Krqruxxhze" ### from d2l.ai def set_figsize(figsize=(3.5, 2.5)): """Set the figure size for matplotlib.""" use_svg_display() plt.rcParams['figure.figsize'] = figsize # + id="To8SHbWrxpb8" ### from d2l.ai def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend): """Set the axes for matplotlib.""" axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_xscale(xscale) axes.set_yscale(yscale) axes.set_xlim(xlim) axes.set_ylim(ylim) if legend: axes.legend(legend) axes.grid() # + id="krPOBKc3x3Mo" def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None): """Plot data points.""" if legend is None: legend = [] set_figsize(figsize) axes = axes if axes else plt.gca() # Return True if `X` (tensor or list) has 1 axis def has_one_axis(X): return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list) and not hasattr(X[0], "__len__")) if has_one_axis(X): X = [X] if Y is None: X, Y = [[]] * len(X), X elif has_one_axis(Y): Y = [Y] if len(X) != len(Y): X = X * len(Y) axes.cla() for x, y, fmt in zip(X, Y, fmts): if len(x): axes.plot(x, y, fmt) else: axes.plot(y, fmt) set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend) # + id="LKVK7W8ckson" ### to plot data ### from d2l.ai class Animator: """For plotting data in animation.""" def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5)): # Incrementally plot multiple lines if legend is None: legend = [] use_svg_display() self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize) if nrows * ncols == 1: self.axes = [self.axes,] # Use a lambda function to capture arguments self.config_axes = lambda: set_axes(self.axes[ 0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend) self.X, self.Y, self.fmts = None, None, fmts def add(self, x, y): # Add multiple data points into the figure if not hasattr(y, "__len__"): y = [y] n = len(y) if not hasattr(x, "__len__"): x = [x] * n if not self.X: self.X = [[] for _ in range(n)] if not self.Y: self.Y = [[] for _ in range(n)] for i, (a, b) in enumerate(zip(x, y)): if a is not None and b is not None: self.X[i].append(a) self.Y[i].append(b) self.axes[0].cla() for x, y, fmt in zip(self.X, self.Y, self.fmts): self.axes[0].plot(x, y, fmt) self.config_axes() display.display(self.fig) display.clear_output(wait=True) # + id="zRtLAftglLl4" ### work with time ### from d2l.ai class Timer: """Record multiple running times.""" def __init__(self): self.times = [] self.start() def start(self): """Start the timer.""" self.tik = time.time() def stop(self): """Stop the timer and record the time in a list.""" self.times.append(time.time() - self.tik) return self.times[-1] def avg(self): """Return the average time.""" return sum(self.times) / len(self.times) def sum(self): """Return the sum of time.""" return sum(self.times) def cumsum(self): """Return the accumulated time.""" return np.array(self.times).cumsum().tolist() # + id="T8Dlv7N7BXPX" ### training function ### modified from d2l.ai def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device): """Train a model for sequence to sequence.""" def xavier_init_weights(m): if type(m) == nn.Linear: nn.init.xavier_uniform_(m.weight) net.apply(xavier_init_weights) net.to(device) optimizer = torch.optim.Adam(net.parameters(), lr=lr) loss = MaskedSoftmaxCELoss() net.train() animator = Animator(xlabel='epoch', ylabel='loss', xlim=[10, num_epochs]) for epoch in range(num_epochs): timer = Timer() metric =Accumulator(2) # Sum of training loss, no. of tokens for batch in data_iter: X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch] bos = torch.tensor([tgt_vocab['<bos>']] * Y.shape[0], device=device).reshape(-1, 1) dec_input =torch.cat([bos, Y[:, :-1]], 1) # Teacher forcing Y_hat, _ = net(X, dec_input, X_valid_len) l = loss(Y_hat, Y, Y_valid_len) l.sum().backward() # Make the loss scalar for `backward` grad_clipping(net, 1) num_tokens = Y_valid_len.sum() optimizer.step() with torch.no_grad(): metric.add(l.sum(), num_tokens) if (epoch + 1) % 10 == 0: animator.add(epoch + 1, (metric[0] / metric[1],)) print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} ' f'tokens/sec on {str(device)}') # + id="3KCPB3BNKsVk" ### new PositionalEncoding !!! (see code for exact function) ### new MultiHeadAttention !!! # + id="RedoUorNJIkM" ### from d2l.ai def try_gpu(i=0): """Return gpu(i) if exists, otherwise return cpu().""" if torch.cuda.device_count() >= i + 1: return torch.device(f'cuda:{i}') return torch.device('cpu') # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="xrl-0YJ5jfaV" outputId="7c1b06c9-a5d2-4eb3-be78-9a95a51c6ebb" num_hiddens, num_layers, dropout, batch_size, num_steps = 64, 2, 0.1, 64, 10 lr, num_epochs, device = 0.005, 200, try_gpu() ffn_num_input, ffn_num_hiddens, num_heads = 64, 64, 4 key_size, query_size, value_size = 64, 64, 64 norm_shape = [64] #### THE LAST PARAMETER IM load_data_nmt FUNCTION IS NUMBER OF SENTENCES FOR ### TRAINING train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size, num_steps,600) encoder = TransformerEncoder( len(src_vocab), key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, num_layers, dropout) decoder = TransformerDecoder( len(tgt_vocab), key_size, query_size, value_size, num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens, num_heads, num_layers, dropout) net = EncoderDecoder(encoder, decoder) train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device) # + id="JmnuGss0BMwQ" ### prediction ### from d2l.ai def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, device, save_attention_weights=False): """Predict for sequence to sequence.""" # Set `net` to eval mode for inference net.eval() src_tokens = src_vocab[src_sentence.lower().split(' ')] + [ src_vocab['<eos>']] enc_valid_len = torch.tensor([len(src_tokens)], device=device) src_tokens = truncate_pad(src_tokens, num_steps, src_vocab['<pad>']) # Add the batch axis enc_X = torch.unsqueeze( torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0) enc_outputs = net.encoder(enc_X, enc_valid_len) dec_state = net.decoder.init_state(enc_outputs, enc_valid_len) # Add the batch axis dec_X = torch.unsqueeze( torch.tensor([tgt_vocab['<bos>']], dtype=torch.long, device=device), dim=0) output_seq, attention_weight_seq = [], [] for _ in range(num_steps): Y, dec_state = net.decoder(dec_X, dec_state) # We use the token with the highest prediction likelihood as the input # of the decoder at the next time step dec_X = Y.argmax(dim=2) pred = dec_X.squeeze(dim=0).type(torch.int32).item() # Save attention weights (to be covered later) if save_attention_weights: attention_weight_seq.append(net.decoder.attention_weights) # Once the end-of-sequence token is predicted, the generation of the # output sequence is complete if pred == tgt_vocab['<eos>']: break output_seq.append(pred) return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq # + id="l1d85cISkE2n" colab={"base_uri": "https://localhost:8080/"} outputId="dd2c63ea-62d4-46f4-8e6d-63c7deaf85a7" engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .', 'got it !', 'hug me .'] fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .', 'j\'ai pigรฉ !', 'Serre-moi dans tes bras !'] for eng, fra in zip(engs, fras): translation, dec_attention_weight_seq = predict_seq2seq( net, eng, src_vocab, tgt_vocab, num_steps, device, True) print(f'{eng} => {translation}, ', f'bleu {bleu(translation, fra, k=2):.3f}') # + id="mvCvbT1TyrsN" ### from heylingo engs_heylingo = ['it is how it is .','i paid .','i can .', 'i\'m going out .', 'it is a book .', 'i need to know .', 'the man who saw us .', 'she works in an office .', 'a price war .', 'he is seen as a safe pair of hands .','the fighting continued all night .', 'it turned out all right in the end .'] fras_heylingo = ['c\'estcommeรงa .', 'j\โ€™ai payรฉ .', 'je peux .', 'je sors .', 'c\'est un livre .', 'je dois savoir .', 'l\โ€™homme qui nous a vus .', 'elle travaille dans un bureau .', 'une guerre des prix .', 'on le considรจre comme quelqu\โ€™un de sรปr .','les combats se sont poursuivis toute la nuit .','finalement tout s\โ€™est bien passรฉ .'] # + id="-cw7O6r91eLr" colab={"base_uri": "https://localhost:8080/"} outputId="f05dadda-299d-4e81-9b15-5e81a156ea8e" for eng, fra in zip(engs_heylingo, fras_heylingo): translation, dec_attention_weight_seq = predict_seq2seq( net, eng, src_vocab, tgt_vocab, num_steps, device, True) print(f'{eng} => {translation}, ', f'bleu {bleu(translation, fra, k=2):.3f}')
Basic_v3_Exp_PyTorch_Transformer_scratch_29_01_2021_13_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 (ipykernel) # language: python # name: python3 # --- # # Efficient hyperparameter search with GridSearchCV and optuna # # ``` # Authors: <NAME> # <NAME> # ``` # # adapted from the work of <NAME> and <NAME>. # %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Most models have hyperparameters that influence how complex functions they can learn. Think the depth of a decision tree. # <img src="figures/overfitting_underfitting_cartoon.svg" width="60%"> # ## Hyperparameters, Over-fitting, and Under-fitting # # Unfortunately, there is no general rule how to find the sweet spot, and so machine learning practitioners have to find the best trade-off of model-complexity and generalization by trying several hyperparameter settings. Hyperparameters are the internal knobs or tuning parameters of a machine learning algorithm (in contrast to model parameters that the algorithm learns from the training data -- for example, the weight coefficients of a linear regression model); the depth of a decision tree or the number of trees in a gradient boosting are such hyperparameters. # # Most commonly this "hyperparameter tuning" is done using a brute force search, for example over multiple values of ``max_depth``: # + import pandas as pd from sklearn.model_selection import cross_val_score, KFold from sklearn.tree import DecisionTreeRegressor print('Loading data...') # load or create your dataset df_train = pd.read_csv('datasets/regression.train', header=None, sep='\t') df_test = pd.read_csv('datasets/regression.test', header=None, sep='\t') df = pd.concat([df_train, df_test], axis=0) y = df[0].values X = df.drop(0, axis=1).values cv = KFold(shuffle=True, n_splits=5, random_state=42) reg = DecisionTreeRegressor() # for each parameter setting do cross-validation: for max_depth in [1, 3, 5, 10, 20]: reg.set_params(max_depth=max_depth) scores = cross_val_score(reg, X, y, cv=cv, scoring="r2") print(f"max_depth: {max_depth}, average score: {np.mean(scores)}") # - # There is a function in scikit-learn, called ``validation_plot`` to reproduce the cartoon figure above. It plots one parameter, such as the number of neighbors, against training and validation error (using cross-validation): # + from sklearn.model_selection import validation_curve max_depth = [1, 2, 3, 4, 5, 6, 7] train_scores, test_scores = validation_curve( reg, X, y, param_name="max_depth", param_range=max_depth, cv=cv, scoring="r2" ) plt.plot(max_depth, train_scores.mean(axis=1), label="train R2") plt.plot(max_depth, test_scores.mean(axis=1), label="test R2") plt.ylabel('R2') plt.xlabel('Tree depth') plt.xlim([1, max(max_depth)]) plt.legend(loc="best"); # - # To automate hyperparameter search there is a built-in class in scikit-learn, ``GridSearchCV``. ``GridSearchCV`` takes a dictionary that describes the parameters that should be tried and a model to train. # # The grid of parameters is defined as a dictionary, where the keys are the parameters and the values are the settings to be tested. # # To inspect training score on the different folds, the parameter ``return_train_score`` is set to ``True``. # + from sklearn.model_selection import GridSearchCV param_grid = {'max_depth': max_depth} grid = GridSearchCV(DecisionTreeRegressor(), param_grid=param_grid, cv=cv, verbose=3, return_train_score=True, n_jobs=-1) # - # One of the great things about GridSearchCV is that it is a *meta-estimator*. It takes an estimator like `DecisionTreeRegressor` above, and creates a new estimator, that behaves exactly the same - in this case, like a regressor. # So we can call ``fit`` on it, to train it: grid.fit(X, y) # What ``fit`` does is a bit more involved then what we did above. First, it runs the same loop with cross-validation, to find the best parameter combination. # Once it has the best combination, it runs fit again on all data passed to fit (without cross-validation), to built a single new model using the best parameter setting. # Then, as with all models, we can use ``predict`` or ``score``: # grid.predict(X) # You can inspect the best parameters found by ``GridSearchCV`` in the ``best_params_`` attribute, and the best score in the ``best_score_`` attribute: print(grid.best_score_) print(grid.best_params_) # But you can investigate the performance and much more for each set of parameter values by accessing the `cv_results_` attributes. The `cv_results_` attribute is a dictionary where each key is a string and each value is array. It can therefore be used to make a pandas DataFrame. type(grid.cv_results_) print(grid.cv_results_.keys()) # + import pandas as pd cv_results = pd.DataFrame(grid.cv_results_) cv_results.head() # - cv_results_tiny = cv_results[['param_max_depth', 'mean_test_score']] cv_results_tiny.sort_values(by='mean_test_score', ascending=False).head() # There is a problem with using this score for evaluation, however. You might be making what is called a **multiple hypothesis testing error**. If you try very many parameter settings, some of them will work better just by chance, and the score that you obtained might not reflect how your model would perform on new unseen data. # Therefore, it is good to split off a separate test-set before performing grid-search. This pattern can be seen as a training-validation-test split, and is common in machine learning: # <img src="figures/grid_search_cross_validation.svg" width="70%"> # We can do this very easily by splitting of some test data using ``train_test_split``, training ``GridSearchCV`` on the training set, and applying the ``score`` method to the test set: # + from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) param_grid = {'max_depth': max_depth} cv = KFold(n_splits=10, shuffle=True) grid = GridSearchCV(DecisionTreeRegressor(), param_grid=param_grid, cv=cv) grid.fit(X_train, y_train) grid.score(X_test, y_test) # - # We can also look at the parameters that were selected: grid.best_params_ # Some practitioners go for an easier scheme, splitting the data simply into three parts, training, validation and testing. This is a possible alternative if your training set is very large, or it is infeasible to train many models using cross-validation because training a model takes very long. # You can do this with scikit-learn for example by splitting of a test-set and then applying GridSearchCV with ShuffleSplit cross-validation with a single iteration: # # <img src="figures/train_validation_test2.svg" width="60%"> # + from sklearn.model_selection import train_test_split, ShuffleSplit X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) param_grid = {'max_depth': max_depth} single_split_cv = ShuffleSplit(n_splits=1, test_size=0.2) grid = GridSearchCV(DecisionTreeRegressor(), param_grid=param_grid, cv=single_split_cv, verbose=3) grid.fit(X_train, y_train) grid.score(X_test, y_test) # - # This is much faster, but it might result in worse hyperparameters and therefore worse results as the error estimate on left-out data will have much more variance. In other words you're more likely to be unlucky! # <div class="alert alert-success"> # <b>EXERCISE</b>: # <ul> # <li> # Apply grid-search to find the best learning_rate and number of tree in a HistGradientBoostingRegressor. # </li> # </ul> # </div> # # Solution is in: `solutions/03-gbdt_grid_search_cv.py` from sklearn.ensemble import HistGradientBoostingRegressor # ## Guided hyper-optimization # Hyper-optimization of parameters was done up to now by giving some values to be tried. Usually, we could automatically generated those values (randomly or not) by using `RandomSearchCV` or `GridSearchCV`. # # We could do a little be better by trying some parameters which we could consider more probable to optimize our problem depending on the previous parameters which we used before. # # We will use `optuna` to do so. # # # URL : https://pypi.org/project/optuna/ # # See video : https://www.youtube.com/watch?v=J_aymk4YXhg # + import optuna from optuna import samplers def objective(trial): max_depth = trial.suggest_int('max_depth', 2, 32) learning_rate = trial.suggest_loguniform('learning_rate', 10**-5, 10**0) l2_regularization = trial.suggest_loguniform('l2_regularization', 10**-5, 10**0) min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 100) max_iter = trial.suggest_int('max_iter', 10, 1000) reg = HistGradientBoostingRegressor( **trial.params, random_state=42, ) return np.mean(cross_val_score(reg, X_train, y_train, cv=5, n_jobs=-1, scoring="r2")) sampler = samplers.TPESampler(seed=10) study = optuna.create_study(sampler=sampler, direction='maximize') optuna.logging.disable_default_handler() # limit verbosity study.optimize(objective, n_trials=10) # Show best result print(study.best_trial.params) print(study.best_trial.value) # - values = [t.value for t in study.trials] plt.plot(values) values = [t.value for t in study.trials] values = [np.max(values[:k]) for k in range(1, len(values))] plt.plot(values) plt.xlabel('Trials') plt.ylabel('R2') reg = HistGradientBoostingRegressor(random_state=42) reg.set_params(**study.best_trial.params) reg.fit(X_train, y_train) reg.score(X_test, y_test) # <div class="alert alert-success"> # <b>EXERCISE</b>: # <ul> # <li> # How would you avoid optimizing the <code>max_iter</code> parameter? # </li> # </ul> # </div> # # Solution is in `solutions/03-gbdt_optuna.py` # To learn more please have a look at the doc of optuna. In particular: # # https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html#optuna.study.Study.optimize
10_hyperparameter_optimization/01-model_selection_grid_search_optuna.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 # --- # # Lab 10: Central limit theorem, change detection, multidimensional Gaussian distribution # %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy as sp import scipy.stats as st from scipy.stats import multivariate_normal print ('Modules Imported!') # ## Gaussian Distribution and the Central Limit Theorem: # The Gaussian distribution (also known as the normal distribution) is a continuous type distribution and has a pdf defined by $f(u)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{(u-\mu)^2}{2\sigma^2}\right)$. The mean is given by $\mu$ and the variance is given by $\sigma^2$. Below is a graph of the pdf and the CDF of the standard Gaussian ($\mu=0, \sigma^2=1$). As shown in your probability course, the CDF is simply the integral of the pmf. Let $X \sim Gauss(0,1)$. $P\{X\le c\}=\Phi(c)=\int^c_{-\infty} f(u)\,du$ This is known as the Phi function, but often the complementary CDF, or Q function, is used. $Q(c)=P\{X\ge c\}=\int^{\infty}_c f(u)\,du = 1-\Phi(c) = \Phi(-c)$. X = st.norm() x = np.linspace(-10,10,1000) plt.plot(x,X.pdf(x)) plt.title('pdf of standard Gaussian') plt.figure() plt.plot(x,X.cdf(x)) plt.title('CDF of standard Gaussian') # We can also shift and stretch the Gaussian. Notice how the scaling changes when we change the mean and standard deviation. X = st.norm(3,4) x = np.linspace(-10,10,1000) plt.plot(x,X.pdf(x)) plt.title('pdf of N(3,4) Gaussian') plt.figure() plt.plot(x,X.cdf(x)) plt.title('CDF of N(3,4) Gaussian') # The Gaussian distribution is one of the most frequently used distributions due to the central limit theorem (CLT). To discuss the CLT, we begin with the law of large numbers (LLN). The LLN, roughly speaking, tells us that if $X_1, X_2, \cdots $ is a sequence of independent and identically distributed random variables with mean $\mu$, and if $S_n =X_1+X_2+\cdots+X_n,$ then, with probability one, $\lim_{n\to\infty}\frac{S_n}{n}=\mu$. This gives rise to the practical approximation, $S_n \approx n \mu.$ For example, if we roll a fair die 1000 times, the sum of the numbers rolled should be approximately 3,500. # # The CLT gives an important refinement on the LLN. Roughly speaking, it tells us that $S_n$ as just described tends to have a Gaussian distribution. If each $X_k$ has mean $\mu$ and variance $\sigma^2,$ then $S_n$ has mean $n\mu$ and variance $n\sigma^2.$ Therefore, the standardized version of $S_n$ is $\frac{S_n-n\mu}{\sqrt{n\sigma^2}}.$ The CLT states that for any constant $c,$ # $$ # \lim_{n\to\infty} P\left\{ \frac{S_n-n\mu}{\sqrt{n\sigma^2}} \leq c \right\} = \Phi(c) # $$ # In practice, this gives the Gaussian approximation: $S_n$ approximately has the # Gaussian (same as normal) distribution with parameters $n\mu$ and # variance $n\sigma^2.$ # # # In order to visualize this, let's look at sums of Bernoulli random variables. Suppose we have $n$ indpendent Bernoulli random variables, $X_1,X_2,\cdots,X_n$, each with parameter $p$. Recall that the Bernoulli distribution has a mean of $\mu_X=p$ and a variance of $\sigma_X^2=p(1-p)$. The sum of these random variables, of course, has the the binomial distribution with parameters $n$ and $p$. That is, $S_n=(X_1+X_2+\cdots+X_n) \sim Bin(n,p)$. If we standardize our binomial (using $\mu = np, \sigma^2 = np(1-p)$) we find the following: # # $ \frac{S_n-np}{\sqrt{np(1-p)}}=\frac{S_n-np}{\sqrt{n}\sqrt{p(1-p)}} = \frac{S_n-n\mu_X}{\sqrt{n}\sigma_X}$ # # By the central limit theorem, the distribution of this goes to the standard normal distribution as n goes to infinity. (This was the first example of the CLT discovered, and is called the DeMoivre-Laplace limit theorem.) # <br>**<SPAN style="BACKGROUND-COLOR: #C0C0C0">Problem 1:</SPAN>** Show graphically that as $n$ becomes large, the distribution of the sum of $n$ i.i.d. Bernoulli random variables converges to the normal distribution. To do this use n = 50 and $p = 0.4.$ # # 1. Overlay a plot of the pmf of the binomial distribution versus the pdf of a normal distribution with the same mean and variance. Your pmf should be discrete. # 2. Overlay a plot of the CDF of the binomial distribution versus the CDF of a normal distribution with the same mean and variance. # 3. Comment on what happens as you change $n.$ # + # Your code here # - # __Answer:__ (Your answer here) # **<SPAN style="BACKGROUND-COLOR: #C0C0C0">End of Problem 1</SPAN>** # Another way to view the central limit theorem is through statistics. Suppose we have any discrete distribution. For instance, let's go back to our apocalyptic zombie scenario from Lab 6. Recall that the pmf of the number of zombies getting into a building in a given night has the distribution: # # $P\{Z = 5\} = .05$ # # $P\{Z = 3\} = .1$ # # $P\{Z = 2\} = .25$ # # $P\{Z = 1\} = .2$ # # $P\{Z = 0\} = .05$ # # $P\{Z = -2\} = .2$ # # $P\{Z = -3\} = .1$ # # $P\{Z = -4\} = .05$ # # We're assuming that this pmf is the same each night. Suppose that an anti-Zombie coalition has been formed across campus and includes 150 buildings (all with the same distribution). One of the survivors just happens to be a statistician who wants to assess the campus's survival capability. He goes to each building each night for twenty nights, and observes how many zombies enter. For each building he calculates the average number of Zombies per night that he saw enter the building. This results in 150 averages of 20 random variates each. # # <br>**<SPAN style="BACKGROUND-COLOR: #C0C0C0">Problem 2:</SPAN>** # # 1. Create a histogram of the averages across the buildings with the number of bins being equal to the square root of the number of buildings. # 2. Answer the following questions: Is your histogram approximately normally distributed? What happens as you increase the number of buildings? What happens as you increase the number of nights observed? # + # Your code here # - # __Answer__: (Your answer here) # **<SPAN style="BACKGROUND-COLOR: #C0C0C0">End of Problem 2</SPAN>** # ## Change Detection: # Often complex systems or machines have sensors to monitor the health of the machine. The sensor outputs might be modeled as iid with some pmf $p_o$ as long as the system is in good condition, and iid with some other pmf $p_1$ if the system has changed in some way (such as system failure, intruder present, etc). A detection rule observes the data and raises the alarm at some time $\tau.$ Ideally the alarm time $\tau$ is always greater than, but not much greater than, the system change time. One approach to this problem is to fix a window length $W$ and divide time into a sequence of nonoverlapping time windows. At the end of each window we perform a binary hypothesis test to decide if the data in the window was generated by $p_0$ # or $p_1.$ If the decision is to decide in favor of $p_1$ the alarm is raised, so that $\tau$ is the time at the end of the window. This scenario is simulated below. Try running the simulation muliple times. Try experimenting by varying the detection threshold and window size. You might notice that sometimes the log likelihood ratio crosses above the threshold in the middle of a window, but the alarm isn't sounded because the likelihood ratio is tested only at the end of a window. # + # Window method for change detection N_max=1000 # maximum number of observations allowed gamma=np.random.randint(0,700) # time of system change W=30 # window length, initally W=30 threshold=5.0 # detection threshold, initally 5.0 p0=np.array([0.2,0.2,0.4,0.2]) p1=np.array([0.4,0.3,0.2,0.1]) if np.size(p0)!=np.size(p1): print ("warning, p0 and p1 have different sizes") # Observations will have pmf p0 for times 1 through gamma - 1, pmf p1 afterwards def f(i): return np.log(p1[i]/p0[i]) c=np.arange(np.size(p0)) Xcstm0 = st.rv_discrete(values=(c,p0)) # scipy.stats object for distibution p0 Xcstm1 = st.rv_discrete(values=(c,p1)) # scipy.stats object for distibution p1 variates=np.column_stack([Xcstm0.rvs(size=N_max),Xcstm1.rvs(size=N_max)]) #Nmax x 2 array log_LR=np.zeros(N_max+1) # log_LR will store the sequence of log likelihood ratios t=0 alarm_flag=0 while (t<N_max-1): t=t+1 if t<gamma: log_LR[t]=log_LR[t-1]+f(variates[t,0]) else: log_LR[t]=log_LR[t-1]+f(variates[t,1]) if t % W==0: # if t is a multiple of W, time to do an LRT if log_LR[t] > threshold: alarm_flag=1 alarm_time=t break else: # Reset LR log_LR[t]=0. print ("Window Size=",W,"LRT threshold=",threshold) if alarm_flag==0: print ("Time N_max reached with no alarm") else: if (alarm_time < gamma): print ("False alarm at time", alarm_time) else: print ("System change detected with time to detection", alarm_time-gamma) plt.plot(log_LR[0:alarm_time+50]) plt.plot(gamma,0,'ro') # Time of system change indicated by red dot plt.plot(alarm_time,0,'go') # Alarm time indicated by green dot plt.title('cumulative log likelihood ratio within windows vs. time') plt.ylabel('log likelihood') plt.xlabel('time') # - # <br>**<SPAN style="BACKGROUND-COLOR: #C0C0C0">Problem 3:</SPAN>** Run the above simulation 1,000 times. Calculate and print out: # # 1. the experimental probability of a false alarm # 2. the mean time to detection given that the false alarm does not happen. # # If failure is not detected use $N_{max}-\gamma$ for detection time. (Again, it's probably in your best interest not to plot a graph for each trial). # + # Your code here # - # __Answer__: (Your answer here) # **<SPAN style="BACKGROUND-COLOR: #C0C0C0">End of Problem 3</SPAN>** # Longer window sizes in the above method of change detection can lead to more accurate hypothesis testing (reducing the probability of false alarm and/or increasing the probability of detection during a given window after system change occurs), but longer window sizes can also lead to larger time to detection because after the system change we have to wait at least until the next window boundary (or the one after that) to get a detection. An alternative method, called the *cumulative sum* method, is to continUally update the log likelihood ratio, but reseting it to zero whenever it goes negative, and sounding the alarm whenever it crosses above a threshold. Note that a somewhat larger threshold should be used for the cumulative sum algorithm to offset the fact that the negative values of log likelihood are bumped up to zero. # # <br>**<SPAN style="BACKGROUND-COLOR: #C0C0C0">Problem 4:</SPAN>** # # 1. Implement the cumulative sum algorithm for the same pair of distributions and same distribution of system change time $\gamma$ as above. Adjust the threshold for the cumulative sum algorithm to get approximately the same probability of false alarm as for the window method above (this may require some trial and error). # 2. Print out the probability of false alarm. Estimate the resulting mean time to detection and print it out. # 3. Comment on how it differs from the average we found above. # + # Your code here # - # __Answer:__ (Your answer here) # **<SPAN style="BACKGROUND-COLOR: #C0C0C0">End of Problem 4</SPAN>** # ## Binary Hypothesis Testing for Multidimensional Gaussian Distributions: # In ECE 313 we consider the bivariate Gaussian distribution. It is a joint distribution for two random variables, $X_1,X_2$ and is uniquely determined by five parameters, the means of the two random variables, $m_1$ and $m_2$, the variances of the two random variables, and the covariance between the two random variables defined by $\mbox{Cov}(X_1,X_2)=E[(X_1-m_1)(X_2-m_2)].$ # By the way, note that $\mbox{Cov}(X_1,X_1)=\mbox{Var}(X_1,X_1).$ Equivalently, # we can think of $\binom{X_1}{X_2}$ as a random vector, with mean $\binom{m_1}{m_2}$ and covariance matrix # $\Sigma=\left( \begin{array} \mbox{Cov}(X_1,X_1) & \mbox{Cov}(X_1,X_2)\\ \mbox{Cov}(X_2,X_1) & \mbox{Cov}(X_2,X_2) \end{array}\right).$ # Joint normal (also known as joint Gaussian) distributions exist in any number of dimensions. A Guassian distribution in a given number of dimensions is specified uniquely by a mean vector and a covariance matrix. The following code generates variates for two normal distributions. The orange triangles follow a distribution that is rotationally symmetric about the origin. The blue circles follow a distribution with positive correlation between the two coordinates; the shape of the blue blob of points is elongated along a line of slope one. Also, the mean vector for the blue points is $\binom{2.0}{0}$ so the blue blob is offset a bit to the right of the orange blob. Try running the code a few times to see the variation. To get a better idea of the shapes, try increasing the number of samples to 1000. Now suppose you were to have 50 samples generated from one of the two distributions. That is, you get to see either 50 orange points or 50 blue points, but with the colors removed. How well do you think the maximum likelihood decision rule could detect which distribution was used to generate the points? (This is stated as a problem for you to work out, below.) dim=2 # Dimension of the random vectors num_samples=200 Sigma0=2.0*np.identity(dim) # identity matrix Sigma1=np.identity(dim)+ 4.0*np.ones([dim,dim]) # some positive correlation added mu0=np.zeros(dim) mu1=np.zeros(dim) mu1[0]=2.0 # first coordinate has nonzero mean under H1 variates0= multivariate_normal.rvs(mu0,Sigma0,num_samples) variates1= multivariate_normal.rvs(mu1,Sigma1,num_samples) plt.scatter(variates0[:,0],variates0[:,1],color='orange',marker='^') plt.scatter(variates1[:,0],variates1[:,1],color='blue') # plt.plot.scatter(variates2) plt.show() # The following code runs a ML detection rule on simulated multidimensional Gaussian random vectors of any finite dimension. It is very similar to the code used for hypothesis testing at the beginning of Lab 9. The difference is that here two multivariate normal pdfs are used instead of two discrete distributions. # + # Simulation of ML detection rule for two multidimensional Gaussian distibutions # dim = 3 # Dimension of the random vectors num_samples = 10 Sigma0 = np.identity(dim) # identity matrix Sigma1 = np.identity(dim)+ 0.5*np.ones([dim,dim]) # some positive correlation added mu0 = np.zeros(dim) mu1 = np.ones(dim)*0.1 # small nonzero mean under H1 dist0 = multivariate_normal(mu0, Sigma0) # multivariate_normal was imported from Scipy dist1 = multivariate_normal(mu1, Sigma1) Htrue=np.random.randint(2) # Sets the true hypothesis to be 0 or 1. if Htrue==0: # generate num_samples random variates using the true hypothesis variates = dist0.rvs(num_samples) # num_samples x dim array, each row is random variate else: variates = dist1.rvs(num_samples) # num_samples x dim array, each row is random variate print ("Data is generated using true hypothesis H",Htrue ,": ") print (variates) log_LR=0.0 # log_LR will become the log likelihood ratio for count in range(num_samples): log_LR += np.log(dist1.pdf(variates[count,:])/dist0.pdf(variates[count,:])) if log_LR >= 0: print ("log_LR=", log_LR, ">=0; declare H1 is true") else: print ("log_LR=", log_LR, "<0; declare H0 is true") if (log_LR >=0) and (Htrue==0): print ("False Alarm occured") if (log_LR <0) and (Htrue==1): print ("Miss occured") # - # <br>**<SPAN style="BACKGROUND-COLOR: #C0C0C0">Problem 5:</SPAN>** Adapt the above code to the case of 50 samples of bivariate gaussian random variable using the parameters of the orange and blue scatter plots shown above. Run the simulation 1,000 times to estimate and print out the probability of a false alarm and the probability of a miss. # + # Your code here # - # __Answer:__ (Your answer here) # **<SPAN style="BACKGROUND-COLOR: #C0C0C0">End of Problem 5</SPAN>** # ## Lab Questions: # For this weeks lab, please answer all questions 1-5. # <div class="alert alert-block alert-warning"> # ## Academic Integrity Statement ## # # By submitting the lab with this statement, you declare you have written up the lab entirely by yourself, including both code and markdown cells. You also agree that you should not share your code with anyone else. Any violation of the academic integrity requirement may cause an academic integrity report to be filed that could go into your student record. See <a href="https://provost.illinois.edu/policies/policies/academic-integrity/students-quick-reference-guide-to-academic-integrity/">Students' Quick Reference Guide to Academic Integrity</a> for more information.
ECE314/lab10/Lab 10.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:py39_spgh_dev] # language: python # name: conda-env-py39_spgh_dev-py # --- # + [markdown] extensions={"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"col": 0, "height": 4, "hidden": false, "row": 0, "width": 12}, "report_default": {}}}} # --------------- # # **If any part of this notebook is used in your research, please cite with the reference found in** **[README.md](https://github.com/pysal/spaghetti#bibtex-citation).** # # # ---------------- # # ## Network-constrained spatial dependence # ### Demonstrating cluster detection along networks with the Global Auto *K* function # # **Author: <NAME>** **<<EMAIL>>** # # **This notebook is an advanced walk-through for:** # # 1. Understanding the global auto *K* function with an elementary geometric object # 2. Basic examples with synthetic data # 3. Empirical examples # - # %load_ext watermark # %watermark # + extensions={"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"hidden": true}, "report_default": {}}}} import geopandas import libpysal import matplotlib import matplotlib_scalebar from matplotlib_scalebar.scalebar import ScaleBar import numpy import spaghetti # %matplotlib inline # %watermark -w # %watermark -iv # - try: from IPython.display import set_matplotlib_formats set_matplotlib_formats("retina") except ImportError: pass # **The** [*K* function](https://en.wikipedia.org/wiki/Spatial_descriptive_statistics#Ripley's_K_and_L_functions) **considers all pairwise distances of nearest neighbors to determine the existence of clustering, or lack thereof, over a delineated range of distances. For further description see Oโ€™Sullivan and Unwin (2010) and Okabe and Sugihara (2012).** # # * **<NAME> and <NAME>.** *Point Pattern Analysis*, chapter 5, pages 121โ€“156. John Wiley & Sons, Ltd, 2010. doi:10.1002/9780470549094.ch5. # # * **<NAME> and <NAME>.** *Network K Function Methods*, chapter 6, pages 119โ€“136. John Wiley & Sons, Ltd, 2012. doi:10.1002/9781119967101.ch6. # # # --------------------- # # ### 1. A demonstration of clustering # # #### Results plotting helper function # + def plot_k(k, _arcs, df1, df2, obs, scale=True, wr=[1, 1.2], size=(14, 7)): """Plot a Global Auto K-function and spatial context.""" def function_plot(f, ax): """Plot a Global Auto K-function.""" ax.plot(k.xaxis, k.observed, "b-", linewidth=1.5, label="Observed") ax.plot(k.xaxis, k.upperenvelope, "r--", label="Upper") ax.plot(k.xaxis, k.lowerenvelope, "k--", label="Lower") ax.legend(loc="best", fontsize="x-large") title_text = "Global Auto $K$ Function: %s\n" % obs title_text += "%s steps, %s permutations," % (k.nsteps, k.permutations) title_text += " %s distribution" % k.distribution f.suptitle(title_text, fontsize=25, y=1.1) ax.set_xlabel("Distance $(r)$", fontsize="x-large") ax.set_ylabel("$K(r)$", fontsize="x-large") def spatial_plot(ax): """Plot spatial context.""" base = _arcs.plot(ax=ax, color="k", alpha=0.25) df1.plot(ax=base, color="g", markersize=30, alpha=0.25) df2.plot(ax=base, color="g", marker="x", markersize=100, alpha=0.5) carto_elements(base, scale) sub_args = {"gridspec_kw":{"width_ratios": wr}, "figsize":size} fig, arr = matplotlib.pyplot.subplots(1, 2, **sub_args) function_plot(fig, arr[0]) spatial_plot(arr[1]) fig.tight_layout() def carto_elements(b, scale): """Add/adjust cartographic elements.""" if scale: kw = {"units":"ft", "dimension":"imperial-length", "fixed_value":1000} b.add_artist(ScaleBar(1, **kw)) b.set(xticklabels=[], xticks=[], yticklabels=[], yticks=[]); # - # #### Equilateral triangle def equilateral_triangle(x1, y1, x2, mids=True): """Return an equilateral triangle and its side midpoints.""" x3 = (x1+x2)/2. y3 = numpy.sqrt((x1-x2)**2 - (x3-x1)**2) + y1 p1, p2, p3 = (x1, y1), (x2, y1), (x3, y3) eqitri = libpysal.cg.Chain([p1, p2, p3, p1]) if mids: eqvs = eqitri.vertices[:-1] eqimps, vcount = [], len(eqvs), for i in range(vcount): for j in range(i+1, vcount): (_x1, _y1), (_x2, _y2) = eqvs[i], eqvs[j] mp = libpysal.cg.Point(((_x1+_x2)/2., (_y1+_y2)/2.)) eqimps.append(mp) return eqitri, eqimps eqtri_sides, eqtri_midps = equilateral_triangle(0., 0., 6., 1) ntw = spaghetti.Network(eqtri_sides) ntw.snapobservations(eqtri_midps, "eqtri_midps") vertices_df, arcs_df = spaghetti.element_as_gdf( ntw, vertices=ntw.vertex_coords, arcs=ntw.arcs ) eqv = spaghetti.element_as_gdf(ntw, pp_name="eqtri_midps") eqv_snapped = spaghetti.element_as_gdf(ntw, pp_name="eqtri_midps", snapped=True) eqv_snapped numpy.random.seed(0) kres = ntw.GlobalAutoK( ntw.pointpatterns["eqtri_midps"], nsteps=100, permutations=100) plot_k(kres, arcs_df, eqv, eqv_snapped, "eqtri_mps", wr=[1, 1.8], scale=False) # **Interpretation:** # # * **This example demonstrates a complete lack of clustering with a strong indication of dispersion when approaching 5 units of distance.** # # -------------------------------- # # ### 2. Synthetic examples # # #### Regular lattice โ€” distinguishing visual clustering from statistical clustering bounds = (0,0,3,3) h, v = 2, 2 lattice = spaghetti.regular_lattice(bounds, h, nv=v, exterior=True) ntw = spaghetti.Network(in_data=lattice) # #### Network arc midpoints: statistical clustering midpoints = [] for chain in lattice: (v1x, v1y), (v2x, v2y) = chain.vertices mp = libpysal.cg.Point(((v1x+v2x)/2., (v1y+v2y)/2.)) midpoints.append(mp) ntw.snapobservations(midpoints, "midpoints") # #### All observations on two network arcs: visual clustering npts = len(midpoints) * 2 xs = [0.0] * npts + [2.0] * npts ys = list(numpy.linspace(0.4,0.6, npts)) + list(numpy.linspace(2.1,2.9, npts)) pclusters = [libpysal.cg.Point(xy) for xy in zip(xs,ys)] ntw.snapobservations(pclusters, "pclusters") vertices_df, arcs_df = spaghetti.element_as_gdf(ntw, vertices=True, arcs=True) midpoints = spaghetti.element_as_gdf(ntw, pp_name="midpoints", snapped=True) pclusters = spaghetti.element_as_gdf(ntw, pp_name="pclusters", snapped=True) # #### Visual clustering numpy.random.seed(0) kres = ntw.GlobalAutoK(ntw.pointpatterns["pclusters"], nsteps=100, permutations=100) plot_k(kres, arcs_df, pclusters, pclusters, "pclusters", wr=[1, 1.8], scale=False) # **Interpretation:** # # * **This example exhibits a high degree of clustering within 1 unit of distance followed by a complete lack of clustering, then a strong indication of clustering around 3.5 units of distance and above. Both colloquilly and statistically, this pattern is clustered.** # # # #### Statistical clustering numpy.random.seed(0) kres = ntw.GlobalAutoK(ntw.pointpatterns["midpoints"], nsteps=100, permutations=100) plot_k(kres, arcs_df, midpoints, midpoints, "midpoints", wr=[1, 1.8], scale=False) # **Interpretation:** # # * **This example exhibits no clustering within 1 unit of distance followed by large increases in clustering at each 1-unit increment. After 3 units of distance, this pattern is highly clustered. Statistically speaking, this pattern is clustered, but not colloquilly.** # # # -------------------------- # # ### 3. Empircal examples # #### Instantiate the network from a `.shp` file ntw = spaghetti.Network(in_data=libpysal.examples.get_path("streets.shp")) vertices_df, arcs_df = spaghetti.element_as_gdf( ntw, vertices=ntw.vertex_coords, arcs=ntw.arcs ) # #### Associate the network with point patterns for pp_name in ["crimes", "schools"]: pp_shp = libpysal.examples.get_path("%s.shp" % pp_name) ntw.snapobservations(pp_shp, pp_name, attribute=True) ntw.pointpatterns # #### Empircal โ€” schools schools = spaghetti.element_as_gdf(ntw, pp_name="schools") schools_snapped = spaghetti.element_as_gdf(ntw, pp_name="schools", snapped=True) numpy.random.seed(0) kres = ntw.GlobalAutoK( ntw.pointpatterns["schools"], nsteps=100, permutations=100) plot_k(kres, arcs_df, schools, schools_snapped, "schools") # **Interpretation:** # # * **Schools exhibit no clustering until roughly 1,000 feet then display more clustering up to approximately 3,000 feet, followed by high clustering up to 6,000 feet.** # # #### Empircal โ€” crimes crimes = spaghetti.element_as_gdf(ntw, pp_name="crimes") crimes_snapped = spaghetti.element_as_gdf(ntw, pp_name="crimes", snapped=True) numpy.random.seed(0) kres = ntw.GlobalAutoK( ntw.pointpatterns["crimes"], nsteps=100, permutations=100) plot_k(kres, arcs_df, crimes, crimes_snapped, "crimes") # **Interpretation:** # # * **There is strong evidence to suggest crimes are clustered at all distances along the network, but more so within several feet of each other and at 10,000 feet.** # + [markdown] extensions={"jupyter_dashboards": {"version": 1, "views": {"grid_default": {"col": 8, "height": 4, "hidden": false, "row": 48, "width": 4}, "report_default": {}}}} # -----------
notebooks/network-spatial-dependence.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] # --- # * This notebook was made to reproduce drifter track with reference of Nancy's notebook with longitude ticks shown completely in the figure. # + # %matplotlib inline import matplotlib.pyplot as plt import netCDF4 as nc import numpy as np import scipy.io import datetime as dt from salishsea_tools import nc_tools, viz_tools, tidetools, bathy_tools,geo_tools import drifter # - drifters = scipy.io.loadmat('/ocean/mhalvers/research/drifters/SoG_drifters.mat',squeeze_me=True) ubc = drifters['ubc'] grid = nc.Dataset('/ocean/jieliu/research/meopar/river-treatment/bathy_meter_SalishSea6.nc','r') bathy = grid.variables['Bathymetry'][:, :] X = grid.variables['nav_lon'][:, :] Y = grid.variables['nav_lat'][:, :] tracersT = nc.Dataset('/data/jieliu/MEOPAR/river-treatment/oct8_10RFdailySmoo/\ SalishSea_1h_20141008_20141010_grid_T.nc') ssh = tracersT.variables['sossheig'] timesteps = tracersT.variables['time_counter'] def convert_time(matlab_time_array): "converts a matlab time array to python format" python_time_array=[] for t in matlab_time_array: python_datetime = dt.datetime.fromordinal(int(t)) + dt.timedelta(days=t%1) - dt.timedelta(days = 366) python_time_array.append(python_datetime) python_time_array = np.array(python_time_array) return python_time_array def get_tracks(switch,lats,lons,ptime,in_water): """returns a list of tracks of each buoy, ie a trajectory for each time the buoy was released into the water""" all_tracks=[] for ind in switch: track_on = 1 i = ind track ={'time':[], 'lat':[],'lon':[]} while(track_on): if in_water[i]!=1: track_on=0 elif i==np.shape(in_water)[0]-1: track['time'].append(ptime[i]) track['lat'].append(lats[i]) track['lon'].append(lons[i]) track_on=0 else: track['time'].append(ptime[i]) track['lat'].append(lats[i]) track['lon'].append(lons[i]) i=i+1 all_tracks.append(track) return all_tracks def organize_info(buoy,btype): """ organizes the buoy info. Groups the buoy data into tracks for when it was released into the water. """ #creat arrays for easier access buoy_name = btype[buoy][0] lats = btype[buoy]['lat'].flatten() lons = btype[buoy]['lon'].flatten() mtime = btype[buoy]['mtime'] in_water = btype[buoy]['isSub'].flatten() #convert mtime to python datetimes ptime = convert_time(mtime) #loop through in_water flag to find when buoy switched from being out of water to being in water. switch = []; for ind in np.arange(1,in_water.shape[0]): if int(in_water[ind]) != int(in_water[ind-1]): if int(in_water[ind])==1: switch.append(ind) all_tracks=get_tracks(switch,lats,lons,ptime.flatten(),in_water) return buoy_name, all_tracks # + def find_start(tracks, start_date): """returns the a list of indices for a track released on start date. Only checks the month and day of the start day""" i=0 ind=[] starttimes=[] for t in tracks: if int(t['time'][0].month) == start_date.month: if int(t['time'][0].day) == start_date.day: ind.append(i) i=i+1 return ind # - def plot_buoy(tracks, startdate, i=0, fancy=False): """ plots a buoy trajectory at the given startdate in an axis, ax. returns the trajectory that was plotted. The first track released on the startdate is plotted. For trajectories that were released mulitples times a day, i selects which release is plotted. """ fig,ax = plt.subplots(1,1,figsize=(5,5)) ind =find_start(tracks,startdate) traj=tracks[ind[i]] duration = (traj['time'][-1]-traj['time'][0]).total_seconds()/3600 print ('Released', traj['time'][0], 'at', traj['lat'][0], ',' , traj['lon'][0], 'for' , duration, 'hours') ax.plot(traj['lon'],traj['lat'],'ob') ax.plot(traj['lon'][0],traj['lat'][0],'sr') bathy, X, Y = tidetools.get_SS2_bathy_data() [j,i]=geo_tools.find_closest_model_point(float(traj['lon'][0]),float(traj['lat'][0]),X,Y,land_mask=bathy.mask) ax.plot(-123-np.array([18.2, 13.7, 12])/60.,49+np.array([6.4, 8, 7.6])/60.,'-k',lw=2); if fancy: cmap = plt.get_cmap('winter_r') cmap.set_bad('burlywood') ax.pcolormesh(X, Y, bathy, cmap=cmap) ax.set_title('Observed Drift Track') ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') ax.text(-123.15,49.13, "Fraser River", fontsize=12) else: viz_tools.plot_coastline(ax, grid, coords='map') viz_tools.plot_coastline(ax, grid, coords='map',isobath=4) viz_tools.plot_coastline(ax, grid, coords='map',isobath=20) print ('NEMO coords:', j,i) ax.set_xlim([-123.6,-123]) ax.set_ylim([48.8,49.4]) ax.set_xticks([-123.6, -123.4, -123.2,-123]) ax.set_xticklabels([-123.6, -123.4, -123.2,-123]) ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') plt.show() return traj def calculate_position_onehour(tracks, startdate,day,hour, minute, filename, i=0): """ """ ind =find_start(tracks,startdate) traj=tracks[ind[i]] duration = (traj['time'][-1]-traj['time'][0]).total_seconds()/3600 print ('Released', traj['time'][0], 'at', traj['lat'][0], ',' , traj['lon'][0], 'for' , duration, 'hours') bathy, X, Y = tidetools.get_SS2_bathy_data() [j,i]=geo_tools.find_closest_model_point(float(traj['lon'][0]),float(traj['lat'][0]),X,Y,land_mask=bathy.mask) print(j,i,traj['time'][0].hour+0.5+traj['time'][0].minute/60) fig,ax = plt.subplots(1,1,figsize=(5,5)) ax.plot(traj['lon'],traj['lat'],'ob') ax.plot(traj['lon'][0],traj['lat'][0],'sr') ax.plot(-123-np.array([18.2, 13.7, 12])/60.,49+np.array([6.4, 8, 7.6])/60.,'-k',lw=2); viz_tools.plot_coastline(ax, grid, coords='map') viz_tools.plot_coastline(ax, grid, coords='map',isobath=4) viz_tools.plot_coastline(ax, grid, coords='map',isobath=20) ax.set_xlim([-123.6,-123]) ax.set_ylim([48.8,49.4]) with open(filename, 'w') as file: for t in range(len(traj['time'])): if np.abs((traj['time'][t] - dt.datetime(2014,10,day,hour,minute)).seconds)<=50: [j,i]=geo_tools.find_closest_model_point(float(traj['lon'][t]),float(traj['lat'][t]),X,Y,land_mask=bathy.mask) print(j,i,(traj['time'][t].day-8)*24+traj['time'][t].hour+0.5+traj['time'][t].minute/60, traj['time'][t]) t_time = (traj['time'][t].day-8)*24+traj['time'][t].hour+0.5+traj['time'][t].minute/60 file.writelines('%s %s %s \n' %(i+1,j+1,t_time)) ax.plot(traj['lon'][t],traj['lat'][t],'*') hour = hour +1 if hour > 23: hour = 0 day = day +1 file.close() plt.show() return traj buoy = 0 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,16,0,'test.txt',i=-1) buoy = 0 name, tracks=drifter.organize_info(buoy,ubc) print (name) t_j = plot_buoy(tracks,dt.datetime(2014,10,8),i=-1) fig.savefig('drop31.png') buoy = 1 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,16,5,i=-1) buoy = 1 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8),i=-1) # + #fig.savefig('drop212a.png') # - buoy = 2 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,16,10,i=-1) buoy = 2 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) # + #fig.savefig('drop112a.png') # - buoy = 3 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,17,30,i=-1) buoy = 3 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop112b.png') buoy = 4 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,17,30,i=-1) buoy = 4 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop212b.png') buoy = 5 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,17,35,i=-1) buoy = 5 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop323a.png') buoy = 6 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,19,10,i=-1) buoy = 6 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop323b.png') buoy = 7 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,19,20,i=-1) buoy = 7 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop23.png') buoy = 9 name, tracks=drifter.organize_info(buoy,ubc) print (name) du = calculate_position_onehour(tracks,dt.datetime(2014,10,8),8,19,20,i=-1) buoy = 9 name, tracks=organize_info(buoy,ubc) print (name) fig=plot_buoy(tracks,dt.datetime(2014,10,8), i=-1) fig.savefig('drop13.png')
jie/drifter/ReproduceDrifterTrack.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.7 64-bit # name: python3 # --- # + import numpy as np from sklearn import datasets, linear_model, model_selection import matplotlib.pyplot as plt from matplotlib import rcParams # %matplotlib inline rcParams.update({ "font.family":'DejaVu Serif', # "font.size": 8, "mathtext.fontset":'stix', # "font.serif": ['DejaVu Sans'], "figure.autolayout":True, }) # # ไธบๅŽ้ขๅ‚จๅญ˜ๅ›พ็‰‡ๅšๅ‡†ๅค‡ # filePath = os.path.abspath() # fileDirPath = os.path.dirname(filePath) # - # - ๅฐ่ฏ•่Žทๅ–ๅ˜้‡ๅ็งฐ # ```Python # import inspect, re # import numpy # # def varname(p): # for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: # m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) # if m: # return m.group(1) # # def chArr(p): # for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: # m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) # if m: # print(m.group(1)) # return # # chArr(X) # ``` dataColNames = datasets.load_diabetes(return_X_y=True, as_frame=True)[0].columns.tolist() dataColNamesDict = dict(zip(range(len(dataColNames)), dataColNames)) len(dataColNamesDict.keys()) dataColNamesDict[0] for key in dataColNamesDict.keys(): X, y = datasets.load_diabetes(return_X_y=True) # ่ฟ”ๅ›žXๅ’Œy X = X[:, np.newaxis, key] # ๅชไฟ็•™ๅŽŸๆฅๅพˆๅคšๅˆ—ไธญ็š„ไธ€ๅˆ— X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33) model = linear_model.LinearRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) plt.scatter(X_test[:,0], y_test, color='black') plt.plot(X_test, y_pred, color='blue', linewidth=3) plt.xlabel('Scaled ' + dataColNamesDict[key]) plt.ylabel('Disease Progression') plt.title('A Graph Plot Showing Diabetes Progression Against ' + dataColNamesDict[key]) plt.show() rawData = datasets.load_linnerud() rawData # + feature = rawData['data'] feature_names = dict(zip(range(len(rawData['feature_names'])), rawData['feature_names'])) target = rawData['target'] target_names =dict(zip(range(len(rawData['target_names'])), rawData['target_names'])) print("feature_names", feature_names) print("feature", feature.shape) print("target_names", target_names) print("target", target.shape) # - fig, axes = plt.subplots(len(feature_names.keys()), len(target_names.keys()), figsize=(16,12), dpi=120) Dfig, Daxes = plt.subplots(len(feature_names.keys()), len(target_names.keys()), figsize=(16,12), dpi=120) for i in feature_names.keys(): for j in target_names.keys(): ax = axes[i][j] Dax = Daxes[i][j] X = feature[:,i] y = target[:,j] Dax.scatter(X, y, color='black') Dax.grid() Dax.set_xlabel('feature ' + feature_names[i]) Dax.set_ylabel('target ' + target_names[j]) Dax.set_title('Data set: Body Indexs [' + target_names[j] + '] Against [' + feature_names[i] + "]") X_train, X_test, y_train, y_test = [i.reshape(-1, 1) for i in model_selection.train_test_split(X, y, test_size=0.33)] model = linear_model.LinearRegression() model.fit(X_train.reshape(-1, 1), y_train.reshape(-1, 1)) y_pred = model.predict(X_test) ax.scatter(X_test[:,0], y_test, color='black') ax.plot(X_test, y_pred, color='blue', linewidth=3) ax.grid() ax.set_xlabel('feature ' + feature_names[i]) ax.set_ylabel('target ' + target_names[j]) ax.set_title('Body Indexs [' + target_names[j] + '] Against [' + feature_names[i] + "]") plt.show()
2-Regression/1-Tools/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.8.9 64-bit (''venv'': venv)' # name: python3 # --- # + import sys sys.path.insert(0, '../src') # + from pathlib import Path import torch from neuro_comma.predict import RepunctPredictor from neuro_comma.model import CorrectionModel # - model = CorrectionModel( pretrained_model="DeepPavlov/rubert-base-cased-sentence", targets={ "O": 0, "COMMA": 1, "PERIOD": 2 } ) model.load('../models/repunct-model-new/weights/weights_ep6_9912.pt') quantized_model = model.quantize() quantized_model.save('../models/repunct-model-new/weights/quantized_weights_ep6_9912.pt') predictor = RepunctPredictor(model_name='repunct-model-new', models_root=Path('../models'), model_weights='quantized_weights_ep6_9912.pt', quantization=True) # + text = ("ะŸะพะบะฐะทะฐั‚ะตะปะธ ะดะฐะฒะปะตะฝะธั ะผะพะณัƒั‚ ะธะทะผะตะฝัั‚ัŒัั ะฒ ะทะฐะฒะธัะธะผะพัั‚ะธ ะพั‚ ั€ัะดะฐ ั„ะฐะบั‚ะพั€ะพะฒ " "ะ”ะฐะถะต ัƒ ะพะดะฝะพะณะพ ะธ ั‚ะพะณะพ ะถะต ะฟะฐั†ะธะตะฝั‚ะฐ ะฒ ั‚ะตั‡ะตะฝะธะต ััƒั‚ะพะบ ะฝะฐะฑะปัŽะดะฐัŽั‚ัั ะบะพะปะตะฑะฐะฝะธั ะะ” " "ะะฐะฟั€ะธะผะตั€ ัƒั‚ั€ะพะผ ะฟะพัะปะต ะฟั€ะพะฑัƒะถะดะตะฝะธั ะบั€ะพะฒัะฝะพะต ะดะฐะฒะปะตะฝะธะต ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ะฝะธะทะบะธะผ " "ะฟะพัะปะต ะพะฑะตะดะฐ ะพะฝะพ ะผะพะถะตั‚ ะฝะฐั‡ะฐั‚ัŒ ะฟะพะดะฝะธะผะฐั‚ัŒัั") predictor(text) # -
notebooks/quantization.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 # --- # !ls -ltrh /dev/video* # + from IPython.display import display from jetcam.utils import bgr8_to_jpeg from jetcam.usb_camera import USBCamera from jetcam.csi_camera import CSICamera import ipywidgets import numpy as np import cv2 import os print(cv2.__version__) folder = "dnn" proto = os.path.sep.join([folder, "deploy.prototxt"]) weight = os.path.sep.join([folder, "res10_300x300_ssd_iter_140000.caffemodel"]) net = cv2.dnn.readNet(proto, weight) camera = USBCamera(width=640, height=360, capture_device=0) image_widget = ipywidgets.Image(format='jpeg') image_widget_blur = ipywidgets.Image(format='jpeg') camera.running = True # + def update_image(change): frame = change['new'] image_widget.value = bgr8_to_jpeg(frame) display(image_widget) camera.observe(update_image, names='value') # + def blur_face(image, factor=2): (h, w) = image.shape[:2] k_w = int(w / factor) k_h = int(h / factor) if k_w % 2 == 0: k_w -= 1 if k_h % 2 == 0: k_h -= 1 return cv2.GaussianBlur(image, (k_w, k_h), 0) def update_image_blur(change): frame = change['new'] blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300)) net.setInput(blob) detections = net.forward() (h, w) = frame.shape[:2] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.5: box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") face = frame[startY:endY, startX:endX] face = blur_face(face) frame[startY:endY, startX:endX] = face image_widget_blur.value = bgr8_to_jpeg(frame) display(image_widget_blur) camera.observe(update_image_blur, names='value') # -
blur_face.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 # --- # # Activation functions # # - toc:true # - badges: true # - comments: true # - author: <NAME> # - categories: [python, machine-learning, pytorch] # Function that activates the particular neuron or node if the value across a particular threshold. These functions add the necessary non-linearity in the ANNs. Each perceptron is, in reality (and traditionally), a logistic regression unit. When N units are stacked on top of each other we get a basic single layer perceptron which serves as the basis of Artificial neural network. # # [Click here for Google's ML glossary definition](https://developers.google.com/machine-learning/glossary#activation-function) # # There are different types of activation function and each has its benefits and faults. One of the consideration is the ease in evaluation of the gradient. It should be easy but also help in the final learning process by translating the necessary abstraction and non-linearity across the network. Some of the activation functions are primarily used to model the output of the ANN. Traditionally for a classification task, we would use a sigmoid activation function for a binary classification to predict a binary output (yes/no). In the case of multi-class classification that activation is replaced by softmax activation to estimate the 'probability' across different classes. # # Some of the traditionally used Activation functions: # <ul> # <li>Sigmoid activaton function</li> # <li>tanh (hyperbolic tangent) activaton function</li> # <li>ReLU activaton function</li> # <li>Leaky ReLU activaton function</li> # <li>Softplus function </li> # <li>Softmax function </li> # </ul> import numpy as np import matplotlib.pyplot as plt # %config InlineBackend.figure_format = 'retina' import seaborn as sns sns.set_palette("deep") # ## ## Baseline reference z = np.linspace(-10,10,100) # ### Sigmoid activation function def sigmoid(z): return 1/(1+np.exp(-z)) # derivative of Sigmoid Function def dsigmoid(a): return a*(1-a) # returns a derivative od sigmoid function if a=sigmoid then a'=a(1-a) plt.plot(z, sigmoid(z), label = r'$sigmoid$') plt.plot(z, dsigmoid(sigmoid(z)), label = r'$ \frac{\partial (sigmoid)}{\partial z}$') plt.legend(fontsize = 12) plt.xlabel('z') plt.show() # Pytorch autograd example import torch x = torch.tensor(z, requires_grad=True) print(x.requires_grad) b = torch.sigmoid(x) x b.backward(torch.ones(x.shape)) x.grad plt.plot(x.data.numpy(), b.data.numpy(), label = r'$sigmoid$') plt.plot(x.data.numpy(), x.grad.data.numpy(), label = r'$ \frac{\partial (sigmoid)}{\partial z}$') plt.legend(fontsize = 12) np.unique(np.round((x.grad.data.numpy() - dsigmoid(sigmoid(z))),4)) # ### Hyperbolic tangent activation function # + def tanh(z): return np.tanh(z) # derivative of tanh def dtanh(a): return 1-np.power(a,2) # - plt.plot(z, tanh(z),'b', label = 'tanh') plt.plot(z, dtanh(tanh(z)),'r', label=r'$ \frac{dtanh}{dz}$') plt.legend(fontsize = 12) plt.show() # ### ReLU (Rectified Linear Unit) Activation function # + def ReLU(z): return np.maximum(0,z) # derivative of ReLu def dReLU(a): return 1*(a>0) # - plt.plot(z, ReLU(z),'b', label ='ReLU') plt.plot(z, dReLU(ReLU(z)),'r', label=r'$ \frac{dReLU}{dz}$') plt.legend(fontsize = 12) plt.xlabel('z') plt.ylim(0,4) plt.xlim(-4,4) plt.show() # ### Leaky ReLU Activation function # + def LeakyReLU(z): return np.maximum(0.01*z,z) # derivative of ReLu def dLeakyReLU(a): return 0.01*(a>0) # - plt.plot(z, LeakyReLU(z),'b', label = 'LeakyReLU') plt.plot(z, dLeakyReLU(LeakyReLU(z)),'r', label=r'$ \frac{dLeakyReLU}{dz}$') plt.legend(fontsize = 12) plt.xlabel('z') plt.ylim(0,4) plt.xlim(-4,4) plt.show() # ### Comparison of derivative for activation functions plt.plot(z, dsigmoid(sigmoid(z)),label = r'$ \frac{dsigmoid}{dz}$' ) plt.plot(z, dtanh(tanh(z)), label = r'$ \frac{dtanh}{dz}$') plt.plot(z, dReLU(ReLU(z)), label=r'$ \frac{dReLU}{dz}$') plt.plot(z, dLeakyReLU(LeakyReLU(z)), label=r'$ \frac{dLeakyReLU}{dz}$') plt.legend(fontsize = 12) plt.xlabel('z') plt.title('Derivatives of activation functions') plt.show()
_notebooks/2020-04-22-activation_functions.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 # --- # # Data modeling with Apache Cassandra # ## Part I. ETL Pipeline for pre-processing files # ### Setup from pathlib import Path import pandas as pd import cassandra from helpers import * from queries import * # %load_ext autoreload # %autoreload 2 # ### Create a list of filepaths to process original event data csv files root_path = Path.cwd() data_path = root_path.joinpath("event_data") file_path_list = [e for e in data_path.rglob("*.csv")] print(f"Found {len(file_path_list)} CSV files in: {data_path}") # ### Process individual files to create a single file that will be used for Apache Casssandra tables # Let's take a look at one individual csv file first first_file = file_path_list[0] # !head $first_file first_df = pd.read_csv(first_file) first_df.shape first_df.head() # Load all csv files into one dataframe and save it as CSV try: df = pd.read_csv(f"{root_path}/event_datafile_new.csv") print("Loaded file from disk") except FileNotFoundError: columns = ["artist", "firstName", "gender", "itemInSession", "lastName", "length", "level", "location", "sessionId", "song", "userId"] df = load_all_records(file_path_list, columns) finally: print(f"Shape: {df.shape}") df.head() df.dtypes # Set correct dtypes for ts (timestamp) and userId (int) # Although userId should be of type int, because of a limitation of pandas < 0.24 (Series of type int can not hold NaNs) we leave it as int # df["userId"] = df["userId"].fillna(0).astype("int64") df["ts"] = df["ts"].astype("datetime64[ms]") df.head() if not root_path.joinpath("event_datafile_new.csv").exists(): df.to_csv(f"{root_path}/event_datafile_new.csv", index=False) else: print("File event_datafile_new.csv does already exist") # ## Part II. Data Modelling with Apache Cassandra # # Now we are ready to work with the CSV file titled <font color=red>**event_datafile_new.csv**</font>, located within the W\workspace directory. # The event_datafile_new.csv contains the following columns: # - artist # - firstName of user # - gender of user # - item number in session # - last name of user # - length of the song # - level (paid or free song) # - location of the user # - sessionId # - song title # - userId # # The image below is a screenshot of what the denormalized data should appear like in the <font color=red>**event_datafile_new.csv**</font> after the code above is run:<br> # # <img src="images/image_event_datafile_new.jpg"> # #### Create Cluster # + from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect() # - # #### Create Keyspace # http://cassandra.apache.org/doc/latest/cql/ddl.html#create-keyspace session.execute(cluster_create_keyspace) # #### Set Keyspace session.set_keyspace("sparkify") # ## Create queries to find answers to the following three questions # # 1. Give me the artist, song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4 # 2. Give me only the following: name of artist, song (sorted by itemInSession) and user (first and last name) for userid = 10, sessionid = 182 # 3. Give me every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own' # ### Query 1 session.execute(q1_drop_table) session.execute(q1_create_table) # #### Insert data table = "song_playlist_session" cols = ["sessionId", "itemInSession", "artist", "song", "length"] q1_cql = f"INSERT INTO {table} ({cols[0]}, {cols[1]}, {cols[2]}, {cols[3]}, {cols[4]}) VALUES (?, ?, ?, ?, ?)" print(q1_cql) batch_insert(cql=q1_cql, cols=cols, data=df, size=500, session=session) # #### Perform sanity check query(f"SELECT * FROM {table} LIMIT 5", session, print_result=False) # #### Execute query # _Give me the artist, song title and song's length in the music app history that was heard during sessionId = 338, and itemInSession = 4_ q1 = query(q1_query, session) # ### Query 2 session.execute(q2_drop_table) session.execute(q2_create_table) # #### Insert data table = "song_playlist_user" cols = ["userId", "sessionId", "itemInSession", "artist", "song", "firstName", "lastName"] q2_cql = f"INSERT INTO {table} ({cols[0]}, {cols[1]}, {cols[2]}, {cols[3]}, {cols[4]}, {cols[5]}, {cols[6]}) VALUES (?, ?, ?, ?, ?, ?, ?)" print(q2_cql) batch_insert(cql=q2_cql, cols=cols, data=df, size=250, session=session) # #### Perform sanity check query(f"SELECT * FROM {table} LIMIT 5", session, print_result=False) # #### Execute query # _Give me only the following: name of artist, song (sorted by itemInSession) and user (first and last name) for userid = 10, sessionid = 182_ # explicitly select itemInSession to show that sorting works q2 = query(q2_query, session) # ### Query 3 session.execute(q3_drop_table) session.execute(q3_create_table) # #### Insert data table = "song_user_name" cols = ["song", "userId", "firstName", "lastName"] q3_cql = f"INSERT INTO {table} ({cols[0]}, {cols[1]}, {cols[2]}, {cols[3]}) VALUES (?, ?, ?, ?)" print(q3_cql) batch_insert(cql=q3_cql, cols=cols, data=df, size=500, session=session) # #### Perform sanity check query(f"SELECT * FROM {table} LIMIT 5", session, print_result=False) # #### Execute query # _Give me every user name (first and last) in my music app history who listened to the song 'All Hands Against His Own'_ q3 = query(q3_query, session) # ### Drop tables before closing out session [session.execute(q) for q in [q1_drop_table, q2_drop_table, q3_drop_table]] # ### Close session and cluster connectionยถ session.shutdown() cluster.shutdown()
cassandra/cassandra.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # Demo version of the ``square_limit`` topic notebook in ``examples/topics/geometry``. # # Most examples work across multiple plotting backends, this example is also available for: # * [Bokeh - square_limit](../bokeh/square_limit.ipynb) import holoviews as hv import numpy as np from matplotlib.path import Path from matplotlib.transforms import Affine2D hv.extension('matplotlib') # %output fig='svg' # ## Declaring data and transforms # + spline=[(0.0,1.0),(0.08,0.98),(0.22,0.82),(0.29,0.72),(0.29,0.72),(0.3,0.64),(0.29,0.57),(0.3,0.5), (0.3,0.5),(0.34,0.4),(0.43,0.32),(0.5,0.26),(0.5,0.26),(0.58,0.21),(0.66,0.22),(0.76,0.2),(0.76,0.2), (0.82,0.12),(0.94,0.05),(1.0,0.0),(1.0,0.0),(0.9,0.03),(0.81,0.04),(0.76,0.05),(0.76,0.05),(0.69,0.04), (0.62,0.04),(0.55,0.04),(0.55,0.04),(0.49,0.1),(0.4,0.17),(0.35,0.2),(0.35,0.2),(0.29,0.24),(0.19,0.28), (0.14,0.31),(0.14,0.31),(0.09,0.35),(-0.03,0.43),(-0.05,0.72),(-0.05,0.72),(-0.04,0.82),(-0.02,0.95),(0.0,1.0), (0.1,0.85),(0.14,0.82),(0.18,0.78),(0.18,0.75),(0.18,0.75),(0.16,0.74),(0.14,0.73),(0.12,0.73),(0.12,0.73), (0.11,0.77),(0.11,0.81),(0.1,0.85),(0.05,0.82),(0.1,0.8),(0.08,0.74),(0.09,0.7),(0.09,0.7),(0.07,0.68), (0.06,0.66),(0.04,0.67),(0.04,0.67),(0.04,0.73),(0.04,0.81),(0.05,0.82),(0.11,0.7),(0.16,0.56),(0.24,0.39), (0.3,0.34),(0.3,0.34),(0.41,0.22),(0.62,0.16),(0.8,0.08),(0.23,0.8),(0.35,0.8),(0.44,0.78),(0.5,0.75), (0.5,0.75),(0.5,0.67),(0.5,0.59),(0.5,0.51),(0.5,0.51),(0.46,0.47),(0.42,0.43),(0.38,0.39),(0.29,0.71), (0.36,0.74),(0.43,0.73),(0.48,0.69),(0.34,0.61),(0.38,0.66),(0.44,0.64),(0.48,0.63),(0.34,0.51),(0.38,0.56), (0.41,0.58),(0.48,0.57),(0.45,0.42),(0.46,0.4),(0.47,0.39),(0.48,0.39),(0.42,0.39),(0.43,0.36),(0.46,0.32), (0.48,0.33),(0.25,0.26),(0.17,0.17),(0.08,0.09),(0.0,0.01),(0.0,0.01),(-0.08,0.09),(-0.17,0.18),(-0.25,0.26), (-0.25,0.26),(-0.2,0.37),(-0.11,0.47),(-0.03,0.57),(-0.17,0.26),(-0.13,0.34),(-0.08,0.4),(-0.01,0.44), (-0.12,0.21),(-0.07,0.29),(-0.02,0.34),(0.05,0.4),(-0.06,0.14),(-0.03,0.23),(0.03,0.28),(0.1,0.34),(-0.02,0.08), (0.02,0.16),(0.09,0.23),(0.16,0.3)] rotT = Affine2D().rotate_deg(90).translate(1, 0) rot45T = Affine2D().rotate_deg(45).scale(1. / np.sqrt(2.), 1. / np.sqrt(2.)).translate(1 / 2., 1 / 2.) flipT = Affine2D().scale(-1, 1).translate(1, 0) def combine(obj): "Collapses overlays of Splines to allow transforms of compositions" if not isinstance(obj, hv.Overlay): return obj return hv.Spline((np.vstack([el.data[0] for el in obj.values()]), np.hstack([el.data[1] for el in obj.values()]))) def T(spline, transform): "Apply a transform to a spline or overlay of splines" spline = combine(spline) result = Path(spline.data[0], codes=spline.data[1]).transformed(transform) return hv.Spline((result.vertices, result.codes)) def beside(spline1, spline2, n=1, m=1): den = float(n + m) t1 = Affine2D().scale(n / den, 1) t2 = Affine2D().scale(m / den, 1).translate(n / den, 0) return combine(T(spline1, t1) * T(spline2, t2)) def above(spline1, spline2, n=1, m=1): den = float(n + m) t1 = Affine2D().scale(1, n / den).translate(0, m / den) t2 = Affine2D().scale(1, m / den) return combine(T(spline1, t1) * T(spline2, t2)) def nonet(p, q, r, s, t, u, v, w, x): return above(beside(p, beside(q, r), 1, 2), above(beside(s, beside(t, u), 1, 2), beside(v, beside(w, x), 1, 2)), 1, 2) def quartet(p, q, r, s): return above(beside(p, q), beside(r, s)) def side(n,t): if n == 0: return hv.Spline(([(np.nan, np.nan)],[1])) else: return quartet(side(n-1,t), side(n-1,t), rot(t), t) def corner(n,u,t): if n == 0: return hv.Spline(([(np.nan, np.nan)],[1])) else: return quartet(corner(n-1,u,t), side(n-1,t), rot(side(n-1,t)), u) def squarelimit(n,u,t): return nonet(corner(n,u,t), side(n,t), rot(rot(rot(corner(n,u,t)))), rot(side(n,t)), u, rot(rot(rot(side(n,t)))), rot(corner(n,u,t)), rot(rot(side(n,t))), rot(rot(corner(n,u,t)))) def rot(el): return T(el,rotT) def rot45(el): return T(el, rot45T) def flip(el): return T(el, flipT) # - # ## Plot # + # %%opts Spline [xaxis=None yaxis=None aspect='equal' bgcolor='white'] (linewidth=0.8) # %%output size=250 fish = hv.Spline((spline, [1,4,4,4]*34)) # Cubic splines smallfish = flip(rot45(fish)) t = fish * smallfish * rot(rot(rot(smallfish))) u = smallfish * rot(smallfish) * rot(rot(smallfish)) * rot(rot(rot(smallfish))) squarelimit(3,u,t)
examples/gallery/demos/matplotlib/square_limit.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={"duration": 0.052824, "end_time": "2020-11-30T17:25:31.792141", "exception": false, "start_time": "2020-11-30T17:25:31.739317", "status": "completed"} tags=[] # ## 101-preprocess.ipynb # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" papermill={"duration": 6.670962, "end_time": "2020-11-30T17:25:38.514710", "exception": false, "start_time": "2020-11-30T17:25:31.843748", "status": "completed"} tags=[] import sys # for kaggle kernel # add datasets iterative-stratification and umaplearn sys.path.append('../input/iterative-stratification/iterative-stratification-master') sys.path.append('../input/umaplearn/umap') # %mkdir model # %mkdir interim from scipy.sparse.csgraph import connected_components from umap import UMAP from iterstrat.ml_stratifiers import MultilabelStratifiedKFold, RepeatedMultilabelStratifiedKFold import numpy as np import scipy as sp import random import pandas as pd import matplotlib.pyplot as plt import os import copy import seaborn as sns import time # import joblib from sklearn import preprocessing from sklearn.metrics import log_loss from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA, FactorAnalysis from sklearn.manifold import TSNE import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim print(f"is cuda available: {torch.cuda.is_available()}") import warnings # warnings.filterwarnings('ignore') def seed_everything(seed_value): random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) os.environ['PYTHONHASHSEED'] = str(seed_value) if torch.cuda.is_available(): torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False DEFAULT_SEED = 512 seed_everything(seed_value=DEFAULT_SEED) # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" papermill={"duration": 0.063865, "end_time": "2020-11-30T17:25:38.631690", "exception": false, "start_time": "2020-11-30T17:25:38.567825", "status": "completed"} tags=[] # file name prefix NB = '101' IS_TRAIN = False ################################################################ MODEL_DIR = "../input/503-203-tabnet-with-nonscored-features-train/model" # "../model" INT_DIR = "interim" # "../interim" DEVICE = ('cuda' if torch.cuda.is_available() else 'cpu') # label smoothing PMIN = 0.0 PMAX = 1.0 # submission smoothing SMIN = 0.0 SMAX = 1.0 # + papermill={"duration": 6.43346, "end_time": "2020-11-30T17:25:45.118700", "exception": false, "start_time": "2020-11-30T17:25:38.685240", "status": "completed"} tags=[] train_features = pd.read_csv('../input/lish-moa/train_features.csv') train_targets_scored = pd.read_csv('../input/lish-moa/train_targets_scored.csv') train_targets_nonscored = pd.read_csv('../input/lish-moa/train_targets_nonscored.csv') test_features = pd.read_csv('../input/lish-moa/test_features.csv') sample_submission = pd.read_csv('../input/lish-moa/sample_submission.csv') # + papermill={"duration": 0.062223, "end_time": "2020-11-30T17:25:45.236461", "exception": false, "start_time": "2020-11-30T17:25:45.174238", "status": "completed"} tags=[] # test_features_dummy = pd.read_csv('../input/dummytestfeatures/test_features_dummy.csv') # test_features = pd.concat([test_features, test_features_dummy]).reset_index(drop=True) # + papermill={"duration": 67.494823, "end_time": "2020-11-30T17:26:52.789608", "exception": false, "start_time": "2020-11-30T17:25:45.294785", "status": "completed"} tags=[] from sklearn.preprocessing import QuantileTransformer GENES = [col for col in train_features.columns if col.startswith('g-')] CELLS = [col for col in train_features.columns if col.startswith('c-')] for col in (GENES + CELLS): vec_len = len(train_features[col].values) vec_len_test = len(test_features[col].values) raw_vec = pd.concat([train_features, test_features])[col].values.reshape(vec_len+vec_len_test, 1) if IS_TRAIN: transformer = QuantileTransformer(n_quantiles=100, random_state=0, output_distribution="normal") transformer.fit(raw_vec) pd.to_pickle(transformer, f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') else: transformer = pd.read_pickle(f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') train_features[col] = transformer.transform(train_features[col].values.reshape(vec_len, 1)).reshape(1, vec_len)[0] test_features[col] = transformer.transform(test_features[col].values.reshape(vec_len_test, 1)).reshape(1, vec_len_test)[0] # + papermill={"duration": 122.985066, "end_time": "2020-11-30T17:28:55.827709", "exception": false, "start_time": "2020-11-30T17:26:52.842643", "status": "completed"} tags=[] # GENES n_comp = 50 n_dim = 15 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])]) if IS_TRAIN: pca = PCA(n_components=n_comp, random_state=DEFAULT_SEED).fit(train_features[GENES]) umap = UMAP(n_components=n_dim, random_state=DEFAULT_SEED).fit(train_features[GENES]) pd.to_pickle(pca, f"{MODEL_DIR}/{NB}_pca_g.pkl") pd.to_pickle(umap, f"{MODEL_DIR}/{NB}_umap_g.pkl") else: pca = pd.read_pickle(f"{MODEL_DIR}/{NB}_pca_g.pkl") umap = pd.read_pickle(f"{MODEL_DIR}/{NB}_umap_g.pkl") data2 = pca.transform(data[GENES]) data3 = umap.transform(data[GENES]) train2 = data2[:train_features.shape[0]] test2 = data2[-test_features.shape[0]:] train3 = data3[:train_features.shape[0]] test3 = data3[-test_features.shape[0]:] train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)]) train3 = pd.DataFrame(train3, columns=[f'umap_G-{i}' for i in range(n_dim)]) test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)]) test3 = pd.DataFrame(test3, columns=[f'umap_G-{i}' for i in range(n_dim)]) train_features = pd.concat((train_features, train2, train3), axis=1) test_features = pd.concat((test_features, test2, test3), axis=1) #CELLS n_comp = 15 n_dim = 5 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])]) if IS_TRAIN: pca = PCA(n_components=n_comp, random_state=DEFAULT_SEED).fit(train_features[CELLS]) umap = UMAP(n_components=n_dim, random_state=DEFAULT_SEED).fit(train_features[CELLS]) pd.to_pickle(pca, f"{MODEL_DIR}/{NB}_pca_c.pkl") pd.to_pickle(umap, f"{MODEL_DIR}/{NB}_umap_c.pkl") else: pca = pd.read_pickle(f"{MODEL_DIR}/{NB}_pca_c.pkl") umap = pd.read_pickle(f"{MODEL_DIR}/{NB}_umap_c.pkl") data2 = pca.transform(data[CELLS]) data3 = umap.transform(data[CELLS]) train2 = data2[:train_features.shape[0]] test2 = data2[-test_features.shape[0]:] train3 = data3[:train_features.shape[0]] test3 = data3[-test_features.shape[0]:] train2 = pd.DataFrame(train2, columns=[f'pca_C-{i}' for i in range(n_comp)]) train3 = pd.DataFrame(train3, columns=[f'umap_C-{i}' for i in range(n_dim)]) test2 = pd.DataFrame(test2, columns=[f'pca_C-{i}' for i in range(n_comp)]) test3 = pd.DataFrame(test3, columns=[f'umap_C-{i}' for i in range(n_dim)]) train_features = pd.concat((train_features, train2, train3), axis=1) test_features = pd.concat((test_features, test2, test3), axis=1) # drop_cols = [f'c-{i}' for i in range(n_comp,len(CELLS))] # + papermill={"duration": 0.74868, "end_time": "2020-11-30T17:28:56.629721", "exception": false, "start_time": "2020-11-30T17:28:55.881041", "status": "completed"} tags=[] from sklearn.feature_selection import VarianceThreshold if IS_TRAIN: var_thresh = VarianceThreshold(threshold=0.5).fit(train_features.iloc[:, 4:]) pd.to_pickle(var_thresh, f"{MODEL_DIR}/{NB}_variance_thresh0_5.pkl") else: var_thresh = pd.read_pickle(f"{MODEL_DIR}/{NB}_variance_thresh0_5.pkl") data = train_features.append(test_features) data_transformed = var_thresh.transform(data.iloc[:, 4:]) train_features_transformed = data_transformed[ : train_features.shape[0]] test_features_transformed = data_transformed[-test_features.shape[0] : ] train_features = pd.DataFrame(train_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\ columns=['sig_id','cp_type','cp_time','cp_dose']) train_features = pd.concat([train_features, pd.DataFrame(train_features_transformed)], axis=1) test_features = pd.DataFrame(test_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\ columns=['sig_id','cp_type','cp_time','cp_dose']) test_features = pd.concat([test_features, pd.DataFrame(test_features_transformed)], axis=1) print(train_features.shape) print(test_features.shape) # + papermill={"duration": 0.255663, "end_time": "2020-11-30T17:28:56.940924", "exception": false, "start_time": "2020-11-30T17:28:56.685261", "status": "completed"} tags=[] train = train_features[train_features['cp_type']!='ctl_vehicle'].reset_index(drop=True) test = test_features[test_features['cp_type']!='ctl_vehicle'].reset_index(drop=True) train = train.drop('cp_type', axis=1) test = test.drop('cp_type', axis=1) # + papermill={"duration": 0.467941, "end_time": "2020-11-30T17:28:57.462437", "exception": false, "start_time": "2020-11-30T17:28:56.994496", "status": "completed"} tags=[] train.to_pickle(f"{INT_DIR}/{NB}_train_preprocessed.pkl") test.to_pickle(f"{INT_DIR}/{NB}_test_preprocessed.pkl") # + [markdown] papermill={"duration": 0.054159, "end_time": "2020-11-30T17:28:57.572463", "exception": false, "start_time": "2020-11-30T17:28:57.518304", "status": "completed"} tags=[] # ## 203-101-nonscored-pred-2layers.ipynb # + papermill={"duration": 0.068347, "end_time": "2020-11-30T17:28:57.694621", "exception": false, "start_time": "2020-11-30T17:28:57.626274", "status": "completed"} tags=[] # file name prefix NB = '203' # IS_TRAIN = True # MODEL_DIR = "model" # "../model" # INT_DIR = "interim" # "../interim" DEVICE = ('cuda' if torch.cuda.is_available() else 'cpu') # label smoothing PMIN = 0.0 PMAX = 1.0 # submission smoothing SMIN = 0.0 SMAX = 1.0 # model hyper params HIDDEN_SIZE = 2048 # training hyper params EPOCHS = 15 BATCH_SIZE = 2048 NFOLDS = 10 # 10 NREPEATS = 1 NSEEDS = 5 # 5 # Adam hyper params LEARNING_RATE = 5e-4 WEIGHT_DECAY = 1e-5 # scheduler hyper params PCT_START = 0.2 DIV_FACS = 1e3 MAX_LR = 1e-2 # + papermill={"duration": 0.086161, "end_time": "2020-11-30T17:28:57.834659", "exception": false, "start_time": "2020-11-30T17:28:57.748498", "status": "completed"} tags=[] def process_data(data): data = pd.get_dummies(data, columns=['cp_time','cp_dose']) return data class MoADataset: def __init__(self, features, targets): self.features = features self.targets = targets def __len__(self): return (self.features.shape[0]) def __getitem__(self, idx): dct = { 'x' : torch.tensor(self.features[idx, :], dtype=torch.float), 'y' : torch.tensor(self.targets[idx, :], dtype=torch.float) } return dct class TestDataset: def __init__(self, features): self.features = features def __len__(self): return (self.features.shape[0]) def __getitem__(self, idx): dct = { 'x' : torch.tensor(self.features[idx, :], dtype=torch.float) } return dct def train_fn(model, optimizer, scheduler, loss_fn, dataloader, device): model.train() final_loss = 0 for data in dataloader: optimizer.zero_grad() inputs, targets = data['x'].to(device), data['y'].to(device) # print(inputs.shape) outputs = model(inputs) loss = loss_fn(outputs, targets) loss.backward() optimizer.step() scheduler.step() final_loss += loss.item() final_loss /= len(dataloader) return final_loss def valid_fn(model, loss_fn, dataloader, device): model.eval() final_loss = 0 valid_preds = [] for data in dataloader: inputs, targets = data['x'].to(device), data['y'].to(device) outputs = model(inputs) loss = loss_fn(outputs, targets) final_loss += loss.item() valid_preds.append(outputs.sigmoid().detach().cpu().numpy()) final_loss /= len(dataloader) valid_preds = np.concatenate(valid_preds) return final_loss, valid_preds def inference_fn(model, dataloader, device): model.eval() preds = [] for data in dataloader: inputs = data['x'].to(device) with torch.no_grad(): outputs = model(inputs) preds.append(outputs.sigmoid().detach().cpu().numpy()) preds = np.concatenate(preds) return preds def calc_valid_log_loss(train, target, target_cols): y_pred = train[target_cols].values y_true = target[target_cols].values y_true_t = torch.from_numpy(y_true.astype(np.float64)).clone() y_pred_t = torch.from_numpy(y_pred.astype(np.float64)).clone() return torch.nn.BCELoss()(y_pred_t, y_true_t).to('cpu').detach().numpy().copy() # + papermill={"duration": 0.069469, "end_time": "2020-11-30T17:28:57.968770", "exception": false, "start_time": "2020-11-30T17:28:57.899301", "status": "completed"} tags=[] class Model(nn.Module): def __init__(self, num_features, num_targets, hidden_size=HIDDEN_SIZE): super(Model, self).__init__() self.batch_norm1 = nn.BatchNorm1d(num_features) self.dropout1 = nn.Dropout(0.2) self.dense1 = nn.utils.weight_norm(nn.Linear(num_features, hidden_size)) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(0.25) self.dense3 = nn.utils.weight_norm(nn.Linear(hidden_size, num_targets)) def forward(self, x): x = self.batch_norm1(x) x = self.dropout1(x) x = F.relu(self.dense1(x)) x = self.batch_norm3(x) x = self.dropout3(x) x = self.dense3(x) return x # + papermill={"duration": 0.088602, "end_time": "2020-11-30T17:28:58.112487", "exception": false, "start_time": "2020-11-30T17:28:58.023885", "status": "completed"} tags=[] def run_training(train, test, trn_idx, val_idx, feature_cols, target_cols, fold, seed): seed_everything(seed) train_ = process_data(train) test_ = process_data(test) train_df = train_.loc[trn_idx,:].reset_index(drop=True) valid_df = train_.loc[val_idx,:].reset_index(drop=True) x_train, y_train = train_df[feature_cols].values, train_df[target_cols].values x_valid, y_valid = valid_df[feature_cols].values, valid_df[target_cols].values train_dataset = MoADataset(x_train, y_train) valid_dataset = MoADataset(x_valid, y_valid) trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True) validloader = torch.utils.data.DataLoader(valid_dataset, batch_size=BATCH_SIZE, shuffle=False) model = Model( num_features=len(feature_cols), num_targets=len(target_cols), ) model.to(DEVICE) optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY) scheduler = optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=PCT_START, div_factor=DIV_FACS, max_lr=MAX_LR, epochs=EPOCHS, steps_per_epoch=len(trainloader)) loss_fn = nn.BCEWithLogitsLoss() oof = np.zeros((len(train), target.iloc[:, 1:].shape[1])) best_loss = np.inf best_loss_epoch = -1 if IS_TRAIN: for epoch in range(EPOCHS): train_loss = train_fn(model, optimizer, scheduler, loss_fn, trainloader, DEVICE) valid_loss, valid_preds = valid_fn(model, loss_fn, validloader, DEVICE) if valid_loss < best_loss: best_loss = valid_loss best_loss_epoch = epoch oof[val_idx] = valid_preds model.to('cpu') torch.save(model.state_dict(), f"{MODEL_DIR}/{NB}_nonscored_SEED{seed}_FOLD{fold}_.pth") model.to(DEVICE) if epoch % 10 == 0 or epoch == EPOCHS-1: print(f"seed: {seed}, FOLD: {fold}, EPOCH: {epoch}, train_loss: {train_loss:.6f}, valid_loss: {valid_loss:.6f}, best_loss: {best_loss:.6f}, best_loss_epoch: {best_loss_epoch}") #--------------------- PREDICTION--------------------- x_test = test_[feature_cols].values testdataset = TestDataset(x_test) testloader = torch.utils.data.DataLoader(testdataset, batch_size=BATCH_SIZE, shuffle=False) model = Model( num_features=len(feature_cols), num_targets=len(target_cols), ) model.load_state_dict(torch.load(f"{MODEL_DIR}/{NB}_nonscored_SEED{seed}_FOLD{fold}_.pth")) model.to(DEVICE) if not IS_TRAIN: valid_loss, valid_preds = valid_fn(model, loss_fn, validloader, DEVICE) oof[val_idx] = valid_preds predictions = np.zeros((len(test_), target.iloc[:, 1:].shape[1])) predictions = inference_fn(model, testloader, DEVICE) return oof, predictions # + papermill={"duration": 0.066545, "end_time": "2020-11-30T17:28:58.234265", "exception": false, "start_time": "2020-11-30T17:28:58.167720", "status": "completed"} tags=[] def run_k_fold(train, test, feature_cols, target_cols, NFOLDS, seed): oof = np.zeros((len(train), len(target_cols))) predictions = np.zeros((len(test), len(target_cols))) mskf = RepeatedMultilabelStratifiedKFold(n_splits=NFOLDS, n_repeats=NREPEATS, random_state=None) for f, (t_idx, v_idx) in enumerate(mskf.split(X=train, y=target)): oof_, pred_ = run_training(train, test, t_idx, v_idx, feature_cols, target_cols, f, seed) predictions += pred_ / NFOLDS / NREPEATS oof += oof_ / NREPEATS return oof, predictions # + papermill={"duration": 0.066459, "end_time": "2020-11-30T17:28:58.355653", "exception": false, "start_time": "2020-11-30T17:28:58.289194", "status": "completed"} tags=[] def run_seeds(train, test, feature_cols, target_cols, nfolds=NFOLDS, nseed=NSEEDS): seed_list = range(nseed) oof = np.zeros((len(train), len(target_cols))) predictions = np.zeros((len(test), len(target_cols))) time_start = time.time() for seed in seed_list: oof_, predictions_ = run_k_fold(train, test, feature_cols, target_cols, nfolds, seed) oof += oof_ / nseed predictions += predictions_ / nseed print(f"seed {seed}, elapsed time: {time.time() - time_start}") train[target_cols] = oof test[target_cols] = predictions # + papermill={"duration": 5.585977, "end_time": "2020-11-30T17:29:04.004441", "exception": false, "start_time": "2020-11-30T17:28:58.418464", "status": "completed"} tags=[] train_features = pd.read_csv('../input/lish-moa/train_features.csv') train_targets_scored = pd.read_csv('../input/lish-moa/train_targets_scored.csv') train_targets_nonscored = pd.read_csv('../input/lish-moa/train_targets_nonscored.csv') test_features = pd.read_csv('../input/lish-moa/test_features.csv') sample_submission = pd.read_csv('../input/lish-moa/sample_submission.csv') # + papermill={"duration": 0.301913, "end_time": "2020-11-30T17:29:04.362253", "exception": false, "start_time": "2020-11-30T17:29:04.060340", "status": "completed"} tags=[] train = pd.read_pickle(f"{INT_DIR}/101_train_preprocessed.pkl") test = pd.read_pickle(f"{INT_DIR}/101_test_preprocessed.pkl") # + papermill={"duration": 0.539266, "end_time": "2020-11-30T17:29:04.962362", "exception": false, "start_time": "2020-11-30T17:29:04.423096", "status": "completed"} tags=[] train_trainbook = pd.read_pickle("../input/503-203-tabnet-with-nonscored-features-train/interim/101_train_preprocessed.pkl") test_trainbook = pd.read_pickle("../input/503-203-tabnet-with-nonscored-features-train/interim/101_test_preprocessed.pkl") # + papermill={"duration": 0.141322, "end_time": "2020-11-30T17:29:05.197903", "exception": false, "start_time": "2020-11-30T17:29:05.056581", "status": "completed"} tags=[] train_trainbook.head() # + papermill={"duration": 0.13252, "end_time": "2020-11-30T17:29:05.454419", "exception": false, "start_time": "2020-11-30T17:29:05.321899", "status": "completed"} tags=[] train.head() # + papermill={"duration": 0.109191, "end_time": "2020-11-30T17:29:05.650319", "exception": false, "start_time": "2020-11-30T17:29:05.541128", "status": "completed"} tags=[] test_trainbook.head() # + papermill={"duration": 0.085079, "end_time": "2020-11-30T17:29:05.793600", "exception": false, "start_time": "2020-11-30T17:29:05.708521", "status": "completed"} tags=[] test.head() # + [markdown] papermill={"duration": 0.05757, "end_time": "2020-11-30T17:29:05.908861", "exception": false, "start_time": "2020-11-30T17:29:05.851291", "status": "completed"} tags=[] # ### non-scored labels prediction # + papermill={"duration": 0.386359, "end_time": "2020-11-30T17:29:06.353081", "exception": false, "start_time": "2020-11-30T17:29:05.966722", "status": "completed"} tags=[] # remove nonscored labels if all values == 0 train_targets_nonscored = train_targets_nonscored.loc[:, train_targets_nonscored.sum() != 0] print(train_targets_nonscored.shape) train = train.merge(train_targets_nonscored, on='sig_id') # + papermill={"duration": 0.276663, "end_time": "2020-11-30T17:29:06.689900", "exception": false, "start_time": "2020-11-30T17:29:06.413237", "status": "completed"} tags=[] target = train[train_targets_nonscored.columns] target_cols = target.drop('sig_id', axis=1).columns.values.tolist() feature_cols = [c for c in process_data(train).columns if c not in target_cols and c not in ['kfold','sig_id']] # + papermill={"duration": 73.437271, "end_time": "2020-11-30T17:30:20.186209", "exception": false, "start_time": "2020-11-30T17:29:06.748938", "status": "completed"} tags=[] run_seeds(train, test, feature_cols, target_cols) # + papermill={"duration": 0.096668, "end_time": "2020-11-30T17:30:20.347687", "exception": false, "start_time": "2020-11-30T17:30:20.251019", "status": "completed"} tags=[] print(f"train shape: {train.shape}") print(f"test shape: {test.shape}") print(f"features : {len(feature_cols)}") print(f"targets : {len(target_cols)}") # + papermill={"duration": 0.659268, "end_time": "2020-11-30T17:30:21.081370", "exception": false, "start_time": "2020-11-30T17:30:20.422102", "status": "completed"} tags=[] valid_loss_total = calc_valid_log_loss(train, target, target_cols) print(f"CV loss: {valid_loss_total}") # + papermill={"duration": 0.663406, "end_time": "2020-11-30T17:30:21.809212", "exception": false, "start_time": "2020-11-30T17:30:21.145806", "status": "completed"} tags=[] train.to_pickle(f"{INT_DIR}/{NB}_train_nonscored_pred.pkl") test.to_pickle(f"{INT_DIR}/{NB}_test_nonscored_pred.pkl") # + papermill={"duration": 1.984803, "end_time": "2020-11-30T17:30:23.857733", "exception": false, "start_time": "2020-11-30T17:30:21.872930", "status": "completed"} tags=[] valid_results = train_targets_nonscored.drop(columns=target_cols).merge(train[['sig_id']+target_cols], on='sig_id', how='left').fillna(0) y_true = train_targets_nonscored[target_cols].values y_true = y_true > 0.5 y_pred = valid_results[target_cols].values score = 0 for i in range(len(target_cols)): score_ = log_loss(y_true[:, i], y_pred[:, i]) score += score_ / target.shape[1] print("CV log_loss: ", score) # + [markdown] papermill={"duration": 0.093009, "end_time": "2020-11-30T17:30:24.017382", "exception": false, "start_time": "2020-11-30T17:30:23.924373", "status": "completed"} tags=[] # ## 503-203-tabnet-with-nonscored-features-10fold3seed # + papermill={"duration": 9.392582, "end_time": "2020-11-30T17:30:33.477588", "exception": false, "start_time": "2020-11-30T17:30:24.085006", "status": "completed"} tags=[] # !pip install --no-index --find-links /kaggle/input/pytorchtabnet/pytorch_tabnet-2.0.0-py3-none-any.whl pytorch-tabnet # + papermill={"duration": 0.09091, "end_time": "2020-11-30T17:30:33.657414", "exception": false, "start_time": "2020-11-30T17:30:33.566504", "status": "completed"} tags=[] from pytorch_tabnet.tab_model import TabNetRegressor # + papermill={"duration": 0.077498, "end_time": "2020-11-30T17:30:33.803409", "exception": false, "start_time": "2020-11-30T17:30:33.725911", "status": "completed"} tags=[] def seed_everything(seed_value): random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) os.environ['PYTHONHASHSEED'] = str(seed_value) if torch.cuda.is_available(): torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False seed_everything(42) # + papermill={"duration": 0.079131, "end_time": "2020-11-30T17:30:33.948966", "exception": false, "start_time": "2020-11-30T17:30:33.869835", "status": "completed"} tags=[] # file name prefix NB = '503' NB_PREV = '203' # IS_TRAIN = False # MODEL_DIR = "../input/moa503/503-tabnet" # "../model" # INT_DIR = "../input/moa503/203-nonscored-pred" # "../interim" DEVICE = ('cuda' if torch.cuda.is_available() else 'cpu') # label smoothing PMIN = 0.0 PMAX = 1.0 # submission smoothing SMIN = 0.0 SMAX = 1.0 # model hyper params # training hyper params # EPOCHS = 25 # BATCH_SIZE = 256 NFOLDS = 10 # 10 NREPEATS = 1 NSEEDS = 3 # 5 # Adam hyper params LEARNING_RATE = 5e-4 WEIGHT_DECAY = 1e-5 # scheduler hyper params PCT_START = 0.2 DIV_FACS = 1e3 MAX_LR = 1e-2 # + papermill={"duration": 5.383198, "end_time": "2020-11-30T17:30:39.404440", "exception": false, "start_time": "2020-11-30T17:30:34.021242", "status": "completed"} tags=[] train_features = pd.read_csv('../input/lish-moa/train_features.csv') train_targets_scored = pd.read_csv('../input/lish-moa/train_targets_scored.csv') train_targets_nonscored = pd.read_csv('../input/lish-moa/train_targets_nonscored.csv') test_features = pd.read_csv('../input/lish-moa/test_features.csv') sample_submission = pd.read_csv('../input/lish-moa/sample_submission.csv') # + papermill={"duration": 0.076301, "end_time": "2020-11-30T17:30:39.551665", "exception": false, "start_time": "2020-11-30T17:30:39.475364", "status": "completed"} tags=[] # test_features_dummy = pd.read_csv('../input/dummytestfeatures/test_features_dummy.csv') # test_features = pd.concat([test_features, test_features_dummy]).reset_index(drop=True) # + papermill={"duration": 0.070952, "end_time": "2020-11-30T17:30:39.690971", "exception": false, "start_time": "2020-11-30T17:30:39.620019", "status": "completed"} tags=[] # + papermill={"duration": 0.079954, "end_time": "2020-11-30T17:30:39.838062", "exception": false, "start_time": "2020-11-30T17:30:39.758108", "status": "completed"} tags=[] print("(nsamples, nfeatures)") print(train_features.shape) print(train_targets_scored.shape) print(train_targets_nonscored.shape) print(test_features.shape) print(sample_submission.shape) # + papermill={"duration": 0.077096, "end_time": "2020-11-30T17:30:39.982993", "exception": false, "start_time": "2020-11-30T17:30:39.905897", "status": "completed"} tags=[] GENES = [col for col in train_features.columns if col.startswith('g-')] CELLS = [col for col in train_features.columns if col.startswith('c-')] # + papermill={"duration": 8.772218, "end_time": "2020-11-30T17:30:48.823127", "exception": false, "start_time": "2020-11-30T17:30:40.050909", "status": "completed"} tags=[] from sklearn.preprocessing import QuantileTransformer use_test_for_preprocessing = False for col in (GENES + CELLS): if IS_TRAIN: transformer = QuantileTransformer(n_quantiles=100, random_state=0, output_distribution="normal") if use_test_for_preprocessing: raw_vec = pd.concat([train_features, test_features])[col].values.reshape(vec_len+vec_len_test, 1) transformer.fit(raw_vec) else: raw_vec = train_features[col].values.reshape(vec_len, 1) transformer.fit(raw_vec) pd.to_pickle(transformer, f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') else: transformer = pd.read_pickle(f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') vec_len = len(train_features[col].values) vec_len_test = len(test_features[col].values) train_features[col] = transformer.transform(train_features[col].values.reshape(vec_len, 1)).reshape(1, vec_len)[0] test_features[col] = transformer.transform(test_features[col].values.reshape(vec_len_test, 1)).reshape(1, vec_len_test)[0] # + papermill={"duration": 0.942467, "end_time": "2020-11-30T17:30:49.834352", "exception": false, "start_time": "2020-11-30T17:30:48.891885", "status": "completed"} tags=[] # GENES n_comp = 90 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])]) if IS_TRAIN: fa = FactorAnalysis(n_components=n_comp, random_state=42).fit(data[GENES]) pd.to_pickle(fa, f'{MODEL_DIR}/{NB}_factor_analysis_g.pkl') else: fa = pd.read_pickle(f'{MODEL_DIR}/{NB}_factor_analysis_g.pkl') data2 = (fa.transform(data[GENES])) train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:] train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)]) test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)]) # drop_cols = [f'c-{i}' for i in range(n_comp,len(GENES))] train_features = pd.concat((train_features, train2), axis=1) test_features = pd.concat((test_features, test2), axis=1) #CELLS n_comp = 50 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])]) if IS_TRAIN: fa = FactorAnalysis(n_components=n_comp, random_state=42).fit(data[CELLS]) pd.to_pickle(fa, f'{MODEL_DIR}/{NB}_factor_analysis_c.pkl') else: fa = pd.read_pickle(f'{MODEL_DIR}/{NB}_factor_analysis_c.pkl') data2 = (fa.transform(data[CELLS])) train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:] train2 = pd.DataFrame(train2, columns=[f'pca_C-{i}' for i in range(n_comp)]) test2 = pd.DataFrame(test2, columns=[f'pca_C-{i}' for i in range(n_comp)]) # drop_cols = [f'c-{i}' for i in range(n_comp,len(CELLS))] train_features = pd.concat((train_features, train2), axis=1) test_features = pd.concat((test_features, test2), axis=1) # + papermill={"duration": 0.075859, "end_time": "2020-11-30T17:30:49.979064", "exception": false, "start_time": "2020-11-30T17:30:49.903205", "status": "completed"} tags=[] # features_g = list(train_features.columns[4:776]) # train_ = train_features[features_g].copy() # test_ = test_features[features_g].copy() # data = pd.concat([train_, test_], axis = 0) # km = KMeans(n_clusters=35, random_state=123).fit(data) # + papermill={"duration": 0.076165, "end_time": "2020-11-30T17:30:50.124377", "exception": false, "start_time": "2020-11-30T17:30:50.048212", "status": "completed"} tags=[] # km.predict(data) # + papermill={"duration": 0.07612, "end_time": "2020-11-30T17:30:50.268643", "exception": false, "start_time": "2020-11-30T17:30:50.192523", "status": "completed"} tags=[] # km.labels_ # + papermill={"duration": 0.998627, "end_time": "2020-11-30T17:30:51.335655", "exception": false, "start_time": "2020-11-30T17:30:50.337028", "status": "completed"} tags=[] from sklearn.cluster import KMeans def fe_cluster(train, test, n_clusters_g = 35, n_clusters_c = 5, SEED = 123): features_g = list(train.columns[4:776]) features_c = list(train.columns[776:876]) def create_cluster(train, test, features, kind = 'g', n_clusters = n_clusters_g): train_ = train[features].copy() test_ = test[features].copy() data = pd.concat([train_, test_], axis = 0) if IS_TRAIN: kmeans = KMeans(n_clusters = n_clusters, random_state = SEED).fit(data) pd.to_pickle(kmeans, f"{MODEL_DIR}/{NB}_kmeans_{kind}.pkl") else: kmeans = pd.read_pickle(f"{MODEL_DIR}/{NB}_kmeans_{kind}.pkl") train[f'clusters_{kind}'] = kmeans.predict(train_) test[f'clusters_{kind}'] = kmeans.predict(test_) train = pd.get_dummies(train, columns = [f'clusters_{kind}']) test = pd.get_dummies(test, columns = [f'clusters_{kind}']) return train, test train, test = create_cluster(train, test, features_g, kind = 'g', n_clusters = n_clusters_g) train, test = create_cluster(train, test, features_c, kind = 'c', n_clusters = n_clusters_c) return train, test train_features ,test_features=fe_cluster(train_features,test_features) # + papermill={"duration": 0.080488, "end_time": "2020-11-30T17:30:51.486318", "exception": false, "start_time": "2020-11-30T17:30:51.405830", "status": "completed"} tags=[] print(train_features.shape) print(test_features.shape) # + papermill={"duration": 4.639258, "end_time": "2020-11-30T17:30:56.195661", "exception": false, "start_time": "2020-11-30T17:30:51.556403", "status": "completed"} tags=[] def fe_stats(train, test): features_g = list(train.columns[4:776]) features_c = list(train.columns[776:876]) for df in train, test: # df['g_sum'] = df[features_g].sum(axis = 1) df['g_mean'] = df[features_g].mean(axis = 1) df['g_std'] = df[features_g].std(axis = 1) df['g_kurt'] = df[features_g].kurtosis(axis = 1) df['g_skew'] = df[features_g].skew(axis = 1) # df['c_sum'] = df[features_c].sum(axis = 1) df['c_mean'] = df[features_c].mean(axis = 1) df['c_std'] = df[features_c].std(axis = 1) df['c_kurt'] = df[features_c].kurtosis(axis = 1) df['c_skew'] = df[features_c].skew(axis = 1) # df['gc_sum'] = df[features_g + features_c].sum(axis = 1) df['gc_mean'] = df[features_g + features_c].mean(axis = 1) df['gc_std'] = df[features_g + features_c].std(axis = 1) df['gc_kurt'] = df[features_g + features_c].kurtosis(axis = 1) df['gc_skew'] = df[features_g + features_c].skew(axis = 1) return train, test train_features,test_features=fe_stats(train_features,test_features) # + papermill={"duration": 0.081529, "end_time": "2020-11-30T17:30:56.355491", "exception": false, "start_time": "2020-11-30T17:30:56.273962", "status": "completed"} tags=[] print(train_features.shape) print(test_features.shape) # + papermill={"duration": 0.434849, "end_time": "2020-11-30T17:30:56.860902", "exception": false, "start_time": "2020-11-30T17:30:56.426053", "status": "completed"} tags=[] remove_vehicle = True if remove_vehicle: trt_idx = train_features['cp_type']=='trt_cp' train_features = train_features.loc[trt_idx].reset_index(drop=True) train_targets_scored = train_targets_scored.loc[trt_idx].reset_index(drop=True) train_targets_nonscored = train_targets_nonscored.loc[trt_idx].reset_index(drop=True) else: pass # + papermill={"duration": 0.734138, "end_time": "2020-11-30T17:30:57.666412", "exception": false, "start_time": "2020-11-30T17:30:56.932274", "status": "completed"} tags=[] # train = train_features.merge(train_targets_scored, on='sig_id') train = train_features.merge(train_targets_scored, on='sig_id') train = train[train['cp_type']!='ctl_vehicle'].reset_index(drop=True) test = test_features[test_features['cp_type']!='ctl_vehicle'].reset_index(drop=True) # target = train[train_targets_scored.columns] target = train[train_targets_scored.columns] target_cols = target.drop('sig_id', axis=1).columns.values.tolist() train = train.drop('cp_type', axis=1) test = test.drop('cp_type', axis=1) # + papermill={"duration": 0.082974, "end_time": "2020-11-30T17:30:57.820937", "exception": false, "start_time": "2020-11-30T17:30:57.737963", "status": "completed"} tags=[] print(target.shape) print(train_features.shape) print(test_features.shape) print(train.shape) print(test.shape) # + papermill={"duration": 0.432945, "end_time": "2020-11-30T17:30:58.327557", "exception": false, "start_time": "2020-11-30T17:30:57.894612", "status": "completed"} tags=[] train_nonscored_pred = pd.read_pickle(f'{INT_DIR}/{NB_PREV}_train_nonscored_pred.pkl') test_nonscored_pred = pd.read_pickle(f'{INT_DIR}/{NB_PREV}_test_nonscored_pred.pkl') # + papermill={"duration": 0.249826, "end_time": "2020-11-30T17:30:58.649057", "exception": false, "start_time": "2020-11-30T17:30:58.399231", "status": "completed"} tags=[] # remove nonscored labels if all values == 0 train_targets_nonscored = train_targets_nonscored.loc[:, train_targets_nonscored.sum() != 0] # nonscored_targets = [c for c in train_targets_nonscored.columns if c != "sig_id"] # + papermill={"duration": 0.426211, "end_time": "2020-11-30T17:30:59.148780", "exception": false, "start_time": "2020-11-30T17:30:58.722569", "status": "completed"} tags=[] train = train.merge(train_nonscored_pred[train_targets_nonscored.columns], on='sig_id') test = test.merge(test_nonscored_pred[train_targets_nonscored.columns], on='sig_id') # + papermill={"duration": 3.160543, "end_time": "2020-11-30T17:31:02.380521", "exception": false, "start_time": "2020-11-30T17:30:59.219978", "status": "completed"} tags=[] from sklearn.preprocessing import QuantileTransformer nonscored_target = [c for c in train_targets_nonscored.columns if c != "sig_id"] for col in (nonscored_target): vec_len = len(train[col].values) vec_len_test = len(test[col].values) # raw_vec = pd.concat([train, test])[col].values.reshape(vec_len+vec_len_test, 1) raw_vec = train[col].values.reshape(vec_len, 1) if IS_TRAIN: transformer = QuantileTransformer(n_quantiles=100, random_state=0, output_distribution="normal") transformer.fit(raw_vec) pd.to_pickle(transformer, f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') else: transformer = pd.read_pickle(f'{MODEL_DIR}/{NB}_{col}_quantile_transformer.pkl') train[col] = transformer.transform(raw_vec).reshape(1, vec_len)[0] test[col] = transformer.transform(test[col].values.reshape(vec_len_test, 1)).reshape(1, vec_len_test)[0] # + papermill={"duration": 0.092253, "end_time": "2020-11-30T17:31:02.544951", "exception": false, "start_time": "2020-11-30T17:31:02.452698", "status": "completed"} tags=[] feature_cols = [c for c in train.columns if c not in target_cols] feature_cols = [c for c in feature_cols if c not in ['sig_id']] len(feature_cols) # + papermill={"duration": 0.082087, "end_time": "2020-11-30T17:31:02.700644", "exception": false, "start_time": "2020-11-30T17:31:02.618557", "status": "completed"} tags=[] num_features=len(feature_cols) num_targets=len(target_cols) # + papermill={"duration": 0.094142, "end_time": "2020-11-30T17:31:02.867277", "exception": false, "start_time": "2020-11-30T17:31:02.773135", "status": "completed"} tags=[] import torch import torch.nn as nn from pytorch_tabnet.metrics import Metric class LabelSmoothing(nn.Module): """ NLL loss with label smoothing. """ def __init__(self, smoothing=0.0, n_cls=2): """ Constructor for the LabelSmoothing module. :param smoothing: label smoothing factor """ super(LabelSmoothing, self).__init__() self.confidence = 1.0 - smoothing + smoothing / n_cls self.smoothing = smoothing / n_cls def forward(self, x, target): probs = torch.nn.functional.sigmoid(x,) # ylogy + (1-y)log(1-y) #with torch.no_grad(): target1 = self.confidence * target + (1-target) * self.smoothing #print(target1.cpu()) loss = -(torch.log(probs+1e-15) * target1 + (1-target1) * torch.log(1-probs+1e-15)) #print(loss.cpu()) #nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1)) #nll_loss = nll_loss.squeeze(1) #smooth_loss = -logprobs.mean(dim=-1) #loss = self.confidence * nll_loss + self.smoothing * smooth_loss return loss.mean() class SmoothedLogLossMetric(Metric): """ BCE with logit loss """ def __init__(self, smoothing=0.001): self._name = f"{smoothing:.3f}" # write an understandable name here self._maximize = False self._lossfn = LabelSmoothing(smoothing) def __call__(self, y_true, y_score): """ """ y_true = torch.from_numpy(y_true.astype(np.float32)).clone() y_score = torch.from_numpy(y_score.astype(np.float32)).clone() # print("smoothed log loss metric: ", self._lossfn(y_score, y_true).to('cpu').detach().numpy().copy()) return self._lossfn(y_score, y_true).to('cpu').detach().numpy().copy().take(0) class LogLossMetric(Metric): """ BCE with logit loss """ def __init__(self, smoothing=0.0): self._name = f"{smoothing:.3f}" # write an understandable name here self._maximize = False self._lossfn = LabelSmoothing(smoothing) def __call__(self, y_true, y_score): """ """ y_true = torch.from_numpy(y_true.astype(np.float32)).clone() y_score = torch.from_numpy(y_score.astype(np.float32)).clone() # print("log loss metric: ", self._lossfn(y_score, y_true).to('cpu').detach().numpy().copy()) return self._lossfn(y_score, y_true).to('cpu').detach().numpy().copy().take(0) # + papermill={"duration": 0.122885, "end_time": "2020-11-30T17:31:03.061965", "exception": false, "start_time": "2020-11-30T17:31:02.939080", "status": "completed"} tags=[] def process_data(data): # data = pd.get_dummies(data, columns=['cp_time','cp_dose']) data.loc[:, 'cp_time'] = data.loc[:, 'cp_time'].map({24: 0, 48: 1, 72: 2, 0: 0, 1: 1, 2: 2}) data.loc[:, 'cp_dose'] = data.loc[:, 'cp_dose'].map({'D1': 0, 'D2': 1, 0: 0, 1: 1}) return data def run_training_tabnet(train, test, trn_idx, val_idx, feature_cols, target_cols, fold, seed, filename="tabnet"): seed_everything(seed) train_ = process_data(train) test_ = process_data(test) train_df = train_.loc[trn_idx,:].reset_index(drop=True) valid_df = train_.loc[val_idx,:].reset_index(drop=True) x_train, y_train = train_df[feature_cols].values, train_df[target_cols].values x_valid, y_valid = valid_df[feature_cols].values, valid_df[target_cols].values model = TabNetRegressor(n_d=32, n_a=32, n_steps=1, lambda_sparse=0, cat_dims=[3, 2], cat_emb_dim=[1, 1], cat_idxs=[0, 1], optimizer_fn=torch.optim.Adam, optimizer_params=dict(lr=2e-2, weight_decay=1e-5), mask_type='entmax', # device_name=DEVICE, scheduler_params=dict(milestones=[100, 150], gamma=0.9),#) scheduler_fn=torch.optim.lr_scheduler.MultiStepLR, verbose=10, seed = seed) loss_fn = LabelSmoothing(0.001) # eval_metric = SmoothedLogLossMetric(0.001) # eval_metric_nosmoothing = SmoothedLogLossMetric(0.) oof = np.zeros((len(train), target.iloc[:, 1:].shape[1])) if IS_TRAIN: # print("isnan", np.any(np.isnan(x_train))) model.fit(X_train=x_train, y_train=y_train, eval_set=[(x_valid, y_valid)], eval_metric=[LogLossMetric, SmoothedLogLossMetric], max_epochs=200, patience=50, batch_size=1024, virtual_batch_size=128, num_workers=0, drop_last=False, loss_fn=loss_fn ) model.save_model(f"{MODEL_DIR}/{NB}_{filename}_SEED{seed}_FOLD{fold}") #--------------------- PREDICTION--------------------- x_test = test_[feature_cols].values model = TabNetRegressor(n_d=32, n_a=32, n_steps=1, lambda_sparse=0, cat_dims=[3, 2], cat_emb_dim=[1, 1], cat_idxs=[0, 1], optimizer_fn=torch.optim.Adam, optimizer_params=dict(lr=2e-2, weight_decay=1e-5), mask_type='entmax', # device_name=DEVICE, scheduler_params=dict(milestones=[100, 150], gamma=0.9),#) scheduler_fn=torch.optim.lr_scheduler.MultiStepLR, verbose=10, seed = seed) model.load_model(f"{MODEL_DIR}/{NB}_{filename}_SEED{seed}_FOLD{fold}.model") valid_preds = model.predict(x_valid) valid_preds = torch.sigmoid(torch.as_tensor(valid_preds)).detach().cpu().numpy() oof[val_idx] = valid_preds predictions = model.predict(x_test) predictions = torch.sigmoid(torch.as_tensor(predictions)).detach().cpu().numpy() return oof, predictions # + papermill={"duration": 0.138606, "end_time": "2020-11-30T17:31:03.314194", "exception": false, "start_time": "2020-11-30T17:31:03.175588", "status": "completed"} tags=[] def run_k_fold(train, test, feature_cols, target_cols, NFOLDS, seed): oof = np.zeros((len(train), len(target_cols))) predictions = np.zeros((len(test), len(target_cols))) mskf = MultilabelStratifiedKFold(n_splits=NFOLDS, shuffle=True, random_state = seed) for f, (t_idx, v_idx) in enumerate(mskf.split(X=train, y=target)): oof_, pred_ = run_training_tabnet(train, test, t_idx, v_idx, feature_cols, target_cols, f, seed) predictions += pred_ / NFOLDS / NREPEATS oof += oof_ / NREPEATS return oof, predictions def run_seeds(train, test, feature_cols, target_cols, nfolds=NFOLDS, nseed=NSEEDS): seed_list = range(nseed) oof = np.zeros((len(train), len(target_cols))) predictions = np.zeros((len(test), len(target_cols))) time_start = time.time() for seed in seed_list: oof_, predictions_ = run_k_fold(train, test, feature_cols, target_cols, nfolds, seed) oof += oof_ / nseed predictions += predictions_ / nseed print(f"seed {seed}, elapsed time: {time.time() - time_start}") train[target_cols] = oof test[target_cols] = predictions # + papermill={"duration": 0.888024, "end_time": "2020-11-30T17:31:04.304905", "exception": false, "start_time": "2020-11-30T17:31:03.416881", "status": "completed"} tags=[] train.to_pickle(f"{INT_DIR}/{NB}_pre_train.pkl") test.to_pickle(f"{INT_DIR}/{NB}_pre_test.pkl") # + papermill={"duration": 42.642497, "end_time": "2020-11-30T17:31:47.022753", "exception": false, "start_time": "2020-11-30T17:31:04.380256", "status": "completed"} tags=[] run_seeds(train, test, feature_cols, target_cols, NFOLDS, NSEEDS) # + papermill={"duration": 0.765549, "end_time": "2020-11-30T17:31:47.892623", "exception": false, "start_time": "2020-11-30T17:31:47.127074", "status": "completed"} tags=[] train.to_pickle(f"{INT_DIR}/{NB}_train.pkl") test.to_pickle(f"{INT_DIR}/{NB}_test.pkl") # + papermill={"duration": 1.209492, "end_time": "2020-11-30T17:31:49.194319", "exception": false, "start_time": "2020-11-30T17:31:47.984827", "status": "completed"} tags=[] # train[target_cols] = np.maximum(PMIN, np.minimum(PMAX, train[target_cols])) valid_results = train_targets_scored.drop(columns=target_cols).merge(train[['sig_id']+target_cols], on='sig_id', how='left').fillna(0) y_true = train_targets_scored[target_cols].values y_true = y_true > 0.5 y_pred = valid_results[target_cols].values score = 0 for i in range(len(target_cols)): score_ = log_loss(y_true[:, i], y_pred[:, i]) score += score_ / target.shape[1] print("CV log_loss: ", score) # + papermill={"duration": 2.243205, "end_time": "2020-11-30T17:31:51.531553", "exception": false, "start_time": "2020-11-30T17:31:49.288348", "status": "completed"} tags=[] sub6 = sample_submission.drop(columns=target_cols).merge(test[['sig_id']+target_cols], on='sig_id', how='left').fillna(0) sub6.to_csv('submission.csv', index=False) # + papermill={"duration": 0.134249, "end_time": "2020-11-30T17:31:51.769621", "exception": false, "start_time": "2020-11-30T17:31:51.635372", "status": "completed"} tags=[] sub6 # + papermill={"duration": 0.101302, "end_time": "2020-11-30T17:31:51.965544", "exception": false, "start_time": "2020-11-30T17:31:51.864242", "status": "completed"} tags=[] import glob # + papermill={"duration": 5.908104, "end_time": "2020-11-30T17:31:57.967803", "exception": false, "start_time": "2020-11-30T17:31:52.059699", "status": "completed"} tags=[] # !mkdir -p /root/.cache/torch/hub/checkpoints/ # !cp ../input/gen-efficientnet-pretrained/tf_efficientnet_*.pth /root/.cache/torch/hub/checkpoints/ # !cp ../input/deepinsight-resnest-v2-resnest50-output/resnest50_fast_2s2x40d-9d126481.pth /root/.cache/torch/hub/checkpoints/ # !ls -la /root/.cache/torch/hub/checkpoints/ # + papermill={"duration": 400.73258, "end_time": "2020-11-30T17:38:38.814802", "exception": false, "start_time": "2020-11-30T17:31:58.082222", "status": "completed"} tags=[] # !python ../input/markscripts/deepinsight_resnest_lightning_v2_infer.py sub5 = pd.read_csv('submission_resnest_v2.csv') # + papermill={"duration": 433.722822, "end_time": "2020-11-30T17:45:52.785469", "exception": false, "start_time": "2020-11-30T17:38:39.062647", "status": "completed"} tags=[] # !python ../input/markscripts/deepinsight_efficientnet_lightning_v7_b3_infer.py sub4 = pd.read_csv('./submission_effnet_v7_b3.csv') # + papermill={"duration": 141.001385, "end_time": "2020-11-30T17:48:14.023941", "exception": false, "start_time": "2020-11-30T17:45:53.022556", "status": "completed"} tags=[] # ! python ../input/updatedsimplenn/simpleNN_without_ns_newcv.py sub3 = pd.read_csv('./submission.csv') # + papermill={"duration": 183.384957, "end_time": "2020-11-30T17:51:17.696406", "exception": false, "start_time": "2020-11-30T17:48:14.311449", "status": "completed"} tags=[] test = pd.read_csv('../input/lish-moa/test_features.csv') # !python ../input/python-scripts-moa/2heads_1836_oldcv.py sub2 = pd.read_csv('./submission.csv') # + papermill={"duration": 265.327229, "end_time": "2020-11-30T17:55:43.364367", "exception": false, "start_time": "2020-11-30T17:51:18.037138", "status": "completed"} tags=[] # !python ../input/python2stagenn/2stageNN_with_ns_oldcv.py sub1 = pd.read_csv('./submission_2stageNN_with_ns_oldcv_0.01822.csv') # + papermill={"duration": 84.511542, "end_time": "2020-11-30T17:57:08.201593", "exception": false, "start_time": "2020-11-30T17:55:43.690051", "status": "completed"} tags=[] # !python ../input/simplennoldcvfinal/script_NN_836_final.py sub7 = pd.read_csv('submission_script_simpleNN_oldcv_0.01836.csv') # + papermill={"duration": 2.685288, "end_time": "2020-11-30T17:57:11.374800", "exception": false, "start_time": "2020-11-30T17:57:08.689512", "status": "completed"} tags=[] submission = pd.read_csv('../input/lish-moa/sample_submission.csv') submission.iloc[:, 1:] = 0 submission.iloc[:, 1:] = (sub1.iloc[:,1:]*0.37 + sub3.iloc[:,1:]*0.1 + sub4.iloc[:,1:]*0.18 +sub5.iloc[:,1:]*0.15)*0.9 + sub6.iloc[:,1:]*0.1 + sub7.iloc[:,1:]*0.09 + sub2.iloc[:,1:]*0.09 submission.to_csv('submission.csv', index=False) # + papermill={"duration": 0.324209, "end_time": "2020-11-30T17:57:12.026035", "exception": false, "start_time": "2020-11-30T17:57:11.701826", "status": "completed"} tags=[] # + papermill={"duration": 0.588238, "end_time": "2020-11-30T17:57:12.937499", "exception": false, "start_time": "2020-11-30T17:57:12.349261", "status": "completed"} tags=[] # + papermill={"duration": 0.39776, "end_time": "2020-11-30T17:57:13.853755", "exception": false, "start_time": "2020-11-30T17:57:13.455995", "status": "completed"} tags=[] # + papermill={"duration": 0.331314, "end_time": "2020-11-30T17:57:14.515253", "exception": false, "start_time": "2020-11-30T17:57:14.183939", "status": "completed"} tags=[] # + papermill={"duration": 0.322281, "end_time": "2020-11-30T17:57:15.162596", "exception": false, "start_time": "2020-11-30T17:57:14.840315", "status": "completed"} tags=[] # + papermill={"duration": 0.501582, "end_time": "2020-11-30T17:57:15.996751", "exception": false, "start_time": "2020-11-30T17:57:15.495169", "status": "completed"} tags=[] # + papermill={"duration": 0.333951, "end_time": "2020-11-30T17:57:16.813192", "exception": false, "start_time": "2020-11-30T17:57:16.479241", "status": "completed"} tags=[]
final/Best LB/fork-of-blending-with-6-models-5old-1new.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 # # # Wolfcamp Example - Single las file # # # This example shows the full petrophysical workflow avaiable in PetroPy # for a single wolfcamp las file courtesy of University Lands Texas. # # The workflow progresses in these 11 steps # # 1. Read las file and create a :class:`petropy.Log` object # 2. Load tops from a csv file using :meth:`petropy.Log.tops_from_csv` # 3. Create a :class:`petropy.LogViewer` show in edit_mode to fix data # 4. Define formations for calculations. # 5. Calculate fluid properties by # 1. Loading parameters via :meth:`petropy.Log.fluid_properties_parameters_from_csv` # 2. Calculating over formations via :meth:`petropy.Log.formation_fluid_properties` # 6. Calculate mulitmineral properties by # 1. Loading parameters via :meth:`petropy.Log.multimineral_parameters_from_csv` # 2. Calculating over formations via :meth:`petropy.Log.formation_multimineral_model` # 7. Curve summations via :meth:`petropy.Log.summations` # 8. Adding pay flags via :meth:`petropy.Log.add_pay_flag` # 9. Clustering intervals into Electrofacies via :meth:`petropy.electrofacies` # 10. Exporting log statistics via :meth:`petropy.Log.statistics` # 11. Saving LogViewer to png and Log to las # # To bulk process a folder of las files at once, use the `bulk example`_ . # # Downloading the script at the bottom of this webpage will not download the required las # file or PetroPy logo. To download all files, view the `examples folder`_ on GitHub. # # # # + import petropy as ptr # import pyplot to add logo to figure import matplotlib.pyplot as plt ### 1. Read las file # create a Log object by reading a file path # las_file_path = '42303347740000.las' log = ptr.Log(las_file_path) ### 2. load tops ### tops_file_path = 'tops.csv' log.tops_from_csv(tops_file_path) ### 3. graphically edit log ### # use manual mode for fixing borehole washout # # and other changes requiring redrawing data # # use bulk shift mode to linearly adjust all # # curve data # # close both windows to continue program # viewer = ptr.LogViewer(log, top = 6950, height = 100) viewer.show(edit_mode = True) # overwrite log variable with updated log # # from LogViewer edits # log = viewer.log ### 4. define formations ### f = ['WFMPA', 'WFMPB', 'WFMPC'] ### 5. fluid properties ### # load fluid properties from a csv file # # since path is not specified, load default # # csv file included with petropy # log.fluid_properties_parameters_from_csv() # calculate fluid properties over defined # # formations with parameter WFMP from # # previously loaded csv # log.formation_fluid_properties(f, parameter = 'WFMP') ### 6. multimineral model ### # load multimineral parameters from csv file # # since path is not specified, load default # # csv file included with petropy # log.multimineral_parameters_from_csv() # calculate multiminearl model over defined # # formations with parameter WFMP from # # previously loaded csv # log.formation_multimineral_model(f, parameter = 'WFMP') ### 7. summations ### # define curves to calculate cumulative values # c = ['OIP', 'BVH', 'PHIE'] # calculate cumulative values over formations # log.summations(f, curves = c) ### 8. pay flags ### # define pay flogs as list of tuples for # # (curve, value) # flag_1_gtoe = [('PHIE', 0.03)] flag_2_gtoe = [('PAY_FLAG_1', 1), ('BVH', 0.02)] flag_3_gtoe = [('PAY_FLAG_2', 1)] flag_3_ltoe = [('SW', 0.2)] # add pay flags over defined formations # log.add_pay_flag(f, greater_than_or_equal = flag_1_gtoe) log.add_pay_flag(f, greater_than_or_equal = flag_2_gtoe) log.add_pay_flag(f, greater_than_or_equal = flag_3_gtoe, less_than_or_equal = flag_3_ltoe) ### 9. electrofacies ### # define curves to use in electofaceis module # electro_logs = ['GR_N', 'RESDEEP_N', 'NPHI_N', 'RHOB_N', 'PE_N'] # make a list of Log objects as input # logs = [log] # calculate electrofacies for the defined logs# # over the specified formations # # finding 6 clusters of electrofacies # # with RESDEEP_N logarithmically scaled # logs = ptr.electrofacies(logs, f, electro_logs, 6, log_scale = ['RESDEEP_N']) # unpack log object from returned list # log = logs[0] ### 10. statistics ### # define list of curves to find statistics # stats_curves = ['OIP', 'BVH', 'PHIE', 'SW', 'VCLAY', 'TOC'] # calculate stats over specified formation and# # save to csv file wfmp_statistics.csv # # update the line if the well, formation is # # already included in the csv file # log.statistics_to_csv('wfmp_statistics.csv', replace = True, formations = f, curves = stats_curves) ### 11. export data ### # find way to name well, looking for well name# # or UWI or API # if len(log.well['WELL'].value) > 0: well_name = log.well['WELL'].value elif len(str(log.well['UWI'].value)) > 0: well_name = str(log.well['UWI'].value) elif len(log.well['API'].value) > 0: well_name = str(log.well['API'].value) else: well_name = 'UNKNOWN' well_name = well_name.replace('.', '') # scale height of viewer to top and bottom # # of calculated values # wfmpa_top = log.tops['WFMPA'] wfmpc_base = log.next_formation_depth('WFMPC') top = wfmpa_top height = wfmpc_base - wfmpa_top # create LogViewer with the default full_oil # # template included in petropy # viewer = ptr.LogViewer(log, top = top, height = height, template_defaults = 'full_oil') # set viewer to 17x11 inches size for use in # # PowerPoint or printing to larger paper # viewer.fig.set_size_inches(17, 11) # add well_name to title of LogViewer # viewer.fig.suptitle(well_name, fontweight = 'bold', fontsize = 30) # add logo to top left corner # logo_im = plt.imread('company_logo.png') logo_ax = viewer.fig.add_axes([0, 0.85, 0.2, 0.2]) logo_ax.imshow(logo_im) logo_ax.axis('off') # add text to top right corner # if len(str(log.well['UWI'].value)) > 0: label = 'UWI: ' + str(log.well['UWI'].value) + '\n' elif len(log.well['API'].value) > 0: label = 'API: ' + str(log.well['API'].value) + '\n' else: label = '' label += 'County: Reagan\nCreated By: <NAME>\n' label += 'Creation Date: October 23, 2017' viewer.axes[0].annotate(label, xy = (0.99,0.99), xycoords = 'figure fraction', horizontalalignment = 'right', verticalalignment = 'top', fontsize = 14) # save figure and log # viewer_file_name=r'%s_processed.png' % well_name las_file_name = r'%s_processed.las' % well_name viewer.fig.savefig(viewer_file_name) viewer.log.write(las_file_name)
doc/auto_examples/wolfcamp_single.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 from urllib.request import urlopen import scipy.optimize import random from math import exp from math import log # + def parseData(fname): for l in urlopen(fname): yield eval(l) print("Reading data...") data = list(parseData("http://jmcauley.ucsd.edu/cse190/data/beer/beer_50000.json")) print("done") def inner(x,y): return sum([x[i]*y[i] for i in range(len(x))]) def sigmoid(x): return 1.0 / (1 + exp(-x)) # - def feature(datum): feat = [1, datum['review/taste'], datum['review/appearance'], datum['review/aroma'], datum['review/palate'], datum['review/overall']] return feat # + def feature(datum): datum_text=datum['review/text'].lower().split() feat = [1, datum_text.count("lactic"),datum_text.count("tart"),datum_text.count("sour"),datum_text.count("citric"),datum_text.count("sweet"),datum_text.count("acid"),datum_text.count("hop"),datum_text.count("fruit"),datum_text.count("salt"),datum_text.count("spicy")] return feat # - X = [feature(d) for d in data] y = [d['beer/ABV'] >= 6.5 for d in data] X_train = X[:int(len(X)/3)] X_valid = X[int(len(X)/3):int(2*len(X)/3)] X_test = X[int(2*len(X)/3):] y_train = y[:int(len(y)/3)] y_valid = y[int(len(y)/3):int(2*len(y)/3)] y_test = y[int(2*len(y)/3):] X[0] N=len(y_train) coeff_1=N/(2*sum(y_train)) coeff_0=N/(2*(N-sum(y_train))) print(coeff_1) print(coeff_0) print('the number in training set is ',len(y_train)) print('num of positive',sum(y_train)) print('number of negative',len(y_train)-sum(y_train)) print('coefficient before loglikehood is ',len(y_train)/(2*sum(y_train))) print('coefficient before loglikehood for y =0 is ',) # + ################################################## # Logistic regression by gradient ascent # ################################################## # NEGATIVE Log-likelihood def f(theta, X, y, lam): loglikelihood = 0 for i in range(len(X)): logit = inner(X[i], theta) if y[i]: loglikelihood -= log(1 + exp(-logit))*coeff_1 else: loglikelihood -= (logit+log(1+exp(-logit)))*coeff_0 for k in range(len(theta)): loglikelihood -= lam * theta[k]*theta[k] # for debugging # print("ll =" + str(loglikelihood)) return -loglikelihood # NEGATIVE Derivative of log-likelihood def fprime(theta, X, y, lam): dl = [0]*len(theta) for i in range(len(X)): logit = inner(X[i], theta) for k in range(len(theta)): if y[i]: dl[k] += X[i][k] * (1 - sigmoid(logit))*coeff_1 if not y[i]: dl[k] += X[i][k]*(-coeff_0)+X[i][k] * (1 - sigmoid(logit))*coeff_0 for k in range(len(theta)): dl[k] -= lam*2*theta[k] return numpy.array([-x for x in dl]) # - ################################################## # Train # ################################################## def train(lam): theta,_,_ = scipy.optimize.fmin_l_bfgs_b(f, [0]*len(X_train[0]), fprime, pgtol = 10, args = (X_train, y_train, lam)) return theta # + ################################################## # Predict # ################################################## def performance_valid(theta): scores_valid = [inner(theta,x) for x in X_valid] predictions_valid = [s > 0 for s in scores_valid] correct_valid = [(a==b) for (a,b) in zip(predictions_valid,y_valid)] acc_valid = sum(correct_valid) * 1.0 / len(correct_valid) return acc_valid def performance_test(theta): scores_test = [inner(theta,x) for x in X_test] predictions_test = [s > 0 for s in scores_test] correct_test = [(a==b) for (a,b) in zip(predictions_test,y_test)] acc_test = sum(correct_test) * 1.0 / len(correct_test) return acc_test def performance_train(theta): scores_train = [inner(theta,x) for x in X_train] predictions_train = [s > 0 for s in scores_train] correct_train = [(a==b) for (a,b) in zip(predictions_train,y_train)] acc_train = sum(correct_train) * 1.0 / len(correct_train) return acc_train # - def evaluate_classifier_test(theta): scores_test = [inner(theta,x) for x in X_test] predictions_test = [s > 0 for s in scores_test] true_positive = [1 if a==1 and b==1 else 0 for (a,b) in zip(predictions_test,y_test)] true_negative = [1 if a==0 and b==0 else 0 for (a,b) in zip(predictions_test,y_test)] false_positive = [1 if a==1 and b==0 else 0 for (a,b) in zip(predictions_test,y_test)] false_negative = [1 if a==0 and b==1 else 0 for (a,b) in zip(predictions_test,y_test)] TP=sum(true_positive) TN=sum(true_negative) FP=sum(false_positive) FN=sum(false_negative) FPR=FP/(FP+TN) FNR=FN/(FN+TP) BER=0.5*(FPR+FNR) print("number of true positive on test is ",TP) print("number of true negative on test is ",TN) print("number of false positive on test is ",FP) print("number of false negative on test is ",FN) print("Balanced Error Rate for test: ",BER) # also can calculate the length of ttpp = [ 1 for (a,b) in zip(predictions_test,y_test) if a==1 and b==1] def evaluate_classifier_train(theta): scores_train = [inner(theta,x) for x in X_train] predictions_train = [s > 0 for s in scores_train] true_positive = [1 if a==1 and b==1 else 0 for (a,b) in zip(predictions_train,y_train)] true_negative = [1 if a==0 and b==0 else 0 for (a,b) in zip(predictions_train,y_train)] false_positive = [1 if a==1 and b==0 else 0 for (a,b) in zip(predictions_train,y_train)] false_negative = [1 if a==0 and b==1 else 0 for (a,b) in zip(predictions_train,y_train)] TP=sum(true_positive) TN=sum(true_negative) FP=sum(false_positive) FN=sum(false_negative) FPR=FP/(FP+TN) FNR=FN/(FN+TP) BER=0.5*(FPR+FNR) #print("number of true positive on test is ",TP) #print("number of true negative on test is ",TN) #print("number of false positive on test is ",FP) #print("number of false negative on test is ",FN) print("Balanced Error Rate for train: ",BER) def evaluate_classifier_valid(theta): scores_valid = [inner(theta,x) for x in X_valid] predictions_valid = [s > 0 for s in scores_valid] true_positive = [1 if a==1 and b==1 else 0 for (a,b) in zip(predictions_valid,y_valid)] true_negative = [1 if a==0 and b==0 else 0 for (a,b) in zip(predictions_valid,y_valid)] false_positive = [1 if a==1 and b==0 else 0 for (a,b) in zip(predictions_valid,y_valid)] false_negative = [1 if a==0 and b==1 else 0 for (a,b) in zip(predictions_valid,y_valid)] TP=sum(true_positive) TN=sum(true_negative) FP=sum(false_positive) FN=sum(false_negative) FPR=FP/(FP+TN) FNR=FN/(FN+TP) BER=0.5*(FPR+FNR) #print("number of true positive on test is ",TP) #print("number of true negative on test is ",TN) #print("number of false positive on test is ",FP) #print("number of false negative on test is ",FN) print("Balanced Error Rate for valid: ",BER) # + ################################################## # Validation pipeline # ################################################## lam = 1.0 theta = train(lam) acc_valid = performance_valid(theta) acc_test = performance_test(theta) print("lambda = " + str(lam) + ":\taccuracy for validation set is\t" + str(acc_valid)) print("lambda = " + str(lam) + ":\taccuracy for test set is\t" + str(acc_test)) evaluate_classifier_test(theta) evaluate_classifier_train(theta) evaluate_classifier_valid(theta) # - #(5) lam = [0,0.01,0.1] for i in lam: theta = train(i) acc_train = performance_train(theta) acc_valid = performance_valid(theta) acc_test = performance_test(theta) print("lambda = " + str(i) + ":\taccuracy for train set is\t" + str(acc_train)) print("lambda = " + str(i) + ":\taccuracy for validation set is\t" + str(acc_valid)) print("lambda = " + str(i) + ":\taccuracy for test set is\t" + str(acc_test)) scores_test = [inner(theta,x) for x in X_test] predictions_test = [s > 0 for s in scores_test] true_positive = [1 if a==1 and b==1 else 0 for (a,b) in zip(predictions_test,y_test)] true_negative = [1 if a==0 and b==0 else 0 for (a,b) in zip(predictions_test,y_test)] false_positive = [1 if a==1 and b==0 else 0 for (a,b) in zip(predictions_test,y_test)] false_negative = [1 if a==0 and b==1 else 0 for (a,b) in zip(predictions_test,y_test)] TP=sum(true_positive) TN=sum(true_negative) FP=sum(false_positive) FN=sum(false_negative) FPR=FP/(FP+TN) FNR=FN/(FN+TP) BER=0.5*(FPR+FNR) print("number of true positive on test is ",TP) print("number of true negative on test is ",TN) print("number of false positive on test is ",FP) print("number of false positive on test is ",FN) print("Balanced Error Rate: ",BER) ttpp = [ 1 for (a,b) in zip(predictions_test,y_test) if a==1 and b==1] print(len(ttpp))
CSE258 Recommender System and Web Mining/hw2/code/CSE258hw2problem1.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 model import numpy as np import matplotlib.pyplot as plt import cobra # model originally from: # <NAME>, <NAME>, <NAME>, et al (2012) Genome-scale metabolic reconstructions of Pichia stipitis and Pichia pastoris and in silico evaluation of their potentials. BMC Syst Biol 6:24. doi: 10.1186/1752-0509-6-24. # model with heterologous protein production was used as starting point for our simulation: # <NAME>, <NAME>, <NAME>, <NAME> (2016) Genome-scale metabolic model of Pichia pastoris with native and humanized glycosylation of recombinant proteins. Biotechnol Bioeng 113:961โ€“969. doi: 10.1002/bit.25863. # it is common for these models to give some warnings when uploaded for the first time, so in order to avoid them, it is just required to rewrite the model as follows #pheast = cobra.io.read_sbml_model("./data/ihGlycopastoris.xml") #cobra.io.write_sbml_model(pheast,"./data/ihGlycopastoris_rewritten.xml") pheast = cobra.io.read_sbml_model("./data/ihGlycopastoris_rewritten.xml") # - import pandas as pd # In the original model the production of FAB protein was included, but we want to remove its reactions # those will be include protein transport and protein production (dna, rna, amino acid sequence and protein) pheast.reactions.query("FAB", "name") # we also remove the metabolites related to FAB, which will be those related to dna, rna and amino acid sequence, as well as the protein in different compartments pheast.metabolites.query("FAB", "name") # + # first remove the heterologous protein production reactions from the paper pheast.remove_reactions([pheast.reactions.r1337, pheast.reactions.r1338, pheast.reactions.r1100, pheast.reactions.r1101, pheast.reactions.r1102, pheast.reactions.r1103]) # and all the species related to the protein (dna, rna, aa and the protein on different compartments) pheast.remove_metabolites([pheast.metabolites.m1360, pheast.metabolites.m1361, pheast.metabolites.m1362, pheast.metabolites.m1363, pheast.metabolites.m1364]) # + # run the model/optimizes for cell growth # the usual approach for these models is to optimize cell growth/biomass production, which is also done here (reaction r1339 in this model) # one can always choose other reactions to be optimized, as will be seen later on pheast.summary() # optimize() and summary() methods run the same process, but as the name indicates, # summary outputs some information for uptake and secretion besides the optimization result, offered by optimize() method # - # one metabolite is uptaken with a rate of 1 mmol gDW^-1 h^-1 (classic GSM models units) pheast.metabolites.m2 # there is one secretion reaction (r764), insertion of glucose into the cytosol by using ATP (r552) # the glucose uptake reaction (r1145) is where the uptake constraints are defined # it is seen that glucose is limited to an uptake of a rate of 1 mmol gDW^-1 h^-1 (classic GSM models units) pheast.reactions.r1145 # first, it was wanted to see how phaffii grew on methanol (as a natural methylotroph) --> look for methanol reactions pheast.reactions.query("methanol", "name") # this is methanol uptake pheast.reactions.r1158 # One can also query for upper-case methanol and get all reactions of the MUT pathway pheast.reactions.query("Methanol", "name") # right now the carbon source is glucose --> this is changed to methanol (Methanol_CH4O) instead pheast.reactions.r1145.bounds = 0, 0 # we force to not upatke any glucose pheast.reactions.r1158.bounds = 0, 1 # methanol at 1 mmol gDW^-1 h^-1 # now it grows on methanol (slower than in glucose) pheast.summary() # no methane yet in the model pheast.metabolites.query("methane", "name") # There are already some predefined compartments in the model, that are required to specify new species: pheast.compartments # Next steps are for the introduction of new metabolties and reactions to the model to simulate our system: # + # we add methane on the extracellular compartment e_methane = cobra.Metabolite( 'e_methane', formula='CH4', name='extracellular_methane', compartment='C_e') pheast.add_metabolites([e_methane]) # + # make reactions # from literature (<NAME>., & <NAME>. (2016). Methane-oxidizing enzymes: an upstream problem in biological gas-to-liquids conversion. Journal of the American Chemical Society, 138(30), 9327-9340.) # it was found that the methane upatke for M. capsulatus pMMO is between 2.46 mmol/gDW h^-1 and 9 mmol/gDW h^-1, depdending on the copper concentration uptake_methane = cobra.Reaction( 'r_uptake_methane', name = 'Methane Uptake from Environment', lower_bound = 0, upper_bound = 9.0 # obtained from the reference ) methane_oxidation = cobra.Reaction( 'r_methane_oxidation', name = 'Methane Oxidation', lower_bound = 0, # meaning irreversibility upper_bound = 1000.0 # meaning that we don't know the production rate to constraint ) # add involved metabolites and stoichiometry uptake_methane.add_metabolites( { pheast.metabolites.e_methane: 1.0 } ) # pMMO reaction without redox coenzyme (in literature mostly ubiquinol is mentioned but neither there is # cytosolic ubiquinol in this model (only in mitochondria), nor does the literature agree on what its role may be exactly ) methane_oxidation.add_metabolites( { pheast.metabolites.e_methane: -1.0, pheast.metabolites.m1232: -1.0, pheast.metabolites.m1215: 1.0, pheast.metabolites.m139: 1.0, } ) # add gene dependency for pMMO reaction methane_oxidation.gene_reaction_rule = '( pMMO_A and pMMO_B and pMMO_C )' # add reactions to pheast pheast.add_reactions([uptake_methane, methane_oxidation]) # - pheast.reactions.r1158.bounds = 0, 0 # set methanol uptake to 0 and try if it grows on methane (as upper bound was set to 1) # it grows on methane (slower than methanol and glucose) pheast.summary() # we can copy the model to not modify the original one and knock-out one of the genes involved in pMMO, then it won't grow pheast_knock_out = pheast.copy() pheast_knock_out.genes.pMMO_C.knock_out() pheast_knock_out.summary() # + # we will now introduce our heterologous protein: leghemoglobin # we look at the detoxification pathway as there is a heme group in both catalase and hemoglobin which could # influence our system in general and the reaction introduced for production of (leg)hemoglobin pheast.metabolites.query("H2O2","name") # + # this is the peroxisomal H2O2 pheast.metabolites.m713 # + # this is the catalase reaction, heme is not considered pheast.reactions.r99 # + # we find there is a heme metabolite pheast.metabolites.query("Heme","name") # + # it is siroheme pheast.metabolites.m1060 # - # only involved in this reaction; it is also specifically a species of heme different from the one in catalse # and hemoglobin, so we should not take this one pheast.reactions.r487 # + # there are also a bunch of porypherin metabolites which are similar to the hemoglobin pheast.metabolites.query("porphyrin","name") # <NAME>, <NAME>, <NAME>, <NAME>a # Thirty years of heme catalases structural biology # Arch. Biochem. Biophys., 525 (2012), pp. 102-110 # According to the source above C34-heme b is the most abundant, so we could go for that (there are some C34 # poryphyrins) and introduce it in the catalase and later hemoglobin reaction but none are in the peroxisome # + # now we will introduce the heterologous proteins, pMMO and leghemoglobin, with reactions for dna replication, # transcription and translation # as the sequences are long, we calculate the stoichiometry with a script which is on the github repo and imported here # based on the logic behind introduction of heterologous protein production in the paper: # <NAME>, <NAME>, <NAME>, <NAME> (2016) Genome-scale metabolic model of Pichia pastoris with native and humanized glycosylation of recombinant proteins. Biotechnol Bioeng 113:961โ€“969. doi: 10.1002/bit.25863. # for that we define the following function import stoichiometry_gsm def add_protein_reaction(model, reaction, lb, ub, seq, seq_type, protein_name): stoichiometry = stoichiometry_gsm.get_stoichiometry(seq, seq_type, protein_name) reaction = cobra.Reaction( reaction, name = reaction, lower_bound = lb, upper_bound = ub ) for molecule in stoichiometry: reaction.add_metabolites( { getattr(model.metabolites, molecule): stoichiometry[molecule] } ) model.add_reactions([reaction]) # - # and get the sequences for our two recombinant proteins, pMMO and leghemoglobin. defined before in another file from sequences import * # + # add the metabolites to be produced by these reactions pMMO_DNA = cobra.Metabolite( 'pMMO_DNA', name='pMMO_DNA', compartment='C_c') pMMO_RNA = cobra.Metabolite( 'pMMO_RNA', name='pMMO_RNA', compartment='C_c') pMMO_AA = cobra.Metabolite( 'pMMO_AA', name='pMMO_AA', compartment='C_c') hemo_DNA = cobra.Metabolite( 'hemo_DNA', name='Hemo_DNA', compartment='C_c') hemo_RNA = cobra.Metabolite( 'hemo_RNA', name='Hemo_RNA', compartment='C_c') hemo_AA = cobra.Metabolite( 'hemo_AA', name='Leghemoglobin', compartment='C_c') pheast.add_metabolites([pMMO_DNA, pMMO_RNA, pMMO_AA, hemo_DNA, hemo_RNA, hemo_AA]) # - # make new reactions # !! make sure the protein name is the same as you defined the metabolites, otherwise it will fail add_protein_reaction(pheast, 'pMMO_DNA_reaction', 0, 1000, pMMO_dna_seq, 'dna', 'pMMO') add_protein_reaction(pheast, 'pMMO_RNA_reaction', 0, 1000, pMMO_rna_seq, 'rna', 'pMMO') add_protein_reaction(pheast, 'pMMO_AA_reaction', 0, 1000, pMMO_aa_seq, 'aa', 'pMMO') add_protein_reaction(pheast, 'hemo_DNA_reaction', 0, 1000, hemo_dna_seq, 'dna', 'hemo') add_protein_reaction(pheast, 'hemo_RNA_reaction', 0, 1000, hemo_rna_seq, 'rna', 'hemo') add_protein_reaction(pheast, 'hemo_AA_reaction', 0, 1000, hemo_aa_seq, 'aa', 'hemo') # + # also add transport to extracellular and boundary proteins as well as "Biosynthesis" reactions # this was all done in the paper pMMO_c = cobra.Metabolite( 'pMMO_c', formula='', name='pMMO_cytosolic', compartment='C_c') pMMO_e = cobra.Metabolite( 'pMMO_e', formula='', name='pMMO_extracellular', compartment='C_e') hemo_c = cobra.Metabolite( 'hemo_c', formula='', name='hemo_cytosolic', compartment='C_c') hemo_e = cobra.Metabolite( 'hemo_e', formula='', name='hemo_extracellular', compartment='C_e') pheast.add_metabolites([pMMO_c, pMMO_e, hemo_c, hemo_e]) # force the pMMO biosynthesis to the level taken as a basis for methane concentration calculation, see below # there we simulate assuming pMMO could be 5, 10 and 20% of protein # which corresponds to x-(x*(1-0.5)^(1/5)) taking a protein half life of 5 hours and where x is g/gDW of which # we assume 50% to be protein # 5% - 0.003 # 10% - 0.0065 # 20% - 0.013 pMMO_Biosynthesis = cobra.Reaction( 'pMMO_Biosynthesis', name = 'pMMO Biosynthesis', lower_bound = 0.0065, upper_bound = 0.0065 ) hemo_Biosynthesis = cobra.Reaction( 'hemo_Biosynthesis', name = 'LeghemoglobinBiosynthesis', lower_bound = 0.0, upper_bound = 1000.0 ) extrac_pMMO = cobra.Reaction( 'c_pMMO_e', name = 'extracellular transport pMMO', lower_bound = 0, upper_bound = 1000.0 ) extrac_Hemo = cobra.Reaction( 'c_Hemo_e', name = 'extracellular transport Leghemoglobin', lower_bound = 0, upper_bound = 1000.0 ) EX_hemo = cobra.Reaction( 'EX_hemo', name = 'hemoglobin exchange reaction', lower_bound = -1000.0, upper_bound = 1000.0 ) EX_pMMO = cobra.Reaction( 'EX_pMMO', name = 'pMMO exchange reaction', lower_bound = -1000.0, upper_bound = 1000.0 ) hemo_Biosynthesis.add_metabolites( { pheast.metabolites.hemo_DNA: -2.8e-05, pheast.metabolites.hemo_RNA: -0.0029, pheast.metabolites.hemo_AA: -0.997, pheast.metabolites.hemo_c: 1.0, } ) pMMO_Biosynthesis.add_metabolites( { pheast.metabolites.pMMO_DNA: -2.8e-05, pheast.metabolites.pMMO_RNA: -0.0029, pheast.metabolites.pMMO_AA: -0.997, pheast.metabolites.pMMO_c: 1.0, } ) extrac_pMMO.add_metabolites( { pheast.metabolites.pMMO_c: -1.0, pheast.metabolites.pMMO_e: 1.0 } ) extrac_Hemo.add_metabolites( { pheast.metabolites.hemo_c: -1.0, pheast.metabolites.hemo_e: 1.0 } ) EX_pMMO.add_metabolites( { pheast.metabolites.pMMO_e: -1.0 } ) EX_hemo.add_metabolites( { pheast.metabolites.hemo_e: -1.0 } ) pheast.add_reactions([extrac_pMMO, extrac_Hemo, pMMO_Biosynthesis, hemo_Biosynthesis, EX_hemo, EX_pMMO]) # - # One option is to once we have the protein production reaction, optimize hat reaction pheast.objective = pheast.problem.Objective(pheast.reactions.hemo_Biosynthesis.flux_expression) pheast_final = pheast.copy() pheast.summary() cobra.summary.MetaboliteSummary(metabolite= pheast.metabolites.hemo_c, model=pheast) cobra.summary.reaction_summary.ReactionSummary(reaction = pheast.reactions.hemo_Biosynthesis, model = pheast) # However the procedure used in original paper: # <NAME>, <NAME>, <NAME>, <NAME> (2016) Genome-scale metabolic model of Pichia pastoris with native and humanized glycosylation of recombinant proteins. Biotechnol Bioeng 113:961โ€“969. doi: 10.1002/bit.25863. # the procedure is first optimize for the growth, and then use this value as constrain in the next optimization of protein production pheast_growth_constraint = pheast.copy() pheast_growth_constraint.objective = pheast_growth_constraint.problem.Objective(pheast_growth_constraint.reactions.r1339.flux_expression) pheast_growth_constraint.reactions.r1339.bounds = pheast_growth_constraint.optimize().objective_value, pheast_growth_constraint.optimize().objective_value # and once constrained, we optimize the protein production reaction # but with this approach our model is unable to keep the optimal growth and produce recombinant proteins at the same time) # (which makes sense to us) pheast_growth_constraint.objective = pheast_growth_constraint.problem.Objective(pheast_growth_constraint.reactions.hemo_Biosynthesis.flux_expression) pheast_growth_constraint.summary() cobra.summary.MetaboliteSummary(metabolite= pheast_growth_constraint.metabolites.hemo_c, model=pheast_growth_constraint) # this command fails as there is no flux through this reaction cobra.summary.reaction_summary.ReactionSummary(reaction = pheast_growth_constraint.reactions.hemo_Biosynthesis, model = pheast_growth_constraint) # ## Now we check for knockouts and study how they behave # as recommended on cobrapy documentation the following command will be run to develop all model single deletions # https://cobrapy.readthedocs.io/en/latest/deletions.html from cobra.flux_analysis import (single_gene_deletion, single_reaction_deletion, double_gene_deletion,double_reaction_deletion) deletion_results = single_gene_deletion(pheast_final) #deletion_results pd.set_option("display.max_rows", None, "display.max_columns", None) deletion_results # + # we can try different scenarios of the methane oxidation reaction: # amount of protein in yeast cell is about 50% # https://bionumbers.hms.harvard.edu/bionumber.aspx?&id=102328 # AOX expression accounts for 5-30% --> thus we take 3 scenarios in which pMMO makes up (1)5, (2)10 and (3)20% of # total protein per gram DW # <NAME>., & <NAME>. (1980). Oxidation of methanol by the yeast, Pichia pastoris. Purification and properties of the alcohol oxidase. Agricultural and biological chemistry, 44(10), 2279-2289. # <NAME>., & <NAME>. (2013). Regulation of Pichia pastoris promoters and its consequences for protein production. New biotechnology, 30(4), 385-404. # expression under GAP in glucose medium can reach even higher ones compared to AOX in methanol : # <NAME>., <NAME>., & <NAME>. (2016). Comparison of ADH3 promoter with commonly used promoters for recombinant protein production in Pichia pastoris. Protein expression and purification, 121, 112-117. # <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (1997). Isolation of the Pichia pastoris glyceraldehyde-3-phosphate dehydrogenase gene and regulation and use of its promoter. Gene, 186(1), 37-44. # We leave that question open as there are no good absolute numbers and we cannot simulate switching media which we will do in vitro/vivo. # as the turnover rate for the pMMO is estimated/measured at about 0.5-2.5, we choose 1 as a conservative parameter # for our pMMO # <NAME>., & <NAME>. (2007). The biochemistry of methane oxidation. Annu. Rev. Biochem., 76, 223-241. # mass of pMMO is about 300 kDA # <NAME>., & <NAME>. (2017). A tale of two methane monooxygenases. JBIC Journal of Biological Inorganic Chemistry, 22(2-3), 307-319. # one pMMO has a weight of about 4.981620599999999e-19 # --> in one gDW there will be # (1) 0.025g pMMO --> 5.0184472e+16 molecules of pMMO --> 0.29999978778 mmol of CH4 -> CH3OH per gDW/h # (2) 0.05g pMMO --> 1.0036894e+17 molecules of pMMO --> 0.59999955165 mmol of CH4 -> CH3OH per gDW/h # (3) 0.1g pMMO --> 2.0073789e+17 molecules of pMMO --> 1.19999916309 mmol of CH4 -> CH3OH per gDW/h # e.g. pheast.reactions.methane_oxidation.bounds = -1000,0.59999955165 # or at the uptake level: pheast.reactions.uptake_methane = 0,1.19999916309 # --> pheast will metabolize as much methane as possible due to constraints of pMMO and methane availability # --> In a good scenario in which 20% of the total cell protein is pMMO, about 1.2 mmol/gDW/h corresponding to # about 0.02 g / 0.03 ml of methane per gDW/h (at a temperature of 37 degrees C with a CH4 density of 0.623 kg/m3) # (https://www.engineeringtoolbox.com/methane-density-specific-weight-temperature-pressure-d_2020.html) # are needed to reach maximal efficiency (limited by pMMO activity) # thus the process will have a bottleneck at the fermentation technology level # --> on the other hand if we expect to have at least 5% of the total cell protein to be functional pMMO with the # given turnover rate as 1, per gDW/h the culture would need 0.00772391 ml of methane to use it optimally # + def methane_ml_to_mmol_at_37(ml): return(ml*0.623/0.01604) def make_plot(model, precision, max_pMMO_percent): # vector for pMMO percentage pMMO_percentages = list(np.arange(0,max_pMMO_percent+precision,precision)) # from best case scenario we can say that 0.03ml is max methane uptake /gDW/h; we set it to 0.05 as we also # simulate 30% protein here and it is good to have some margin in any case methane_concentrations = list(np.arange(0,0.05+0.001,0.0001)) # results matrix plot = np.zeros([len(methane_concentrations),len(pMMO_percentages)]) xticks = [] yticks = set() for index1,pMMO in enumerate(pMMO_percentages): xticks.append(index1) for index2,methane in enumerate(methane_concentrations): yticks.add(index2) # calculate potential methane consumption # 1. convert g of pMMO to molecules to mmol # weight of pMMO = 4.981620599999999e-19, 0.5 as 50% protein in cell, 6E+23 avogadro's number, # 1000 because of mmol <-> mol, 3600 s <-> h mmol = ((pMMO/100)*0.5) / 4.981620599999999E-19 / 6.0221409E+23 * 1000 * 3600 # set uptake and optimise pheast.reactions.r_uptake_methane.bounds = 0,methane_ml_to_mmol_at_37(methane) pheast.reactions.r_methane_oxidation.bounds = 0,mmol plot[index2,index1] = pheast.optimize().objective_value yticks = list(yticks) imgplot = plt.imshow(plot,extent=[0,len(pMMO_percentages),len(methane_concentrations),0]) plt.colorbar() plt.title("Predicted Hemoglobin Production") plt.xlabel("% of active pMMO of total cell protein") plt.ylabel("ml of methane uptake/gDW/h") plt.gca().invert_yaxis() label_meth = methane_concentrations label_pMMO = pMMO_percentages plt.xticks([round(xticks[i],3) for i in range(0,len(xticks),50)], [round(label_pMMO[i],3) for i in range(0,len(label_pMMO),50)]) plt.yticks([round(yticks[i],3) for i in range(0,len(yticks),50)], [round(label_meth[i],3) for i in range(0,len(label_meth),50)]) make_plot(pheast,0.1,30) # + # thus the max yield of hemoglobin at a methane uptake at about 1.8 mmol/gDW/h (0.033 ml) and 30% of total protein # being functional pMMO would be (in a scenario knocking out the AOX) pheast.reactions.r_uptake_methane.bounds = 0,1.8 pheast.summary() # - # ## Plotting image plots # # Now, we want to use our new model that simulates our K. phaffii status to analyze the optimal environmental conditions for the maximal protein production. First of all, we will focus on oxygen and methane, as the unique carbon source considered. import numpy as np import matplotlib.pyplot as plt # we create a function to see how our protein production is optimize on different environments def image_plot(model, precision, max_met, max_ox): plot = np.zeros([precision, precision]) methane_vec = np.linspace(0,max_met,precision); oxygen_vec = np.linspace(0,max_ox,precision) for count_ox, oxygen in enumerate(oxygen_vec): for count_met, met in enumerate(methane_vec): #print(met, oxygen) model.reactions.r1160.bounds = oxygen, oxygen model.reactions.r_uptake_methane.bounds = met, met result = model.optimize().objective_value if result < 0: result = 0 plot[(precision-1 - count_ox), count_met] = result label_met = np.round(np.linspace(0, max_met, 6),1) label_ox = np.round(np.linspace(max_ox, 0,6),1) ticks = np.linspace(0, precision - 1,6) imgplot = plt.imshow(plot) plt.colorbar() #plt.gca().invert_yaxis() plt.title("Optimization of protein production on different environment uptake") plt.xlabel("Methane uptake") plt.ylabel("Oxygen uptake") plt.xticks(ticks, label_met) plt.yticks(ticks, label_ox) plt.grid() return plot max_met = 5; max_ox = 20; precision = 100 plot = image_plot(pheast_final, precision, max_met, max_ox) max_met = 10; max_ox = 30; precision = 100 plot = image_plot(pheast_final, precision, max_met, max_ox) # Therefore, we see that there is a correlation between methane and oxygen for the best protein production, in a way that this is closer to approx. 2:1 for oxygen:methane, respectively. But then, of course, the higher are those uptakes following the relation, the better is the protein production following a linear relation. # # The reasons we think for this plot shape is that, below the 1:1 relation between oxygen and methane, as we are forcing our model to uptake all the methane, it is unfeasible as for that we need the same amount of oxygen. Otherwise, some methane that we are forcing to get inside the cell, can't because we don't have enough oxygen. # # The gradient on protein production when increasing oxygen might be explained because when the relation is exactly 1:1, all oxygen is used for the uptake of methane and then all the protein we are producing comes from the amino acids uptaken from the environment. As soon, as we have more oxygen availbale, the cell is able to produce its own DNA, RNA and amino acids. # # (The upper limit on oxygen is also because we are forcing the cell to take all the oxygen. There must be some other reaction besides pMMO that is helping to get that oxygen inside the cell, otherwise we would just get a x=y line and all the rest would be inbfeasible. But the idea is that once these reactions reach their limit for oxygen, the model is infeasible.) # # Some explanation we have for the upper gradient is that once we surpass the optimal oxygen value for protein production, this extra oxygen requires some ATP to be metabolized instead of being used for protein production. # # It is infeasible for uppeer values of oxygen, for the same reason as for the methane because at some point we can't use all the oxygen available. # # We also found some limit on the amount of methane that can be uptaken even though we keep increasing the uptake of both. And actually, after some point the protein production starts to decrease. The reason we thouhgt for it is that there is this upper limit for reactions to go to 1000, then it might be that going up and up for this methane is saturating some of the reactions further down where some reaction is surpassing this 1000 limit. # # And right now we don't have any limit on methane uptake until that approx. 1000 because we don't have any toxicity for methanol nor any other product further down that is telling our model that it is not allowed to surpass some value for some given metabolite. # kept in case at some point we want to create a function with the second approach of keeping optimal growth as constrain precision = 10 met_max_uptake = 5 ox_max_uptake = 20 plot = np.zeros([precision, precision]) #conc_vec = np.linspace(0, max_uptake, precision) methane_vec = np.linspace(0,met_max_uptake,precision) oxygen_vec = np.linspace(0,ox_max_uptake,precision) for count_met, met in enumerate(methane_vec): for count_ox, oxygen in enumerate(oxygen_vec): pheast.reactions.uptake_methane.bounds = met, met pheast.reactions.r1160.bounds = oxygen, oxygen pheast.objective = pheast.problem.Objective(pheast.reactions.r1339.flux_expression) pheast.reactions.r1339.bounds = pheast.optimize().objective_value, pheast.optimize().objective_value pheast.objective = pheast.problem.Objective(pheast.reactions.hemo_Biosynthesis.flux_expression) plot[count_met, count_ox] = pheast.optimize().objective_value
GSM_model/GSM_model_glyco.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.1.0 # language: julia # name: julia-1.1 # --- # # Fitzhugh-Nagumo Bayesian Parameter Estimation Benchmarks # ### <NAME>, <NAME> using DiffEqBayes, BenchmarkTools using OrdinaryDiffEq, RecursiveArrayTools, Distributions, ParameterizedFunctions, Mamba using Plots gr(fmt=:png) # ### Defining the problem. # # The [FitzHugh-Nagumo model](https://en.wikipedia.org/wiki/FitzHugh%E2%80%93Nagumo_model) is a simplified version of [Hodgkin-Huxley model](https://en.wikipedia.org/wiki/Hodgkin%E2%80%93Huxley_model) and is used to describe an excitable system (e.g. neuron). fitz = @ode_def FitzhughNagumo begin dv = v - v^3/3 -w + l dw = ฯ„inv*(v + a - b*w) end a b ฯ„inv l prob_ode_fitzhughnagumo = ODEProblem(fitz,[1.0,1.0],(0.0,10.0),[0.7,0.8,1/12.5,0.5]) sol = solve(prob_ode_fitzhughnagumo, Tsit5()) # Data is genereated by adding noise to the solution obtained above. t = collect(range(1,stop=10,length=10)) sig = 0.20 data = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)])) # ### Plot of the data and the solution. scatter(t, data[1,:]) scatter!(t, data[2,:]) plot!(sol) # ### Priors for the parameters which will be passed for the Bayesian Inference priors = [Truncated(Normal(1.0,0.5),0,1.5),Truncated(Normal(1.0,0.5),0,1.5),Truncated(Normal(0.0,0.5),-0.5,0.5),Truncated(Normal(0.5,0.5),0,1)] # ## Parameter Estimation with Stan.jl backend @time bayesian_result_stan = stan_inference(prob_ode_fitzhughnagumo,t,data,priors;reltol=1e-5,abstol=1e-5,vars =(StanODEData(),InverseGamma(3,2))) plot_chain(bayesian_result_stan) # ## Turing.jl backend @time bayesian_result_turing = turing_inference(prob_ode_fitzhughnagumo,Tsit5(),t,data,priors) plot_chain(bayesian_result_turing) # # Conclusion # # In the FitzHugh-Nagumo model the parameters to be estimated were `[0.7,0.8,0.08,0.5]`. We use default number of samples and warmup to get a better estimate of the default performance of the samplers. # # Individually, Stan.jl backend takes 1.7 minutes for warmup and 1.6 seconds for sampling, giving `[0.98,0.83,0.079,0.56]`. Higher accuracy can be obtained with tighter priors, increase in warmup samples and adjusting the tolerance values. # # Turing.jl took just over 0.58 seconds and gave `[0.88,0.88,0.017,0.49]` as the result. The the trace plots indicate some non-convergance, this can be handled by increasing the sampling size for longer iterations. # # Overall we observe some non-convergance in both the backends and to avoid it longer iterations would be required at the cost of effiency the choice of which depends on the user. using DiffEqBenchmarks DiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
notebook/ParameterEstimation/DiffEqBayesFitzHughNagumo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Environment (conda_tensorflow_p36) # language: python # name: conda_tensorflow_p36 # --- # + import keras from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, BatchNormalization, LocallyConnected2D, Permute from keras.layers import Concatenate, Reshape, Softmax, Conv2DTranspose, Embedding, Multiply from keras.callbacks import ModelCheckpoint, EarlyStopping, Callback from keras import regularizers from keras import backend as K import keras.losses import tensorflow as tf from tensorflow.python.framework import ops import isolearn.keras as iso import numpy as np import tensorflow as tf import logging logging.getLogger('tensorflow').setLevel(logging.ERROR) import pandas as pd import os import pickle import numpy as np import scipy.sparse as sp import scipy.io as spio import matplotlib.pyplot as plt import isolearn.io as isoio import isolearn.keras as isol from genesis.visualization import * from genesis.generator import * from genesis.predictor import * from genesis.optimizer import * from definitions.generator.aparent_deconv_conv_generator_concat import load_generator_network, get_shallow_copy_function from definitions.predictor.aparent_w_dense_functional import load_saved_predictor import sklearn from sklearn.decomposition import PCA from sklearn.manifold import TSNE from scipy.stats import pearsonr import seaborn as sns from matplotlib import colors from scipy.optimize import basinhopping, OptimizeResult class IdentityEncoder(iso.SequenceEncoder) : def __init__(self, seq_len, channel_map) : super(IdentityEncoder, self).__init__('identity', (seq_len, len(channel_map))) self.seq_len = seq_len self.n_channels = len(channel_map) self.encode_map = channel_map self.decode_map = { nt: ix for ix, nt in self.encode_map.items() } def encode(self, seq) : encoding = np.zeros((self.seq_len, self.n_channels)) for i in range(len(seq)) : if seq[i] in self.encode_map : channel_ix = self.encode_map[seq[i]] encoding[i, channel_ix] = 1. return encoding def encode_inplace(self, seq, encoding) : for i in range(len(seq)) : if seq[i] in self.encode_map : channel_ix = self.encode_map[seq[i]] encoding[i, channel_ix] = 1. def encode_inplace_sparse(self, seq, encoding_mat, row_index) : raise NotImplementError() def decode(self, encoding) : seq = '' for pos in range(0, encoding.shape[0]) : argmax_nt = np.argmax(encoding[pos, :]) max_nt = np.max(encoding[pos, :]) seq += self.decode_map[argmax_nt] return seq def decode_sparse(self, encoding_mat, row_index) : raise NotImplementError() from keras.backend.tensorflow_backend import set_session def contain_tf_gpu_mem_usage() : config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) set_session(sess) contain_tf_gpu_mem_usage() # + #Specfiy file path to pre-trained predictor network save_dir = os.path.join(os.getcwd(), '../../../aparent/saved_models') saved_predictor_model_name = 'aparent_plasmid_iso_cut_distalpas_all_libs_no_sampleweights_sgd.h5' saved_predictor_model_path = os.path.join(save_dir, saved_predictor_model_name) saved_predictor = load_model(saved_predictor_model_path) acgt_encoder = IdentityEncoder(205, {'A':0, 'C':1, 'G':2, 'T':3}) # + def _store_sequence(run_dir, run_prefix, seq, curr_iter) : #Save sequence to file with open(run_dir + run_prefix + "_iter_" + str(int(curr_iter)) + ".txt", "a+") as f : f.write(seq + "\n") def get_step_func(predictor, sequence_template, acgt_encoder) : available_positions = [ j for j in range(len(sequence_template)) if sequence_template[j] == 'N' ] available_nt_dict = { 0 : [1, 2, 3], 1 : [0, 2, 3], 2 : [1, 0, 3], 3 : [1, 2, 0] } _predict_func = get_predict_func(predictor, len(sequence_template)) def _step_func(x, sequence_template=sequence_template, available_positions=available_positions, available_nt_dict=available_nt_dict) : onehot = np.expand_dims(np.expand_dims(x.reshape((len(sequence_template), 4)), axis=0), axis=-1) #Choose random position and nucleotide identity rand_pos = np.random.choice(available_positions) curr_nt = np.argmax(onehot[0, rand_pos, :, 0]) rand_nt = np.random.choice(available_nt_dict[curr_nt]) #Swap nucleotides onehot[0, rand_pos, :, 0] = 0. onehot[0, rand_pos, rand_nt, 0] = 1. new_x = np.ravel(onehot) return new_x return _step_func def get_predict_func(predictor, seq_len) : fake_lib = np.zeros((1, 13)) fake_lib[:, 5] = 1. fake_d = np.ones((1, 1)) def _predict_func(x, predictor=predictor, fake_lib=fake_lib, fake_d=fake_d, seq_len=seq_len) : onehot = np.expand_dims(np.expand_dims(x.reshape((seq_len, 4)), axis=0), axis=-1) iso_pred, _ = predictor.predict(x=[onehot, fake_lib, fake_d], batch_size=1) score_pred = np.log(iso_pred[0, 0] / (1. - iso_pred[0, 0])) return -score_pred return _predict_func def run_simulated_annealing(run_prefix, predictor, sequence_template, acgt_encoder, n_iters=1000, n_iters_per_temperate=100, temperature_init=1.0, temperature_func=None, verbose=False) : run_dir = "./samples/" + run_prefix + "/" run_prefix = "intermediate" if not os.path.exists(run_dir): os.makedirs(run_dir) if temperature_func is None : temperature_func = lambda t, curr_iter, t_init=temperature_init, total_iters=n_iters: t n_epochs = n_iters // n_iters_per_temperate predict_func = get_predict_func(predictor, len(sequence_template)) step_func = get_step_func(predictor, sequence_template, acgt_encoder) #Random initialization random_sequence = ''.join([ sequence_template[j] if sequence_template[j] != 'N' else np.random.choice(['A', 'C', 'G', 'T']) for j in range(len(sequence_template)) ]) x0 = np.ravel(acgt_encoder.encode(random_sequence)) x = x0 temperature = temperature_init seq_opt = "" tracked_scores = [predict_func(x)] for epoch_ix in range(n_epochs) : x_opt, f_opt = run_basinhopping(x, predict_func, step_func, n_iters=n_iters_per_temperate, temperature=temperature) onehot_opt = np.expand_dims(np.expand_dims(x_opt.reshape((len(sequence_template), 4)), axis=0), axis=-1) seq_opt = acgt_encoder.decode(onehot_opt[0, :, :, 0]) score_opt = -f_opt tracked_scores.append(score_opt) if verbose : print("Iter " + str((epoch_ix + 1) * n_iters_per_temperate) + ", Temp = " + str(round(temperature, 4)) + ", Score = " + str(round(score_opt, 4)) + "...") _store_sequence(run_dir, run_prefix, seq_opt, (epoch_ix + 1) * n_iters_per_temperate) x = x_opt temperature = temperature_func(temperature, (epoch_ix + 1) * n_iters_per_temperate) return seq_opt, np.array(tracked_scores) def run_basinhopping(x, predict_func, step_func, n_iters=1000, temperature=1.0) : def _dummy_min_opt(fun, x0, args=(), **options) : return OptimizeResult(fun=fun(x0), x=x0, nit=0, nfev=0, success=True) minimizer_kwargs = { 'method' : _dummy_min_opt, 'options' : { 'maxiter' : 0 } } opt_res = basinhopping(predict_func, x, minimizer_kwargs=minimizer_kwargs, stepsize=None, niter=n_iters, T=temperature, take_step=step_func) return opt_res.x, opt_res.fun # + #Run the basinhopping algorithm run_prefix = "basinhopping_apa_max_isoform_simple_1000_iters" sequence_template = 'TCCCTACACGACGCTCTTCCGATCTNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNAATAAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNAATAAATTGTTCGTTGGTCGGCTTGAGTGCGTGTGTCTCGTTTAGATGCTGCGCCTAACCCTAAGCAGATTCTTCATGCAATTG' n_sequences = 4096 n_iters = 1000 n_iters_per_temperate = 100 verbose = False t_init = 0.1 t_func = lambda t, curr_iter, t_init=t_init, total_iters=n_iters, t_min=0.05, exp_scale=1./0.7: t_init * t_min**(min(float(curr_iter / total_iters) * exp_scale, 1.0)) f = plt.figure(figsize=(6, 4)) it_space = [0] + [(epoch_ix + 1) * n_iters_per_temperate for epoch_ix in range(n_iters // n_iters_per_temperate)] temp = t_init temp_space = [temp] for j in range(1, len(it_space)) : it = it_space[j] temp = t_func(temp, it) temp_space.append(temp) plt.plot(it_space, temp_space, linewidth=2, color='black', linestyle='-') plt.xlabel("Iteration", fontsize=14) plt.ylabel("Temperature", fontsize=14) plt.title("Anneal schedule", fontsize=14) plt.xlim(0, np.max(it_space)) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.tight_layout() plt.show() optimized_seqs = [] optimized_trajs = [] for sequence_ix in range(n_sequences) : seq, scores = run_simulated_annealing(run_prefix, saved_predictor, sequence_template, acgt_encoder, n_iters=n_iters, n_iters_per_temperate=n_iters_per_temperate, temperature_init=t_init, temperature_func=t_func, verbose=verbose) if sequence_ix % 100 == 0 : print("Optimized sequence " + str(sequence_ix) + ". Score = " + str(round(scores[-1], 4))) optimized_seqs.append(seq) optimized_trajs.append(scores.reshape(1, -1)) optimized_trajs = np.concatenate(optimized_trajs, axis=0) print("Finished optimizing " + str(optimized_trajs.shape[0]) + " sequences.") plot_n_trajs = min(optimized_trajs.shape[0], 500) f = plt.figure(figsize=(6, 4)) it_space = [0] + [(epoch_ix + 1) * n_iters_per_temperate for epoch_ix in range(n_iters // n_iters_per_temperate)] for i in range(plot_n_trajs) : plt.plot(it_space, optimized_trajs[i, :], linewidth=2, linestyle='-') plt.xlabel("Iteration", fontsize=14) plt.ylabel("Fitness Score", fontsize=14) plt.title("Anneal sequence results", fontsize=14) plt.xlim(0, np.max(it_space)) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.tight_layout() plt.show() # + #Save sequences to file with open(run_prefix + "_4096_sequences.txt", "wt") as f: for i in range(len(optimized_seqs)) : f.write(optimized_seqs[i] + "\n") # -
analysis/apa/apa_max_isoform_basinhopping_simple.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 # --- # + slideshow={"slide_type": "skip"} import subframe subframe.plugins.enable() # + slideshow={"slide_type": "slide"} import pandas import numpy numpy.random.seed(1) data = pandas.DataFrame({ 'a': numpy.random.randint(1, 5, 1000), 'b': numpy.random.randint(1, 10, 1000), 'x': numpy.random.randn(1000), 'y': numpy.random.randn(1000) }) # + slideshow={"slide_type": "slide"} subframe.PivotTable( data, labels={'a': 'Foo', 'b': 'Bar'}, options={'rows': ['Foo'], 'cols': ['Bar'], 'rendererName': 'Area Chart'} ) # + slideshow={"slide_type": "slide"} subframe.DataTable(data, labels={'index': 'Index', 'a': 'Foo', 'b': 'Bar'}) # -
examples/Simple Example.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 # --- # # Bite Size Bayes # # Copyright 2020 <NAME> # # License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) import numpy as np import pandas as pd import matplotlib.pyplot as plt # ## Review # # In [a previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/12_binomial.ipynb) we solved the Euro problem, which involved estimating the proportion of heads we get when we spin a coin on edge. # # We used the posterior distribution to test whether the coin is fair or biased, but the answer is not entirely satisfying because it depends on how we define "biased". # # In general, this kind of hypothesis testing is not the best use of a posterior distribution because it does not answer the question we really care about. For practical purposes, it is less useful to know *whether* a coin is biased and more useful to know *how* biased. # # In this notebook we solve the Bayesian bandit problem, which is similar in the sense that it involves estimating proportions, but different in the sense that we use the posterior distribution as part of a decision-making process. # ## The Bayesian bandit problem # # Suppose you have several "one-armed bandit" slot machines, and there's reason to think that they have different probabilities of paying off. # # Each time you play a machine, you either win or lose, and you can use the outcome to update your belief about the probability of winning. # # Then, to decide which machine to play next, you can use the "Bayesian bandit" strategy, explained below. # # First, let's see how to do the update. # ## The prior # # If we know nothing about the probability of wining, we can start with a uniform prior. def decorate_bandit(title): """Labels the axes. title: string """ plt.xlabel('Probability of winning') plt.ylabel('PMF') plt.title(title) xs = np.linspace(0, 1, 101) prior = pd.Series(1/101, index=xs) prior.plot() decorate_bandit('Prior distribution') # ## The likelihood function # # The likelihood function that computes the probability of an outcome (W or L) for a hypothetical value of x, the probability of winning (from 0 to 1). def update(prior, data): """Likelihood function for Bayesian bandit prior: Series that maps hypotheses to probabilities data: string, either 'W' or 'L' """ xs = prior.index if data == 'W': prior *= xs else: prior *= 1-xs prior /= prior.sum() bandit = prior.copy() update(bandit, 'W') update(bandit, 'L') bandit.plot() decorate_bandit('Posterior distribution, 1 loss, 1 win') # **Exercise 1:** Suppose you play a machine 10 times and win once. What is the posterior distribution of $x$? # + # Solution bandit = prior.copy() for outcome in 'WLLLLLLLLL': update(bandit, outcome) bandit.plot() decorate_bandit('Posterior distribution, 9 loss, one win') # - # ## Multiple bandits # Now suppose we have several bandits and we want to decide which one to play. # # For this example, we have 4 machines with these probabilities: actual_probs = [0.10, 0.20, 0.30, 0.40] # The function `play` simulates playing one machine once and returns `W` or `L`. # + from random import random from collections import Counter # count how many times we've played each machine counter = Counter() def flip(p): """Return True with probability p.""" return random() < p def play(i): """Play machine i. returns: string 'W' or 'L' """ counter[i] += 1 p = actual_probs[i] if flip(p): return 'W' else: return 'L' # - # Here's a test, playing machine 3 twenty times: for i in range(20): result = play(3) print(result, end=' ') # Now I'll make four copies of the prior to represent our beliefs about the four machines. beliefs = [prior.copy() for i in range(4)] # This function displays four distributions in a grid. # + options = dict(xticklabels='invisible', yticklabels='invisible') def plot(beliefs, **options): for i, b in enumerate(beliefs): plt.subplot(2, 2, i+1) b.plot(label='Machine %s' % i) plt.gca().set_yticklabels([]) plt.legend() plt.tight_layout() # - plot(beliefs) # **Exercise 2:** Write a nested loop that plays each machine 10 times; then plot the posterior distributions. # # Hint: call `play` and then `update`. # + # Solution for i in range(4): for _ in range(10): outcome = play(i) update(beliefs[i], outcome) # + # Solution plot(beliefs) # - # After playing each machine 10 times, we can summarize `beliefs` by printing the posterior mean and credible interval: def pmf_mean(pmf): """Compute the mean of a PMF. pmf: Series representing a PMF return: float """ return np.sum(pmf.index * pmf) # + from scipy.interpolate import interp1d def credible_interval(pmf, prob): """Compute the mean of a PMF. pmf: Series representing a PMF prob: probability of the interval return: pair of float """ # make the CDF xs = pmf.index ys = pmf.cumsum() # compute the probabilities p = (1-prob)/2 ps = [p, 1-p] # interpolate the inverse CDF options = dict(bounds_error=False, fill_value=(xs[0], xs[-1]), assume_sorted=True) interp = interp1d(ys, xs, **options) return interp(ps) # - for i, b in enumerate(beliefs): print(pmf_mean(b), credible_interval(b, 0.9)) # ## Bayesian Bandits # # To get more information, we could play each machine 100 times, but while we are gathering data, we are not making good use of it. The kernel of the Bayesian Bandits algorithm is that it collects and uses data at the same time. In other words, it balances exploration and exploitation. # # The following function chooses among the machines so that the probability of choosing each machine is proportional to its "probability of superiority". def pmf_choice(pmf, n): """Draw a random sample from a PMF. pmf: Series representing a PMF returns: quantity from PMF """ return np.random.choice(pmf.index, p=pmf) def choose(beliefs): """Use the Bayesian bandit strategy to choose a machine. Draws a sample from each distributions. returns: index of the machine that yielded the highest value """ ps = [pmf_choice(b, 1) for b in beliefs] return np.argmax(ps) # This function chooses one value from the posterior distribution of each machine and then uses `argmax` to find the index of the machine that chose the highest value. # # Here's an example. choose(beliefs) # **Exercise 3:** Putting it all together, fill in the following function to choose a machine, play once, and update `beliefs`: def choose_play_update(beliefs, verbose=False): """Chose a machine, play it, and update beliefs. beliefs: list of Pmf objects verbose: Boolean, whether to print results """ # choose a machine machine = ____ # play it outcome = ____ # update beliefs update(____) if verbose: print(i, outcome, beliefs[machine].mean()) # + # Solution def choose_play_update(beliefs, verbose=False): """Chose a machine, play it, and update beliefs. beliefs: list of Pmf objects verbose: Boolean, whether to print results """ # choose a machine machine = choose(beliefs) # play it outcome = play(machine) # update beliefs update(beliefs[machine], outcome) if verbose: print(i, outcome, beliefs[machine].mean()) # - # Here's an example choose_play_update(beliefs, verbose=True) # ## Trying it out # Let's start again with a fresh set of machines and an empty `Counter`. beliefs = [prior.copy() for i in range(4)] counter = Counter() # If we run the bandit algorithm 100 times, we can see how `beliefs` gets updated: # + num_plays = 100 for i in range(num_plays): choose_play_update(beliefs) plot(beliefs) # - # We can summarize `beliefs` by printing the posterior mean and credible interval: for i, b in enumerate(beliefs): print(pmf_mean(b), credible_interval(b, 0.9)) # The credible intervals usually contain the true values (0.1, 0.2, 0.3, and 0.4). # # The estimates are still rough, especially for the lower-probability machines. But that's a feature, not a bug: the goal is to play the high-probability machines most often. Making the estimates more precise is a means to that end, but not an end itself. # # Let's see how many times each machine got played. If things go according to plan, the machines with higher probabilities should get played more often. for machine, count in sorted(counter.items()): print(machine, count) # **Exercise 4:** Go back and run this section again with a different value of `num_play` and see how it does. # ## Summary # # The algorithm I presented in this notebook is called [Thompson sampling](https://en.wikipedia.org/wiki/Thompson_sampling). It is an example of a general strategy called [Bayesian decision theory](https://wiki.lesswrong.com/wiki/Bayesian_decision_theory), which is the idea of using a posterior distribution as part of a decision-making process, usually by choosing an action that minimizes the costs we expect on average (or maximizes a benefit). # # In my opinion, this strategy is the biggest advantage of Bayesian methods over classical statistics. When we represent knowledge in the form of probability distributions, Bayes's theorem tells us how to change our beliefs as we get more data, and Bayesian decisions theory tells us how to make that knowledge actionable.
_build/jupyter_execute/bandit_soln.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 # --- # # ํ†ต๊ณ„ ๊ธฐ์ดˆ ๋ฐ‘๋ฐ”๋‹ฅ๋ถ€ํ„ฐ # __์ฐธ๊ณ :__ ์—ฌ๊ธฐ์„œ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ๋Š” ์กฐ์—˜ ๊ทธ๋ฃจ์Šค(<NAME>)์˜ # [๋ฐ‘๋‹ค๋‹ฅ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋Š” ๋ฐ์ดํ„ฐ ๊ณผํ•™](https://github.com/joelgrus/data-science-from-scratch) # 5์žฅ์— ์‚ฌ์šฉ๋œ ์†Œ์Šค์ฝ”๋“œ์˜ ์ผ๋ถ€๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ž‘์„ฑ๋˜์—ˆ๋‹ค. # ## ์ฃผ์š” ๋‚ด์šฉ # ๋ฐ์ดํ„ฐ ๋ถ„์„์˜ ๊ธฐ๋ณธ์ด ๋ฐ”๋กœ ํ†ต๊ณ„ ๋ถ„์•ผ์˜ ์ฃผ์š” ๊ฐœ๋…๊ณผ ๊ธฐ๋ฒ•์ด๋‹ค. # ์—ฌ๊ธฐ์„œ๋Š” ์•ž์œผ๋กœ ์šฐ๋ฆฌ์—๊ฒŒ ํ•„์š”ํ•œ ์ •๋„์˜ ํ†ต๊ณ„์˜ ๊ธฐ๋ณธ ๊ฐœ๋…๊ณผ ๊ธฐ๋ฒ•์„ ๊ฐ„๋‹จํ•˜๊ฒŒ ์†Œ๊ฐœํ•œ๋‹ค. # # ๋‹ค๋ฃจ๋Š” ์ฃผ์ œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # # 1. ์ค‘์‹ฌ๊ฒฝํ–ฅ์„ฑ # 1. ์‚ฐํฌ๋„ # 1. ์ƒ๊ด€๊ด€๊ณ„ # 1. ์‹ฌ์Šจ์˜ ์—ญ์„ค # 1. ์ƒ๊ด€๊ด€๊ณ„์™€ ์ธ๊ณผ๊ด€๊ณ„ # ## ๋ฐ์ดํ„ฐ์…‹ ์„ค๋ช…ํ•˜๊ธฐ # ์ด 204๋ช…์˜ ์‚ฌ์šฉ์ž ๊ฐ๊ฐ์˜ ์นœ๊ตฌ์ˆ˜์— ๋ฐ์ดํ„ฐ๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฃผ์–ด์กŒ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. # ์ฆ‰, ์‚ฌ์šฉ์ž๋ณ„ ์ตœ๋Œ€ ์นœ๊ตฌ์ˆ˜๋Š” 100๋ช…์ด๊ณ , ์ตœ์†Œ 1๋ช…์ด๋‹ค. num_friends = [100.0,49,41,40,25,21,21,19,19,18,18,16,15, 15,15,15,14,14,13,13,13,13,12,12,11,10,10, 10,10,10,10,10,10,10,10,10,10,10,10,10,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8, 8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] # ์‚ฌ์šฉ์ž ์ˆ˜๋Š” 204๋ช…์ด๊ณ , ์‚ฌ์šฉ์ž๋ณ„ ์ตœ๋Œ€ ์นœ๊ตฌ์ˆ˜๋Š” 100๋ช…, ์ตœ์†Œ ์นœ๊ตฌ์ˆ˜๋Š” 1๋ช…์ด๋‹ค. print(f"์‚ฌ์šฉ์ž ์ˆ˜:\t{len(num_friends)}", f"์ตœ๋Œ€ ์นœ๊ตฌ ์ˆ˜:\t{max(num_friends)}", f"์ตœ์†Œ ์นœ๊ตฌ ์ˆ˜:\t{min(num_friends)}", sep='\n') from collections import Counter import matplotlib.pyplot as plt friend_counts = Counter(num_friends) xs = range(101) # largest value is 100 ys = [friend_counts[x] for x in xs] # height is just # of friends plt.bar(xs, ys) plt.axis([0, 101, 0, 25]) plt.title("Histogram of Friend Counts") plt.xlabel("# of friends") plt.ylabel("# of people") plt.show() # ์œ„ ํžˆ์Šคํ† ๊ทธ๋žจ์—์„œ ๋ณด์—ฌ์ง€๋Š” ๊ฒƒ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # # * ๋งŽ์€ ์‚ฌ๋žŒ๋“ค์ด 10๋ช… ์ด๋‚ด์˜ ์นœ๊ตฌ๋ฅผ ๊ฐ–๋Š”๋‹ค. # * 100๋ช…์˜ ์นœ๊ตฌ๋ฅผ ๊ฐ€์ง„ ์‚ฌ์šฉ์ž๋„ ์žˆ๋‹ค. # # ๋‹ค๋ฅธ ์ •๋ณด๋ฅผ ์–ด๋–ป๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ์„๊นŒ? # # ์˜ˆ๋ฅผ ๋“ค์–ด, ๋Œ€๋‹ค์ˆ˜ ์‚ฌ๋žŒ๋“ค์˜ ์นœ๊ตฌ ์ˆ˜๋Š” ์–ด๋”˜๊ฐ€๋กœ ์ ๋ฆฌ๋Š” ๊ฒฝํ–ฅ์ด ์žˆ์–ด ๋ณด์ธ๋‹ค. # ์ด๊ฒƒ์„ ์ „๋ฌธ์šฉ์–ด๋กœ ํ‘œํ˜„ํ•˜๋ฉด **์ค‘์‹ฌ ๊ฒฝํ–ฅ์„ฑ**์ด๋‹ค. # ์ฆ‰, ์ผ๋ฐ˜์ ์œผ๋กœ ์‚ฌ์šฉ์ž๋“ค์˜ ์นœ๊ตฌ ์ˆ˜๋ฅผ ๋Œ€ํ‘œํ•˜๋Š” ์ค‘์‹ฌ์ด ์กด์žฌํ•œ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค. friend_counts # ## ์ค‘์‹ฌ ๊ฒฝํ–ฅ์„ฑ # # ์ค‘์‹ฌ ๊ฒฝํ–ฅ์„ฑ์€ ๋ฐ์ดํ„ฐ์˜ ์ค‘์‹ฌ์˜ ์œ„์น˜๋ฅผ ์•Œ๋ ค์ฃผ๋ฉฐ, ์ค‘์‹ฌ ๊ฒฝํ–ฅ์„ฑ์„ ์ง€์ •ํ•˜๊ธฐ ์œ„ํ•ด ๋ณดํ†ต ์„ธ ์ข…๋ฅ˜์˜ ํ‰๊ท (average)์„ ์‚ฌ์šฉํ•œ๋‹ค. # # 1. ํ‰๊ท ๊ฐ’(mean) # 1. ์ค‘์•™๊ฐ’(median) # 1. ์ตœ๋นˆ๊ฐ’(mode) # # **์ฃผ์˜:** ํ‰๊ท (average)๊ณผ ํ‰๊ท ๊ฐ’(mean)๋ฅผ ํ˜ผ๋™ํ•˜์ง€ ๋ง์•„์•ผ ํ•œ๋‹ค. # ### ์ „์ œ # $X$๋ฅผ ๋ฐ์ดํ„ฐ์…‹์ด๋ผ ํ•˜๊ณ , $X$์˜ ํฌ๊ธฐ, ์ฆ‰, ํ…Œ์ดํ„ฐ ๊ฐœ์ˆ˜๋ฅผ $n$์ด๋ผ ํ•˜์ž. # ### ํ‰๊ท ๊ฐ’ # # ํ‰๊ท ๊ฐ’(mean)์€ ์šฐ๋ฆฌ๊ฐ€ ๋ณดํ†ต ํ‰๊ท ์ด๋ผ ๋ถ€๋ฅด๋Š” ๊ฐ’์ด๋ฉฐ ๋ชจ๋“  ๋ฐ์ดํ„ฐ์˜ ํ•ฉ์„ ๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜๋กœ ๋‚˜๋ˆˆ๋‹ค. # ๊ทธ๋Ÿฌ๋ฉด, ๋ฐ์ดํ„ฐ์…‹ $X$์˜ ํ‰๊ท ๊ฐ’์€ ๋ณดํ†ต ๊ทธ๋ฆฌ์Šค ์•ŒํŒŒ๋ฒณ ๋ฎค($\mu$) ๋˜๋Š” $E(X)$๋กœ ํ‘œ์‹œํ•˜๋ฉฐ ๊ฐ’์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค. # # $$ # E(X) = \mu = \frac{\sum X}{n} # $$ # $X=$ `num_friends` ์ผ ๋•Œ ์‚ฌ์šฉ์ž๋“ค์˜ ํ‰๊ท  ์นœ๊ตฌ์ˆ˜๋Š” 7.33๋ช…์ด๋‹ค. # + from typing import List def mean(xs: List[float]) -> float: return sum(xs) / len(xs) mean(num_friends) # - # ### ์ค‘์•™๊ฐ’ # # ์ค‘์•™๊ฐ’(median) ๋ง ๊ทธ๋Œ€๋กœ, ๋ฐ์ดํ„ฐ์˜ ์ค‘์•™์œ„์น˜์— ์ž๋ฆฌ์žก์€ ๊ฐ’์ด๋‹ค. # ๋‹จ, ๋ฐ์ดํ„ฐ๋ฅผ ํฌ๊ธฐ์ˆœ์œผ๋กœ ์ •๋ ฌํ–ˆ์„ ๋•Œ ์ค‘์•™์œ„์น˜์— ์žˆ๋Š” ๊ฐ’์ด๋‹ค. # ๋”ฐ๋ผ์„œ ์ค‘์•™๊ฐ’์„ ๊ตฌํ•˜๋ ค๋ฉด ๋จผ์ € ๋ฐ์ดํ„ฐ๋ฅผ ํฌ๊ธฐ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์•ผ ํ•œ๋‹ค. # ๊ทธ ๋‹ค์Œ์— ์ค‘์•™์œ„์น˜๋ฅผ ์ฐพ์•„๋‚ด์–ด ๊ทธ๊ณณ์— ์œ„์น˜ํ•œ ๊ฐ’์„ ํ™•์ธํ•œ๋‹ค. # # ๊ทธ๋Ÿฐ๋ฐ $n$์ด ์ง์ˆ˜์ด๋ฉด ์ค‘์•™์œ„์น˜์— ๋‘ ์ˆ˜ ์‚ฌ์ด์— ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‘ ์ˆ˜์˜ ํ‰๊ท ๊ฐ’์„ ์ค‘์•™๊ฐ’์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค. # <img src="https://raw.githubusercontent.com/codingalzi/pydata/master/notebooks/images/median.png" width="30%"> # # ์ถœ์ฒ˜: [์œ„ํ‚ค๋ฐฑ๊ณผ](https://en.wikipedia.org/wiki/Median) # ์นœ๊ตฌ์ˆ˜์˜ ์ค‘์•™๊ฐ’์€ 6๋ช…์ด๋‹ค. # + def _median_odd(xs: List[float]) -> float: """๊ธธ์ด๊ฐ€ ํ™€์ˆ˜์ผ ๋•Œ""" return sorted(xs)[len(xs) // 2] def _median_even(xs: List[float]) -> float: """๊ธธ์ด๊ฐ€ ์ง์ˆ˜์ผ ๋•Œ""" sorted_xs = sorted(xs) hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2 return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2 def median(v: List[float]) -> float: """์ค‘์•™๊ฐ’ ์ฐพ๊ธฐ""" return _median_even(v) if len(v) % 2 == 0 else _median_odd(v) median(num_friends) # - # #### ํ‰๊ท ๊ฐ’๊ณผ ์ค‘์•™๊ฐ’์˜ ์ฐจ์ด # # ํ‰๊ท ๊ฐ’์€ ๋ฐ์ดํ„ฐ์— ๋ฏผ๊ฐํ•œ ๋ฐ˜๋ฉด์— ์ค‘์•™๊ฐ’์€ ๊ทธ๋ ‡์ง€ ์•Š๋‹ค. # ์˜ˆ๋ฅผ ๋“ค์–ด, `num_friends`์—์„œ ์ตœ๋Œ€ ์นœ๊ตฌ์ˆ˜๋ฅผ 100๋ช…์—์„œ 200๋ช…์œผ๋กœ ๋ฐ”๊พธ๋ฉด # ๊ทธ๋Ÿฌ๋ฉด ํ‰๊ท ๊ฐ’์€ 7.33๋ช…์—์„œ 7.82๋ช…์œผ๋กœ ์˜ฌ๋ผ๊ฐ„๋‹ค. Y = num_friends.copy() Y[0]=200 mean(Y) # ํ•˜์ง€๋งŒ ์ค‘์•™๊ฐ’์€ ๋ณ€ํ•˜์ง€ ์•Š๋Š”๋‹ค. median(Y) # #### ์ด์ƒ์น˜ # # ์•ž์„œ ์‚ดํŽด๋ณด์•˜๋“ฏ ํ‰๊ท ๊ฐ’์€ ํŠน์ • ๊ฐ’์— ๋ฏผ๊ฐํ•˜๊ฒŒ ๋ฐ˜์‘ํ•œ๋‹ค. # `num_friends`์˜ ๊ฒฝ์šฐ ์นœ๊ตฌ์ˆ˜๊ฐ€ ํ‰๊ทœ 7.33๋ช…์ธ๋ฐ 100๋ช…์˜ ์นœ๊ตฌ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ๋Š” ๋งค์šฐ ํŠน์ดํ•˜๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค. # ์ด๋Ÿฐ ๋ฐ์ดํ„ฐ๋ฅผ **์ด์ƒ์น˜**(outlier)๋ผ ๋ถ€๋ฅธ๋‹ค. # ๋”ฐ๋ผ์„œ ์ด์ƒ์น˜๊ฐ€ ์กด์žฌํ•˜๋ฉด ํ‰๊ท ๊ฐ’์ด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์ž˜๋ชป๋œ ์ •๋ณด๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋‹ค. # # ์˜ˆ๋ฅผ ๋“ค์–ด, 2013๋…„ 3์›” ๋‹น์‹œ, ๊ตญํšŒ์˜์›๋“ค์˜ ํ‰๊ท ์žฌ์‚ฐ์€ 94์–ต 9000๋งŒ์›์ด์—ˆ๋‹ค. # ํ•˜์ง€๋งŒ ์ด์ƒ์น˜๊ฐ’์„ ๋ณด์ธ ๋‘ ์˜์›์„ ์ œ์™ธํ•˜๋ฉด 23์–ต 3000๋งŒ์›์ด๋‹ค. # ๋‘ ๊ฐœ์˜ ์ด์ƒ์น˜๋Š” ํ˜„๋Œ€์ค‘๊ณต์—…์˜ ๋Œ€์ฃผ์ฃผ์ธ ์ •๋ชฝ์ค€์˜ ์•ฝ 2์กฐ์› ๊ฐ€๋Ÿ‰์˜ ์žฌ์‚ฐ๊ณผ ๋‹ค๋ฅธ ํ•œ ๋ช…์˜ ์•ฝ 2000์–ต์› ๊ฐ€๋Ÿ‰์˜ ์žฌ์‚ฐ์ด์—ˆ๋‹ค. # #### ์‚ฌ๋ถ„์œ„์ˆ˜ # # ์ค‘์•™๊ฐ’์€ ์ค‘์•™์œ„์น˜์— ์žˆ๋Š” ๊ฐ’์ด๋ฉฐ, ์„ธ ๊ฐœ์˜ ์‚ฌ๋ถ„์œ„์ˆ˜(quantile) ์ค‘์— ํ•˜๋‚˜์ด๋‹ค. # ๋‹ค๋ฃฌ ๋‘ ๊ฐœ์˜ ์‚ฌ๋ถ„์œ„์ˆ˜๋Š” ํ•˜์œ„ 25% ์œ„์น˜์— ์žˆ๋Š” ์ œ1์‚ฌ๋ถ„์œ„์ˆ˜์™€ # ์ƒ์œ„ 25% ์œ„์น˜์— ์žˆ๋Š” ์ œ3์‚ฌ๋ถ„์œ„์ˆ˜์ด๋‹ค. # ์ฆ‰, ์ค‘์•™๊ฐ’์€ ์ƒ์œ„ 50%์— ํ•ด๋‹นํ•˜๋Š” ์ œ2์‚ฌ๋ถ„์œ„์ˆ˜์— ํ•ด๋‹นํ•œ๋‹ค. # <img src="https://raw.githubusercontent.com/codingalzi/pydata/master/notebooks/images/quantile.png" width="60%"> # `num_friends`์˜ ์ œ1์‚ฌ๋ถ„์œ„์ˆ˜์™€ ์ œ3์‚ฌ๋ถ„์œ„์ˆ˜๋Š” ๊ฐ๊ฐ 3๋ช…๊ณผ 9๋ช…์ด๋‹ค. # + def quantile(xs: List[float], p: float) -> float: """p% ์œ„์น˜๊ฐ’ ์ฐจ๊ธฐ""" p_index = int(p * len(xs)) return sorted(xs)[p_index] print("์ œ1์‚ฌ๋ถ„์œ„์ˆ˜:", quantile(num_friends, 0.25)) print("์ œ3์‚ฌ๋ถ„์œ„์ˆ˜:", quantile(num_friends, 0.75)) # - # ### ์ตœ๋นˆ๊ฐ’ # # ๋ฐ์ดํ„ฐ์—์„œ ๊ฐ€์žฅ ์ž์ฃผ ๋‚˜์˜ค๋Š” ๊ฐ’์„ ์ตœ๋นˆ๊ฐ’(mode)๋ผ ๋ถ€๋ฅด๋ฉฐ, # ๊ฒฝ์šฐ์— ๋”ฐ๋ผ ํ‰๊ท ๊ฐ’, ์ค‘์•™๊ฐ’ ๋Œ€์‹ ์— ์ค‘์‹ฌ์„ ๋Œ€ํ‘œํ•˜๋Š” ๊ฐ’์œผ๋กœ ์‚ฌ์šฉ๋œ๋‹ค. # # `num_friends`์˜ ์ตœ๋นˆ๊ฐ’์€ 1๊ณผ 6์ด๋‹ค. # + def mode(x: List[float]) -> List[float]: """์ตœ๋นˆ๊ฐ’""" counts = Counter(x) max_count = max(counts.values()) return [x_i for x_i, count in counts.items() if count == max_count] set(mode(num_friends)) # - counts = Counter(num_friends) counts max_count = max(counts.values()) max_count [x_i for x_i, count in counts.items() if count == max_count] # ## ์‚ฐํฌ๋„ # ์‚ฐํฌ๋„๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์–ผ๋งˆ๋‚˜ ํผ์ ธ ์žˆ๋Š”์ง€๋ฅผ ์ธก์ •ํ•œ๋‹ค. # ์‚ฐํฌ๋„๊ฐ€ 0์— ๊ฐ€๊นŒ์šด ๊ฐ’์ด๋ฉด ํผ์ ธ์žˆ์ง€ ์•Š๊ณ  ํ•œ ๊ฐ’ ์ฃผ์œ„์— ๋ญ‰์ณ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ด๊ณ , # 0์—์„œ ๋ฉ€์–ด์งˆ ์ˆ˜๋ก ํผ์ ธ์žˆ๋Š” ์ •๋„๊ฐ€ ์ปค์ง„๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค. # # ์‚ฐํฌ๋„๋ฅผ ์ธก์ •ํ•˜๋Š” ๊ธฐ์ค€์€ ๋ณดํ†ต ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # # 1. ๋ฒ”์œ„(range) # 1. ์‚ฌ๋ถ„๋ฒ”์œ„(interquntile range) # 1. ๋ถ„์‚ฐ(variance) # 1. ํ‘œ์ค€ํŽธ์ฐจ(standard deviation) # ### ๋ฒ”์œ„ # # ๋ฒ”์œ„๋Š” ๋ฐ์ดํ„ฐ์…‹์˜ ์ตœ๋Œ€๊ฐ’๊ณผ ์ตœ์†Œ๊ฐ’์˜ ์ฐจ์ด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. # ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฒ”์œ„๊ฐ€ ํฌ๋‹ค๋Š” ๊ฒƒ์€ ๋ฐ์ดํ„ฐ์˜ ํผ์ง ์ •๋„๊ฐ€ ํฌ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. # # ๊ทธ๋Ÿฐ๋ฐ ๋ฒ”์œ„๋Š” ์ตœ๋Œ€, ์ตœ์†Œ๊ฐ’์—๋งŒ ์˜์กดํ•œ๋‹ค. # ์˜ˆ๋ฅผ ๋“ค์–ด, ์ตœ๋Œ€๊ฐ’ 100, ์ตœ์†Œ๊ฐ’ 1์ธ ๋ฐ์ดํ„ฐ๋Š” ๋ชจ๋‘ `num_friends`์™€ ๋™์ผํ•œ ๋ฒ”์œ„๋ฅผ ๊ฐ–๋Š”๋‹ค. # ๋”ฐ๋ผ์„œ ๋ฐ์ดํ„ฐ์˜ ํŠน์„ฑ์„ ์ œ๋Œ€๋กœ ๋ฐ˜์˜ํ•˜์ง€ ๋ชปํ•  ์ˆ˜๊ฐ€ ์žˆ๋‹ค. # <img src="https://raw.githubusercontent.com/codingalzi/pydata/master/notebooks/images/num_friends.png" width="60%"> # `num_friends`์˜ ๋ฒ”์œ„๋Š” 99์ž„์„ ๋‹ค์‹œ ํ•œ ๋ฒˆ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. # + def data_range(xs: List[float]) -> float: return max(xs) - min(xs) data_range(num_friends) # - # ### ์‚ฌ๋ถ„๋ฒ”์œ„ # # ํ‰๊ท , ๋ถ„์‚ฐ, ํ‘œ์ค€ํŽธ์ฐจ์™€ ํ•จ๊ป˜ ๋ฒ”์œ„๋„ ์ด์ƒ์น˜์— ๋ฏผ๊ฐํ•˜๋‹ค. # ์ด๋Ÿฐ ์ ์„ ํ•ด์†Œํ•˜๊ธฐ ์œ„ํ•ด ์ œ1์‚ฌ๋ถ„์œ„์ˆ˜์™€ ์ œ3์‚ฌ๋ถ„์œ„์ˆ˜ ์‚ฌ์ด์˜ ๋ฒ”์œ„์ธ ์‚ฌ๋ถ„๋ฒ”์œ„๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ๋„ ํ•œ๋‹ค. # # ์˜ˆ๋ฅผ ๋“ค์–ด, `num_friends`์˜ ์‚ฌ๋ถ„๋ฒ”์œ„๋Š” 6์ด๋‹ค. # ๋ฒ”์œ„๊ฐ€ 99์˜€๋˜ ๊ฒƒ์— ๋น„ํ•ด ๋งค์šฐ ์ž‘์€ ์‚ฐํฌ๋„๋ฅผ ์˜๋ฏธํ•œ๋‹ค. # + def interquartile_range(xs: List[float]) -> float: """์ œ3์‚ฌ๋ถ„์œ„์ˆ˜ - ์ œ1์‚ฌ๋ถ„์œ„์ˆ˜""" return quantile(xs, 0.75) - quantile(xs, 0.25) interquartile_range(num_friends) # - # ### ๋ถ„์‚ฐ # # ๋ฐ์ดํ„ฐ ํ‰๊ท ๊ฐ’๊ณผ์˜ ์ฐจ์ด์˜ ์ œ๊ณฑ๋“ค์˜ ํ‰๊ท ๊ฐ’์ด ๋ถ„์‚ฐ์ด๋‹ค. # ์‰ฝ๊ฒŒ ๋งํ•˜๋ฉด, ๋ฐ์ดํ„ฐ๊ฐ€ ํ‰๊ท ๊ฐ’์œผ๋กœ๋ถ€ํ„ฐ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์ ธ ์žˆ๋Š”๊ฐ€๋ฅผ ์•Œ๋ ค์ฃผ๋Š” ๊ฐ’์ด๋ฉฐ, # ์ •ํ™•ํ•œ ๊ณ„์‚ฐ์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, # ๋ฐ์ดํ„ฐ์…‹ $X$์˜ ๋ถ„์‚ฐ์€ ๋ณดํ†ต $\textit{Var}(X)$ ๊ธฐํ˜ธ๋กœ ๋‚˜ํƒ€๋‚ธ๋‹ค. # $$ # \textit{Var}(X) = \frac{\sum (X - \mu)^2}{n-1} # $$ # **์ฃผ์˜:** ์ผ๋ฐ˜์ ์œผ๋กœ ๋ถ„๋ชจ๋ฅผ $n$์œผ๋กœ ํ•œ๋‹ค. # ํ•˜์ง€๋งŒ ๋ฐ์ดํ„ฐ ํ‘œ๋ณธ์œผ๋กœ๋ถ€ํ„ฐ ์ „์ฒด์— ๋Œ€ํ•œ ๋ถ„์‚ฐ์„ ์ถ”์ •ํ•˜๋Š” ๊ฒฝ์šฐ $(n-1)$์„ ์‚ฌ์šฉํ•œ๋‹ค. # ์‹ค์ œ๋กœ ๋ฐ์ดํ„ฐ๋ถ„์„์— ๋‹ค๋ฃจ๋Š” ๋ฐ์ดํ„ฐ๋Š” ๊ฑฐ์˜ ํ‘œ๋ณธ ๋ฐ์ดํ„ฐ์ด๋‹ค. # `num_friends` ๋ฐ์ดํ„ฐ์˜ ๋ถ„์‚ฐ๊ฐ’์€ 81.54์ด๋‹ค. # + def dot(v: List[float], w: List[float]) -> float: """Computes v_1 * w_1 + ... + v_n * w_n""" assert len(v) == len(w), "List[float]s must be same length" return sum(v_i * w_i for v_i, w_i in zip(v, w)) def sum_of_squares(v: List[float]) -> float: """๋ฐ˜ํ™˜๊ฐ’: v_1 * v_1 + ... + v_n * v_n""" return dot(v, v) def de_mean(xs: List[float]) -> List[float]: """ํ‰๊ท ๊ฐ’๊ณผ์˜ ์ฐจ์ด ๊ณ„์‚ฐ""" x_bar = mean(xs) return [x - x_bar for x in xs] def variance(xs: List[float]) -> float: """๋ถ„์‚ฐ๊ฐ’ ๊ณ„์‚ฐ. ๋‹จ, 2๊ฐœ ์ด์ƒ์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ์–ด์•ผ ํ•จ.""" assert len(xs) >= 2, "๋‘ ๊ฐœ ์ด์ƒ์˜ ๋ฐ์ดํ„ฐ ํ•„์š”" n = len(xs) deviations = de_mean(xs) return sum_of_squares(deviations) / (n - 1) variance(num_friends) # - # ### ํ‘œ์ค€ํŽธ์ฐจ # # ๋ถ„๊ฐ„๊ฐ’์˜ ๋‹จ์œ„๋Š” ์›๋ž˜ ๋‹จ์œ„์˜ ์ œ๊ณฑ์ด๋‹ค. # ๋”ฐ๋ผ์„œ ๋ถ„์‚ฐ๊ฐ’ ๋ณด๋‹ค๋Š” ๋ถ„์‚ฐ๊ฐ’์˜ ์ œ๊ณฑ๊ทผ์„ ๋ณด๋‹ค ๋งŽ์ด ์‚ฌ์šฉํ•œ๋‹ค. # # ํ‘œ๋ณธ์˜ ํ‘œ์ค€ํŽธ์ฐจ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ธฐํ˜ธ๋Š” ๋ณดํ†ต $s$์ด๋‹ค. # # $$s_X = \sqrt{\textit{Var}(X)}$$ # # `num_friends`์˜ ํ‘œ์ค€ํŽธ์ฐจ๋Š” 9.03์ด๋‹ค. # + import math def standard_deviation(xs: List[float]) -> float: return math.sqrt(variance(xs)) standard_deviation(num_friends) # - # #### ์ด์ƒ์น˜์˜ ์˜ํ–ฅ # # ์•ž์„œ ํ‰๊ท ๊ฐ’์ด ์ด์ƒ์น˜์˜ ์˜ํ–ฅ์„ ํฌ๊ฒŒ ๋ฐ›๋Š”๋‹ค๋Š” ๊ฒƒ์„ ๋ณด์•˜๋‹ค. # ๋”ฐ๋ผ์„œ ๋ถ„์‚ฐ๊ณผ ํ‘œ์ค€ํŽธ์ฐจ ์—ญ์‹œ ์ด์ƒ์น˜์˜ ์˜ํ–ฅ์„ ๋ฐ›๋Š”๋‹ค. # ## ์ƒ๊ด€๊ด€๊ณ„ # ๋‘ ๋ฐ์ดํ„ฐ์…‹์ด ์„œ๋กœ ์ƒ๊ด€์ด ์žˆ๋Š”๊ฐ€๋ฅผ ์•Œ๊ณ ์ž ํ•  ๋•Œ ์ƒ๊ด€๊ด€๊ณ„๋ฅผ ํŒŒ์•…ํ•˜๋ฉฐ, # ์ƒ๊ด€๊ด€๊ณ„์˜ ์ •๋„๋Š” ๋ณดํ†ต ๊ณต๋ถ„์‚ฐ(covariance) ๋˜๋Š” ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜(correlation)๋กœ ์ธก์ •ํ•œ๋‹ค. # # ์˜ˆ๋ฅผ ๋“ค์–ด, ์‚ฌ์šฉ์ž๊ฐ€ ์‚ฌ์ดํŠธ์—์„œ ๋ณด๋‚ด๋Š” ์‹œ๊ฐ„๊ณผ ์นœ๊ตฌ ์ˆ˜ ์‚ฌ์ด์˜ ์—ฐ๊ด€์„ฑ์„ ํŒŒ์•…ํ•˜๊ณ ์ž ํ•œ๋‹ค. print(num_friends) daily_minutes = [1,68.77,51.25,52.08,38.36,44.54,57.13,51.4,41.42, 31.22,34.76,54.01,38.79,47.59,49.1,27.66,41.03, 36.73,48.65,28.12,46.62,35.57,32.98,35,26.07, 23.77,39.73,40.57,31.65,31.21,36.32,20.45,21.93, 26.02,27.34,23.49,46.94,30.5,33.8,24.23,21.4, 27.94,32.24,40.57,25.07,19.42,22.39,18.42,46.96, 23.72,26.41,26.97,36.76,40.32,35.02,29.47,30.2, 31,38.11,38.18,36.31,21.03,30.86,36.07,28.66, 29.08,37.28,15.28,24.17,22.31,30.17,25.53,19.85, 35.37,44.6,17.23,13.47,26.33,35.02,32.09,24.81, 19.33,28.77,24.26,31.98,25.73,24.86,16.28,34.51, 15.23,39.72,40.8,26.06,35.76,34.76,16.13,44.04, 18.03,19.65,32.62,35.59,39.43,14.18,35.24,40.13, 41.82,35.45,36.07,43.67,24.61,20.9,21.9,18.79,27.61, 27.21,26.61,29.77,20.59,27.53,13.82,33.2,25,33.1, 36.65,18.63,14.87,22.2,36.81,25.53,24.62,26.25,18.21, 28.08,19.42,29.79,32.8,35.99,28.32,27.79,35.88,29.06, 36.28,14.1,36.63,37.49,26.9,18.58,38.48,24.48,18.95, 33.55,14.24,29.04,32.51,25.63,22.22,19,32.73,15.16, 13.9,27.2,32.01,29.27,33,13.74,20.42,27.32,18.23,35.35, 28.48,9.08,24.62,20.12,35.26,19.92,31.02,16.49,12.16, 30.7,31.22,34.65,13.13,27.51,33.2,31.57,14.1,33.42, 17.44,10.12,24.42,9.82,23.39,30.93,15.03,21.67,31.09, 33.29,22.61,26.89,23.48,8.38,27.81,32.35,23.84] # `num_friends`์™€ `daily_minutes`๋Š” ๊ฐ๊ฐ # ์‚ฌ์šฉ์ž๋ณ„ ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์ดํŠธ์—์„œ ๋จธ๋ฌด๋ฅด๋Š” ์‹œ๊ฐ„์„ ์ˆœ์„œ์— ๋งž๊ฒŒ ๋ฐ์ดํ„ฐ๋กœ ๋‹ด๊ณ  ์žˆ๋‹ค. # ### ๊ณต๋ถ„์‚ฐ # # ๋‘ ๋ฐ์ดํ„ฐ์…‹์˜ ๊ณต๋ถ„์‚ฐ์€ ๊ฐ ๋ฐ์ดํ„ฐ๋„ท์˜ ๋ณ€์ˆ˜๊ฐ€ ๊ฐ๊ฐ์˜ ํ‰๊ท ๊ฐ’์œผ๋กœ๋ถ€ํ„ฐ ๋–จ์–ด์ ธ ์žˆ๋Š” ์ •๋„๋ฅผ ๊ณ„์‚ฐํ•˜๋ฉฐ, # ์ˆ˜์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # ๋‘ ๋ฐ์ดํ„ฐ์…‹ $X$์™€ $Y$๋ฅผ ํฌ๊ธฐ๋ฅผ $n$์ด๋ผ ํ•˜์ž. # # ๊ทธ๋Ÿฌ๋ฉด, $X$์™€ $Y$์˜ ๊ณต๋ถ„์‚ฐ $Cov(X, Y)$๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # # $$ # Cov(X,Y) = \frac{\sum (X- E(X))(Y- E(Y))}{n-1} # $$ # ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์šฉ์‹œ๊ฐ„ ์‚ฌ์ด์˜ ๊ณต๋ถ„์‚ฐ์€ 22.43์ด๋‹ค. # + def covariance(xs: List[float], ys: List[float]) -> float: assert len(xs) == len(ys), "xs and ys must have same number of elements" return dot(de_mean(xs), de_mean(ys)) / (len(xs) - 1) covariance(num_friends, daily_minutes) # - # #### ๊ณต๋ถ„์‚ฐ์˜ ํŠน์ง•๊ณผ ํ•œ๊ณ„ # # ์–ด๋–ค ์‚ฌ์šฉ์ž์— ๋Œ€ํ•ด ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์šฉ์‹œ๊ฐ„ ๋ชจ๋‘ ํ‰๊ท ๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๋ชจ๋‘ ํฌ๋ฉด ๊ณต๋ถ„์‚ฐ์— ์–‘์ˆ˜์˜ ๊ฐ’์ด ๋”ํ•ด์ง„๋‹ค. # ๋ฐ˜๋ฉด์— ์นœ๊ตฌ์ˆ˜๊ฐ€ ํ‰๊ท ๋ณด๋‹ค ์ž‘์ง€๋งŒ, ์‚ฌ์šฉ์‹œ๊ฐ„์€ ํ‰๊ท ๋ณด๋‹ค ํฌ๋ฉด ์Œ์ˆ˜์˜ ๊ฐ’์ด ๊ณต๋ถ„์‚ฐ์— ๋”ํ•ด์ง„๋‹ค. # ๋”ฐ๋ผ์„œ ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์šฉ์‹œ๊ฐ„์ด ํ‰๊ท ์„ ๊ธฐ์ค€์œผ๋กœ ๋™์ผํ•œ ๋ฐฉํ–ฅ(ํฌ๊ฑฐ๋‚˜ ์ž‘๋‹ค ๊ธฐ์ค€)์ด๋ƒ ์•„๋‹ˆ๋ƒ๊ฐ€ ๊ณต๋ถ„์‚ฐ ๊ฐ’์— ์˜ํ–ฅ์„ ๋ฏธ์นœ๋‹ค. # # ๊ทธ๋Ÿฐ๋ฐ ์นœ๊ตฌ์ˆ˜๋Š” ๊ทธ๋Œ€๋กœ์ธ๋ฐ ์‚ฌ์šฉ์‹œ๊ฐ„๋งŒ ๋Š˜๋ฉด ๊ณต๋ถ„์‚ฐ์€ ์ฆ๊ฐ€ํ•œ๋‹ค. # ํ•˜์ง€๋งŒ ๊ทธ๋ ‡๋‹ค๊ณ  ํ•ด์„œ ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์šฉ์‹œ๊ฐ„์˜ ์—ฐ๊ด€์„ฑ์ด ์–ด๋–ป๊ฒŒ ๋ณ€ํ•œ ๊ฒƒ์ธ์ง€๋ฅผ ํŒ๋‹จํ•˜๊ธฐ๋Š” ์–ด๋ ต๋‹ค. # ์ฆ‰, ๊ณต๋ถ„์‚ฐ์ด ํฌ๋‹ค, ์ž‘๋‹ค์˜ ๊ธฐ์ค€์„ ์žก๊ธฐ๊ฐ€ ์–ด๋ ต๋‹ค. # ### ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜ # # ๊ณต๋ถ„์‚ฐ์˜ ํ•œ๊ณ„๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜๊ฐ€ ์ œ์‹œ๋˜์—ˆ๋‹ค. # ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜๋Š” ๊ณต๋ถ„์‚ฐ์„ ๊ฐ ๋ฐ์ดํ„ฐ์…‹์˜ ํ‘œ์ค€ํŽธ์ฐจ์˜ ๊ณฑ์œผ๋กœ ๋‚˜๋ˆ„์–ด # ๋‘ ๋ฐ์ดํ„ฐ์…‹ ์‚ฌ์ด์˜ **์„ ํ˜•** ์ƒ๊ด€๊ด€๊ณ„๋ฅผ ์ˆ˜์น˜๋กœ ๊ณ„์‚ฐํ•œ๋‹ค. # # ๋‘ ๋ฐ์ดํ„ฐ์…‹ $X, Y$์˜ ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜ ๊ณ„์‚ฐ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. # $$ # Correl(X,Y) = \frac{Cov(X,Y)}{s_X \cdot s_Y} # $$ # #### ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜์˜ ํŠน์ง• # # * ํ”ผ์–ด์Šจ ์ƒ๊ด€๊ณ„์ˆ˜๋Š” -1๊ณผ 1 ์‚ฌ์ด์˜ ์‹ค์ˆ˜์ด๋‹ค. # * 1์— ๊ฐ€๊นŒ์šธ ์ˆ˜๋ก ์–‘์˜ ์„ ํ˜•๊ด€๊ณ„๊ฐ€ ์„ฑ๋ฆฝํ•œ๋‹ค. # * -1์— ๊ฐ€๊นŒ์šธ ์ˆ˜๋ก ์Œ์˜ ์„ ํ˜•๊ด€๊ณ„๊ฐ€ ์„ฑ๋ฆฝํ•œ๋‹ค. # * 0์— ๊ฐ€๊น”์šธ ์ˆ˜๋ก ์„ ํ˜•๊ด€๊ณ„๊ฐ€ ์•ฝํ•ด์ง„๋‹ค. # <img src="https://raw.githubusercontent.com/codingalzi/pydata/master/notebooks/images/Correlation.png" width="70%"> # # ์ถœ์ฒ˜: [์œ„ํ‚ค๋ฐฑ๊ณผ](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) # ์นœ๊ตฌ์ˆ˜์™€ ์‚ฌ์šฉ์‹œ๊ฐ„ ์‚ฌ์ด์˜ ์ƒ๊ด€๊ด€๊ณ„๋Š” 0.25์ด๋ฉฐ, # ์ด๋Š” ๋‘ ๋ฐ์ดํ„ฐ์…‹ ์‚ฌ์ด์˜ ์ƒ๊ด€ ์ •๋„๊ฐ€ ํฌ์ง€ ์•Š์Œ์„ ์˜๋ฏธํ•œ๋‹ค. # + def correlation(xs: List[float], ys: List[float]) -> float: """๊ณต๋ถ„์‚ฐ ๊ณ„์‚ฐ""" stdev_x = standard_deviation(xs) stdev_y = standard_deviation(ys) if stdev_x > 0 and stdev_y > 0: return covariance(xs, ys) / stdev_x / stdev_y else: return 0 # if no variation, correlation is zero correlation(num_friends, daily_minutes) # + plt.scatter(num_friends, daily_minutes) plt.title("Correlation with an Outlier") plt.xlabel("# of friends") plt.ylabel("minutes per day") plt.show() # - # #### ์ด์ƒ์น˜์™€ ์ƒ๊ด€๊ด€๊ณ„ # # ์ด์ƒ์น˜๊ฐ€ ์ƒ๊ด€๊ด€๊ณ„์—๋„ ์˜ํ–ฅ์„ ์ค€๋‹ค. # # ์œ„ ์˜ˆ์ œ์—์„œ 100๋ช…์˜ ์นœ๊ตฌ๋ฅผ ๊ฐ€์ง„ ์‚ฌ์šฉ์ž์˜ ์‚ฌ์ดํŠธ ์‚ฌ์šฉ์‹œ๊ฐ„์ด 1๋ถ„์ด๋ฉฐ, # ์ด ์‚ฌ์šฉ์ž์˜ ๋ฐ์ดํ„ฐ๋Š” ํ™•์‹คํžˆ ์ด์ƒ์น˜๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค. # ์ด์ œ ์ด ์‚ฌ์šฉ์ž์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ์ƒ๊ด€๊ด€๊ณ„๋ฅผ ๊ณ„์‚ฐํ•˜๋ฉด, ์ด๋ฒˆ์—๋Š” ์ƒ๊ด€๊ณ„์ˆ˜๊ฐ€ 0.57์ด ๋œ๋‹ค. # ๋‘ ๋ฐ์ดํ„ฐ์…‹์˜ ์ƒ๊ด€์ •๋„๊ฐ€ ๋‘ ๋ฐฐ์ด์ƒ ์ปค์กŒ๋‹ค. # + outlier = num_friends.index(100) # ์ด์ƒ์น˜์˜ ์ธ๋ฑ์Šค num_friends_good = [x for i, x in enumerate(num_friends) if i != outlier] daily_minutes_good = [x for i, x in enumerate(daily_minutes) if i != outlier] correlation(num_friends_good, daily_minutes_good) # - # ์ด์ƒ์น˜์˜ ์กด์žฌ์—ฌ๋ถ€์— ๋”ฐ๋ฅธ ๋‘ ๋ฐ์ดํ„ฐ์…‹์˜ ๊ทธ๋ž˜ํ”„๋„ ๋ชจ์–‘์ด ๋‹ฌ๋ผ์ง€๋ฉฐ, # ์ด์ƒ์น˜๋ฅผ ์ œ๊ฑฐํ•œ ํ›„์˜ ๊ทธ๋ž˜ํ”„์˜ ์„ ํ˜• ์ƒ๊ด€๊ด€๊ณ„๊ฐ€ ๋ณด๋‹ค ๋ช…ํ™•ํ•˜๊ฒŒ ๋ณด์—ฌ์ง„๋‹ค. # ##### ์ด์ƒ์น˜ ์ œ๊ฑฐ ํ›„ # + plt.scatter(num_friends_good, daily_minutes_good) plt.title("Correlation after Removing the Outlier") plt.xlabel("# of friends") plt.ylabel("minutes per day") plt.show() # - # ## ์‹ฌ์Šจ์˜ ์—ญ์„ค # ์ƒ๊ด€๊ณ„์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•  ๋•Œ ์†Œ์œ„ ํ˜ผ์žฌ๋ณ€์ˆ˜(confounding variable)๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์œผ๋ฉด ์ž˜๋ชป๋œ ๊ฒฐ๊ณผ๋ฅผ ์–ป๋Š”๋‹ค. # ์˜ˆ๋ฅผ ๋“ค์–ด, # ๋ชจ๋“  ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๋ฅผ ์„œ๋ถ€์™€ ๋™๋ถ€๋กœ ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž. # ๊ทธ๋ฆฌ๊ณ  ๊ฐ ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๋“ค์˜ ์นœ๊ตฌ์ˆ˜๋ฅผ ํ™•์ธํ•ด ๋ณด์•˜๋‹ค. # | ์ง€์—ญ | ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž ์ˆ˜ | ํ‰๊ท  ์นœ๊ตฌ ์ˆ˜| # | --- | -------------| -------- | # | ์„œ๋ถ€ | 101 | 8.2๋ช… | # | ๋™๋ถ€ | 103 | 6.5๋ช… | # ์œ„ ํ‘œ์— ์˜ํ•˜๋ฉด ์„œ๋ถ€์— ์‚ฌ๋Š” ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๋“ค์ด ๋ณด๋‹ค ์‚ฌ๊ต์ ์ด๋‹ค. # ๊ทธ๋Ÿฐ๋ฐ ์ด๋ฒˆ์—” ๋ฐ•์‚ฌํ•™์œ„ ์†Œ์œ ์—ฌ๋ถ€๋ฅผ ํฌํ•จํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฅผ ์กฐ์‚ฌํ•˜์˜€๋‹ค. # | ์ง€์—ญ | ํ•™์œ„ | ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž ์ˆ˜ | ํ‰๊ท  ์นœ๊ตฌ ์ˆ˜| # | --- | --- | -------------| -------- | # | ์„œ๋ถ€ | ๋ฐ•์‚ฌ | 35 | 3.1๋ช… | # | ๋™๋ถ€ | ๋ฐ•์‚ฌ | 70 | 3.2๋ช… | # | ์„œ๋ถ€ | ๊ธฐํƒ€ | 66 | 10.9๋ช… | # | ๋™๋ถ€ | ๊ธฐํƒ€ | 33 | 13.4๋ช… | # # ๊ทธ๋žฌ๋”๋‹ˆ ๋ฐ•์‚ฌํ•™์œ„๊ฐ€ ์žˆ๊ฑฐ๋‚˜ ์—†๊ฑฐ๋‚˜ ๋™๋ถ€ ์ง€์—ญ์˜ ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๊ฐ€ ํ‰๊ท ์ ์œผ๋กœ ๋ณด๋‹ค ๋งŽ์€ ์นœ๊ตฌ๊ด€๊ณ„๋ฅผ ๋งบ๊ณ  ์žˆ๋‹ค. # ์•ž์„œ ๋ฐ•์‚ฌํ•™์œ„ ์—ฌ๋ถ€๋ฅผ ๋”ฐ์ง€์ง€ ์•Š์„ ๋•Œ์™€ ์„œ๋กœ ๋ชจ์ˆœ๋˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. # ์™œ ๊ทธ๋Ÿด๊นŒ? # # ์ •๋‹ต์€ ๋‘ ๋ฐ์ดํ„ฐ์…‹ ์‚ฌ์ด์˜ ์ƒ๊ด€๊ณ„์ˆ˜๋ฅผ ์ธก์ •ํ•  ๋•Œ ์ฃผ์–ด์ง„ ๋ฐ์ดํ„ฐ์…‹ ์ด์™ธ์˜ # ๋‹ค๋ฅธ ์กฐ๊ฑด๋“ค์€ ๋ชจ๋‘ ๋™์ผํ•˜๋‹ค๊ณ  ์ „์ œํ•˜๋Š” ๋ฐ์— ์žˆ๋‹ค. # ๊ทธ๋Ÿฐ๋ฐ ์œ„ ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๋“ค์˜ ๊ฒฝ์šฐ ๋ฐ•์‚ฌํ•™์œ„ ์†Œ์ง€ ์—ฌ๋ถ€๊ฐ€ ํ‰๊ท  ์นœ๊ตฌ ์ˆ˜์— ์˜ํ–ฅ์„ ์ค€๋‹ค. # # ๋”ฐ๋ผ์„œ ๋‹จ์ˆœํžˆ ์„œ๋ถ€์™€ ๋™๋ถ€๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์นœ๊ตฌ ์ˆ˜๋ฅผ ๋น„๊ตํ•˜์—ฌ ์ƒ๊ด€๊ณ„์ˆ˜๋ฅผ ๊ตฌํ•˜๋ฉด # ๋‹ค๋ฅธ ์กฐ๊ฑด์ด ๋™์ผํ•ด์•ผ ํ•œ๋‹ค๋Š” ์ „์ œ์กฐ๊ฑด์„ ์–ด๊ธด ์กฐ๊ฑด์—์„œ ๊ฒฐ๊ณผ๋ฅผ ์œ ๋„ํ•œ ๊ฒƒ์ด๋‹ค. # ๋ฐ•์‚ฌํ•™์œ„ ์†Œ์ง€ ์—ฌ๋ถ€๋ฅผ ์กฐ๊ฑด์œผ๋กœ ์ฒจ๊ฐ€ํ•˜๋ฉด ๋™๋ถ€ ์ง€์—ญ์˜ ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๊ฐ€ ๋ณด๋‹ค ์‚ฌ๊ต์ ์œผ๋กœ ๋‚˜์˜ค์ง€๋งŒ # ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” ๋ฐ˜๋Œ€์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๋Š” ์ด์œ ๋Š” # ๋‘ ๊ฐ€์ง€์ด๋‹ค. # # 1. ๋ฐ•์‚ฌ๋“ค์˜ ์นœ๊ตฌ ์ˆ˜๊ฐ€ ์ƒ๋Œ€์ ์œผ๋กœ ์ ๋‹ค. # 1. ๋™๋ถ€ ์ง€์—ญ์— ๋ฐ•์‚ฌ ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๊ฐ€ ๋ณด๋‹ค ๋งŽ์ด ์‚ฐ๋‹ค. # # ๋”ฐ๋ผ์„œ ์„œ๋ถ€ ์ง€์—ญ์˜ ๊ฒฝ์šฐ ๋ฐ•์‚ฌํ•™์œ„๊ฐ€ ์—†๋Š” ์‚ฌ๋žŒ๋“ค์ด ๋ณด๋‹ค ๋งŽ๊ณ  ๊ทธ๋“ค์ด ๋ณด๋‹ค ๋งŽ์€ ์นœ๊ตฌ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๊ธฐ์— # ์ „์ฒด ๋ฐ์ดํ„ฐ ๊ณผํ•™์ž๋“ค์˜ ํ‰๊ท  ์นœ๊ตฌ์ˆ˜๊ฐ€ ๋™๋ถ€ ๋ณด๋‹ค ๋†’์•„๊ฒŒ ๋œ๋‹ค. # ## ์ƒ๊ด€๊ณ„์ˆ˜ ๊ด€๋ จ ์ถ”๊ฐ€ ์ฃผ์˜์‚ฌํ•ญ # # ์ƒ๊ด€๊ด€๊ณ„๊ฐ€ 0 ๋˜๋Š” 1์— ์•„์ฃผ ๊ฐ€๊น๋‹ค๊ณ  ํ•ด์„œ ๋ฐ˜๋“œ์‹œ ์–ด๋–ค ๊ด€๊ณ„๋„ ์—†๋‹ค๊ฑฐ๋‚˜ # ๋งค์šฐ ๋ฐ€์ ‘ํ•ฉ ์„ ํ˜•๊ด€๊ณ„์ด๋‹ค๋ผ๊ณ  ์„ฃ๋ถ€๋ฅด๊ฒŒ ๊ฒฐ๋ก  ๋‚ด๋ฆฌ๋ฉด ์œ„ํ—˜ํ•˜๋‹ค. # ### ์˜ˆ์ œ 1 # # ๋‹ค์Œ ๋‘ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ์…‹ x์™€ y๋ฅผ ์‚ดํŽด๋ณด์ž. # # <table> # <tr> # <td>x</td> # <td>-2</td> # <td>-1</td> # <td>0</td> # <td>1</td> # <td>2</td> # </tr> # <tr> # <td>y</td> # <td>2</td> # <td>1</td> # <td>0</td> # <td>1</td> # <td>2</td> # </tr> # </table> # x์™€ y์˜ ์ƒ๊ด€๊ณ„์ˆ˜๋Š” 0์ด๋‹ค. # + x = [-2, -1, 0, 1, 2] y = [ 2, 1, 0, 1, 2] correlation(x,y) # - # ํ•˜์ง€๋งŒ y๋Š” x์˜ ํ•ญ๋ชฉ์˜ ์ ˆ๋Œ“๊ฐ’์„ ํ•ญ๋ชฉ์œผ๋กœ ๊ฐ–๋Š”๋‹ค. # ์ฆ‰, ์ด๋Ÿฐ ๋ฐ์ดํ„ฐ๋Š” ์ƒ๊ด€๊ณ„์ˆ˜๋กœ ๋‘ ๋ฐ์ดํ„ฐ์…‹์˜ ์—ฐ๊ด€์„ฑ์„ ์ธก์ •ํ•  ์ˆ˜ ์—†๋‹ค. # ### ์˜ˆ์ œ 2 # # ๋‹ค์Œ ๋‘ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ์…‹ x์™€ y๋ฅผ ์‚ดํŽด๋ณด์ž. # # <table> # <tr> # <td>x</td> # <td>-2</td> # <td>-1</td> # <td>0</td> # <td>1</td> # <td>2</td> # </tr> # <tr> # <td>y</td> # <td>99.98</td> # <td>99.99</td> # <td>100</td> # <td>100.01</td> # <td>100.02</td> # </tr> # </table> # x์™€ y์˜ ์ƒ๊ด€๊ณ„์ˆ˜๋Š” 1์ด๋‹ค. # + x = [-2, -1, 0, 1, 2] y = [99.98, 99.99, 100, 100.01, 100.02] correlation(x,y) # - # ํ•˜์ง€๋งŒ ๋‘ ๋ฐ์ดํ„ฐ์…‹ ์‚ฌ์ด์˜ ์„ ํ˜•๊ด€๊ณ„๊ฐ€ ์ •๋ง๋กœ ์™„๋ฒฝํ•˜๊ฒŒ ์„ ํ˜•์ธ์ง€์— ๋Œ€ํ•ด์„œ๋Š” ์žฅ๋‹ดํ•  ์ˆ˜ ์—†๋‹ค. # ## ์ƒ๊ด€๊ด€๊ณ„์™€ ์ธ๊ณผ๊ด€๊ณ„ # ๋‘ ๋ฐ์ดํ„ฐ์…‹ ์‚ฌ์ด์— ์ƒ๊ด€๊ด€๊ณ„๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•ด์„œ ํ•œ ์ชฝ์ด ๋‹ค๋ฅธ ์ชฝ์— ์˜ํ–ฅ์„ ์ฃผ๋Š” ์ธ๊ณผ๊ด€๊ณ„๊ฐ€ ์žˆ๋‹ค๊ณ  ์ฃผ์žฅํ•  ์ˆ˜ ์—†๋‹ค. # ์™œ๋ƒํ•˜๋ฉด ๋‘ ๋ฐ์ดํ„ฐ์…‹์— ์˜ํ–ฅ์„ ์ฃผ๋Š” ๋‹ค๋ฅธ ์™ธ๋ถ€ ์š”์†Œ๊ฐ€ ์กด์žฌํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. # # ์˜ˆ๋ฅผ ๋“ค์–ด, ์นœ๊ตฌ ์ˆ˜๋ฅผ ๋‹ด์€ `num_friends`์™€ ์‚ฌ์ดํŠธ ์‚ฌ์šฉ์‹œ๊ฐ„์„ ๋‹ด์€ `daily_minutes`์˜ ๊ด€๊ณ„๋ฅผ ์‚ดํŽด๋ณด์ž. # ๊ทธ๋Ÿฌ๋ฉด ์ตœ์†Œ ์„ธ ๊ฐ€์ง€ ์‹œ๋‚˜๋ฆฌ์˜ค๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. # # 1. ์‚ฌ์ดํŠธ์—์„œ ๋งŽ์€ ์‹œ๊ฐ„์„ ๋ณด๋‚ผ ์ˆ˜๋ก ๋งŽ์€ ์นœ๊ตฌ๋ฅผ ์‚ฌ๊ท„๋‹ค. # 1. ๋งŽ์€ ์นœ๊ตฌ๊ฐ€ ์žˆ์œผ๋‹ˆ๊นŒ ์‚ฌ์ดํŠธ์—์„œ ์‹œ๊ฐ„์„ ๋ณด๋‹ค ๋งŽ์ด ๋ณด๋‚ธ๋‹ค. # 1. ์‚ฌ์ดํŠธ์—์„œ ๋งŽ์€ ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์œผ๋‹ˆ๊นŒ ์‚ฌ์šฉ์‹œ๊ฐ„์ด ๊ธธ์–ด์ง€๊ณ , ๊ทธ๋Ÿฌ๋‹ค ๋ณด๋‹ˆ๊นŒ ์นœ๊ตฌ๊ฐ€ ๋Š˜์–ด๋‚œ๋‹ค. # # ์ด ์ค‘์— ์–ด๋–ค ๊ฒƒ์ด ๋งž๋Š”์ง€๋Š” ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ ํ™•์ธํ•ด๋ด์•ผ ํ•œ๋‹ค. # ์˜ˆ๋ฅผ ๋“ค์–ด, ์‚ฌ์šฉ์ž ์ง‘๋‹จ์„ ์ž„์˜๋กœ ๋‘ ๋ชจ๋‘ ์œผ๋กœ ๋‚˜๋ˆ„๊ณ , ํ•œ์ชฝ ๋ชจ๋‘ ์—๋งŒ ํŠน์ • ์นœ๊ตฌ๋“ค์˜ ๊ธ€๋งŒ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ๊ณผ ๊ฐ™์ด, # ํ•œ ์ชฝ ๋ชจ๋‘ ์—๋งŒ ์˜ํ–ฅ์„ ์ฃผ๋Š” ์‹คํ—˜์„ ํ•˜๊ณ  ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋น„๊ตํ•œ๋‹ค. # ์ด๋Ÿฐ ์‹์œผ๋กœ ํ•ด์„œ ์ƒ๊ด€๊ด€๊ณ„์˜ ์ง„์งœ ๊ทผ๊ฑฐ๋ฅผ ์–ป์–ด๋‚ด๋„๋ก ํ•ด์•ผ ํ•œ๋‹ค. # ## ์—ฐ์Šต๋ฌธ์ œ # ### ๋ฌธ์ œ 1 # ๋ณธ๋ฌธ ๋‚ด์šฉ์„ ๋„˜ํŒŒ์ด ์–ด๋ ˆ์ด ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋ผ. # ### ๋ฌธ์ œ 2 # ๋ณธ๋ฌธ ๋‚ด์šฉ์„ ํŒ๋‹ค์Šค ์‹œ๋ฆฌ์ฆˆ์™€ ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„ ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋ผ.
notebooks/pydata06_Statistics_basics.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/ris8/ris8.github.io/blob/master/AODFinal.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/", "height": 213} id="MvUgQnZronlk" outputId="15de0972-126d-455b-abc1-61dd8df96e4d" import pandas as pd import seaborn as sns df = pd.read_csv("https://ris8.github.io/assets/img/survey.csv")#pull dataset from blog website since colab is annoying and won't just grab from drive df.sample() # + [markdown] id="P3WQN9jU4AyR" # #Pre-analysis # This survey was administered to college students and their friends, and is made up of voluntary answers. Both of these should be kept in mind; all we can conclude is that these subjects self-reported in a certain way. # I hypothesize that students who said they came from a city are less likely to fear public speaking than those who say they came from a village. # Null hypothesis: students who say they come from a city are **not** less likely to fear public speaking than those who say they came from a village # Alternative hypothesis: students who say they come from a city **are** less likely to fear public speaking than those who say they came from a village # + colab={"base_uri": "https://localhost:8080/", "height": 298} id="ycu43Gj23Ts0" outputId="9a02b9ec-2d3a-4cb8-a055-bf5cd9db2c1d" temp = df["Village - town"].value_counts()#analyze distribution of town v. city and show relevant visualization temp.plot.pie() print(temp/len(df)) # + [markdown] id="QMM0FA2a75mY" # From this, we can see that (in this dataset) roughly 70% of people say they are from cities, while roughly 30% say they are from villages. # + colab={"base_uri": "https://localhost:8080/", "height": 422} id="-hX0d19A2KSo" outputId="7382db02-63e8-4a1a-8949-f5744657e589" df["Public speaking"].value_counts().plot.bar() df["Public speaking"].describe() # + [markdown] id="xBjwaOgZ9OA4" # Here, we see that the 'average' fear of public spekaing is a ~3.5, meaning people are generally pretty afaid of public speaking. We also see that a 5, 'very afraid of,' is the most common report, which descends from there down to 1. Technically, the standard deviation is roughly 1.27, but that's not very relevant since the information is both discrete and very tightly boxed in, between 1 and 5. # + colab={"base_uri": "https://localhost:8080/", "height": 422} id="X8MLeAEH-DIk" outputId="48ed899a-57df-44fc-cc30-f66770be9a40" temp = df[df["Village - town"] == "village"]["Public speaking"]#get distribution for villagers temp.value_counts().plot.bar() temp.describe() # + colab={"base_uri": "https://localhost:8080/", "height": 422} id="OsT3pgZa-Zkm" outputId="c3d0f5c5-1222-4204-a7c4-3b27fa8a2f61" temp = df[df["Village - town"] == "city"]["Public speaking"]#get distribution for city peeps temp.value_counts().plot.bar() temp.describe() # + [markdown] id="p1zSKskA-3tj" # From the initial visualization, it seems like the null hypothesis is correct, as the distributions seem nearly identical. # + id="r0I7mN50-_WS" colab={"base_uri": "https://localhost:8080/"} outputId="18b81100-af25-4b56-84d8-518424429eac" #For bootstrapping, we'll take a point statistic for city and bootstrap town cityMean = df[df["Village - town"] == "city"]["Public speaking"].mean() villData = df[df["Village - town"] == "village"]["Public speaking"] villMeans = []#store the bootstrapped means here for i in range(100000): villMeans.append(villData.sample(frac = 1, replace = True).mean()) pVal=0 for i in villMeans:#calculate pVal by checking what percentage of bootstrapped means are above the point statistic if i <= cityMean: pVal+=1 pVal/=len(villMeans)#divide the number of entries above the point statistic, by the total number of entries (entries being the bootstrapped Adelie body mass averages) print(pVal) # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="x_tMXaM-n3FP" outputId="ae6061e2-229d-422c-bf00-270f58015bc7" import matplotlib.pyplot as plt sns.violinplot(x=villMeans) plt.axvline(cityMean, 0, 1, color = "red")#draw a marker where the point statistic for city-peeps is # + [markdown] id="EveNygV1qVb8" # #Analysis # So, with a Pval of ~58%, we have not proved the alternative hypothesis. As we can see from the visualization, the boostrapped village means are actually slightly lower than the city point statistic, which means they were recorded as having slightly less fear of public speaking (the opposite of our alternative hypothesis). However, there is not enough information to swing either way, as the Pval is anything but conclusive.
AODFinal.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 """TODO: change filename to Metadata file in project of interest""" meta = pd.read_csv('Metadata KPNALF_Other.csv') print("Number of Isolates = ", len(meta)) # - """TODO: change filename to Vitek file in project of interest""" vt = pd.read_csv('Vitek KPNALF_Other.csv') print("Number of Isolates = ", len(vt)) # + """ Note: This section relates the names of the drugs in the Vitek results to the drug names in the database""" vt_dict = {'Testing Date': 'vitek_date', 'AM-Ampicillin': 'Ampicillin (AMP)', 'AMC-Amoxicillin/Clavulanic Acid': 'Amoxicillin/Clavulanic (AUG)', 'AN-Amikacin': 'Amikacin (AMK)', 'CAZ-Ceftazidime': 'Ceftazidime (CAZ)', 'CIP-Ciprofloxacin': 'Ciprofloxacin (CIP)', 'CRO-Ceftriaxone': 'Ceftriaxone (CRO)', 'CZ-Cefazolin': 'Cefazolin (CFZ)', 'FEP-Cefepime': 'Cefepime (FEP)', 'FOX-Cefoxitin': 'Cefoxitin (CFX)', 'FT-Nitrofurantoin': 'Nitrofurantoin (NIT) ', 'GM-Gentamicin': 'Gentamicin (GEN)', 'MEM-Meropenem': 'Meropenem (MEM)', 'NOR-Norfloxacin': 'Norfloxacin (NOR)', 'SXT-Trimethoprim/Sulfamethoxazole': 'Trimethoprim/Sulfamethoxazole (SXT)', 'TCC-Ticarcillin/Clavulanic Acid': 'Ticarcillin/Clavulanic acid (TIM)', 'TM-Tobramycin': 'Tobramycin (TOB)', 'TMP-Trimethoprim': 'Trimethoprim (TMP)', 'TZP-Piperacillin/Tazobactam': 'Piperacillin/Tazobactam (PTZ)', 'P-Benzylpenicillin': 'Benzylpenicillin', 'OXSF-Cefoxitin Screen': 'Cefoxitin Screen', 'CM-Clindamycin': 'Clindamycin', 'DAP-Daptomycin': 'Daptomycin', 'E-Erythromycin': 'Erythromycin', 'FA-Fusidic Acid': 'Fusidic Acid', 'ICR-Inducible Clindamycin Resistance': 'Inducable Clindamycin Resistance', 'LNZ-Linezolid': 'Linezolid', 'MUP-Mupirocin': 'Mupirocin', 'OX1-Oxacillin': 'Oxacillin', 'RA-Rifampicin': 'Rifampicin', 'TEC-Teicoplanin': 'Teicoplanin', 'TE-Tetracycline': 'Tetracycline', 'VA-Vancomycin': 'Vancomycin' } # - """ Note: The organism dictionary is important!! Abbreviated names in vitek results do not match names in the database and finding the correct results when multiple swabs/bugs are detected can become difficult/impossible """ org_dict = pd.read_excel('organism_dictionary_finalised.xlsx') org_dict['Vitek name 1'] = org_dict['Vitek name 1'].str.lstrip() org_dict['Vitek name 2'] = org_dict['Vitek name 2'].str.lstrip() org_dict['Vitek name 3'] = org_dict['Vitek name 3'].str.lstrip() org_dict['Vitek name 4'] = org_dict['Vitek name 4'].str.lstrip() """ Read most recent library file with Vitek results""" df_vitek = pd.read_excel('Vitek_Library_2017_Jun2021.xlsx') print(len(df_vitek)) # + """ This function does the actual mapping from vitek results to the database format """ def map_vitek_template(df_vitek, meta, vitek, org_dict, vt_dict, outfile): vt_template = vitek print("Beginning to search and assign vitek records") for i, row in vt_template.iterrows(): if row['data'] == 'Yes' or row['data'] == 'Yes updated': continue # print(row['tube_code']) acc = meta.loc[(meta['tube_code'] == row['tube_code']), 'ID_number'] """ Accession number if needed to find the vitek result""" if acc.isnull().any(): vt_template.loc[i, 'data'] = 'No' print(row['tube_code'], 'no accession number') continue acn = acc.values[0] acn = int(acn.replace('-', '')) t_acn_match = df_vitek.loc[(df_vitek['Lab ID'] == acn)] ##first look for an matching accession number if len(t_acn_match) == 0: vt_template.loc[i, 'data'] = 'No' print(row['tube_code'], "No matching found in vitek records") continue org_name = meta.loc[(meta['tube_code'] == row['tube_code']), 'species_reported'].values[0] org_genus = org_name.split()[0] """ Find match to exact organism but also just the genus""" match_organisms = org_dict.loc[org_dict['IsolName'].str.match(org_name), :].dropna(axis=1).values.tolist() match_genus = org_dict.loc[org_dict['IsolName'].str.match(org_genus), :].dropna(axis=1).values.tolist() """ if you find nothing, you're shit outta luck""" if len(match_organisms) == 0 and len(match_genus) == 0: if len(t_acn_match) > 0: print(row['tube_code'], org_name, ' no match found in org dictionary') print("But there is an ACN match", t_acn_match.loc[:, 'Organism Name']) continue # print("Orgs len = ", match_organisms) # print("genus = ", match_genus) """ let's see if there are exact matches or just matches to genus""" t_exact_match = [] t_genus_match = [] if len(match_organisms) > 0: match_organisms = match_organisms[0][1:] t_exact_match = df_vitek.loc[(df_vitek['Lab ID'] == acn) & (df_vitek['Organism Name'].isin(list(match_organisms)))] if len(match_genus) > 0: match_genus = match_genus[0][1:] t_genus_match = df_vitek.loc[(df_vitek['Lab ID'] == acn) & (df_vitek['Organism Name'].isin(list(match_genus)))] # print(t_genus_match) if len(t_exact_match) == 0 and len(t_genus_match) == 0: # no record found vt_template.loc[i, 'data'] = 'No' print(acn, 'no record found') continue elif len(t_exact_match) == 1: print(row['tube_code'], " one record found") vt_template.loc[i, 'data'] = 'Yes' vt_template.loc[i, 'vitek_run'] = 'Alfred' for j in vt_dict.keys(): if j == 'Testing Date': vt_template.loc[i, vt_dict[j]] = t_exact_match.loc[:, j].dt.strftime('%Y-%m-%d').values[0] else: vt_template.loc[i, vt_dict[j]] = t_exact_match.loc[:, j].values[0] elif len(t_genus_match) == 1: print(row['tube_code'], " one record found") vt_template.loc[i, 'data'] = 'Yes' vt_template.loc[i, 'vitek_run'] = 'Alfred' for j in vt_dict.keys(): vt_template.loc[i, vt_dict[j]] = t_genus_match.loc[:, j].values[0] elif len(t_exact_match) > 1: print(row['tube_code'], " > 1 record found") """ find the index where Testing Date is max""" key_index = t_exact_match.index[t_exact_match['Testing Date'].argmax()] vt_template.loc[i, 'data'] = 'Yes Updated' vt_template.loc[i, 'vitek_run'] = 'Alfred' for j in vt_dict.keys(): if j.find('Testing Date') > -1: vt_template.loc[i, vt_dict[j]] = t_exact_match.loc[key_index, j].strftime('%Y-%m-%d') else: vt_template.loc[i, vt_dict[j]] = t_exact_match.loc[key_index, j] elif len(t_genus_match) >= 1: print(row['tube_code'], " > 1 record found") key_index = t_genus_match.index[t_genus_match['Testing Date'].argmax()] """ find the index where Testing Date is a match""" vt_template.loc[i, 'data'] = 'Yes Updated' vt_template.loc[i, 'vitek_run'] = 'Alfred' for j in vt_dict.keys(): if j.find('Testing Date') > -1: vt_template.loc[i, vt_dict[j]] = t_genus_match.loc[key_index, j].strftime('%Y-%m-%d') else: vt_template.loc[i, vt_dict[j]] = t_genus_match.loc[key_index, j] print("Done.") vt_template.to_csv(outfile, index=False) return vt_template """ TODO: Remember to change the name of the output file!""" outfile_vt = 'Vitek_KPNALF_Other' + 'temp' + '.csv' vt_template = map_vitek_template(df_vitek, meta, vt, org_dict, vt_dict, outfile_vt)
Updating_vitek_manually_specify_projects.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 df = pd.read_csv('users.csv', header=None, names=["UserID", "PersonaID", "CohortID"]) df.info() df.head() # + # How many unique users? df['UserID'].nunique() # + # How many unique personas? df['PersonaID'].nunique() # + # How many unique cohorts? df['CohortID'].nunique() # + # Average number of users in each cohort? df['UserID'].nunique() / df['CohortID'].nunique() # - # Number of users in each Cohort: mean, min, max, etc. cohort_counts = df['CohortID'].value_counts() cohort_counts.describe() # + # Further stats about each cohort rows = [] for cohortID in df['CohortID'].unique(): _tmp = df[df['CohortID'] == cohortID] _persona_counts = _tmp['PersonaID'].value_counts() _num_users = _tmp.shape[0] row = { 'CohortID': cohortID, 'NumUsers': _num_users, 'NumPersonas': _tmp['PersonaID'].nunique(), 'PersonaCount_Max': _persona_counts.max(), 'PersonaCount_Mean': _persona_counts.mean(), 'PersonaCount_Min': _persona_counts.min(), 'PersonaCount_EQ1': sum(_persona_counts == 1), 'PersonaCount_GT1': sum(_persona_counts > 1), 'PersonaCount_GT5': sum(_persona_counts > 5), } rows.append(row) p = pd.DataFrame(rows, columns=list(row.keys())) p.sort_values('PersonaCount_Mean', ascending=False) # + # Further stats about each Persona rows = [] for personaID in df['PersonaID'].unique(): _tmp = df[df['PersonaID'] == personaID] _cohort_counts = _tmp['CohortID'].value_counts() _num_users = _tmp.shape[0] row = { 'PersonaID': personaID, 'NumUsers': _num_users, 'NumCohorts': _tmp['CohortID'].nunique(), 'CohortCount_Max': _cohort_counts.max(), 'CohortCount_Mean': _cohort_counts.mean(), 'CohortCount_EQ1': sum(_cohort_counts == 1), 'CohortCount_GT1': sum(_cohort_counts > 1), 'CohortCount_GT5': sum(_cohort_counts > 5), } rows.append(row) p = pd.DataFrame(rows, columns=list(row.keys())) p.sort_values('NumUsers')
demos/floc_simulation3/ResultsAnalysis.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.0 64-bit # language: python # name: python3 # --- # # Collect with requests: PBS.org # Imagine you are in a research project exploring how the narrative around technological innovations such as Artificial Intelligence changes over time. You have a "gut feeling" that AI in 2005 was considered to be heralded as saving the world, whilst in 2022 AI is considered a threat on my levels. # # For this project, you decide to collect news articles about Artificial Intelligence from online newssites such as [pbs.org/newshour](https://www.pbs.org/newshour). Once collected, the content could describe something about AI's discourse and issues. # # In the first few Notebooks we are going to look at a single article to extract and gradually work towards a complete scraper. # ### 1. Make a simple request # # + import requests # we are going to look at one article url = 'https://www.pbs.org/newshour/economy/google-ceo-calls-for-regulation-of-artificial-intelligence' # request the page page = requests.get(url) # - # ### 2. Review request # Look at the variable `page` and you will see a <Response [200](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)> which means that the request has succeeded and that information was returned. By using `page.content` you will see the content of the returned response. As you can imagine the output will exceed the size limit of this Notebook. Go the the website itself and look at the source. # display the page.content page
Solutions/Week 02/webscraping/01-collect-with-requests.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 # --- # # Nifti Read Example # # The purpose of this notebook is to illustrate reading Nifti files and iterating over patches of the volumes loaded from them. # # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/nifti_read_example.ipynb) # ## Setup environment # + tags=[] # !python -c "import monai" || pip install -q "monai-weekly[nibabel]" # - # ## Setup imports # + tags=[] # Copyright 2020 MONAI Consortium # 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. import glob import os import shutil import tempfile import nibabel as nib import numpy as np import torch from monai.config import print_config from monai.data import ( ArrayDataset, GridPatchDataset, create_test_image_3d, PatchIter) from monai.transforms import ( AddChannel, Compose, LoadImage, RandSpatialCrop, ScaleIntensity, ToTensor, ) from monai.utils import first print_config() # - # ## Setup data directory # # You can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. # This allows you to save results and reuse downloads. # If not specified a temporary directory will be used. # + tags=[] directory = os.environ.get("MONAI_DATA_DIRECTORY") root_dir = tempfile.mkdtemp() if directory is None else directory print(root_dir) # - # Create a number of test Nifti files: for i in range(5): im, seg = create_test_image_3d(128, 128, 128) n = nib.Nifti1Image(im, np.eye(4)) nib.save(n, os.path.join(root_dir, f"im{i}.nii.gz")) n = nib.Nifti1Image(seg, np.eye(4)) nib.save(n, os.path.join(root_dir, f"seg{i}.nii.gz")) # Create a data loader which yields uniform random patches from loaded Nifti files: # + tags=[] images = sorted(glob.glob(os.path.join(root_dir, "im*.nii.gz"))) segs = sorted(glob.glob(os.path.join(root_dir, "seg*.nii.gz"))) imtrans = Compose( [ LoadImage(image_only=True), ScaleIntensity(), AddChannel(), RandSpatialCrop((64, 64, 64), random_size=False), ToTensor(), ] ) segtrans = Compose( [ LoadImage(image_only=True), AddChannel(), RandSpatialCrop((64, 64, 64), random_size=False), ToTensor(), ] ) ds = ArrayDataset(images, imtrans, segs, segtrans) loader = torch.utils.data.DataLoader( ds, batch_size=10, num_workers=2, pin_memory=torch.cuda.is_available() ) im, seg = first(loader) print(im.shape, seg.shape) # - # Alternatively create a data loader which yields patches in regular grid order from loaded images: # + tags=[] imtrans = Compose([LoadImage(image_only=True), ScaleIntensity(), AddChannel(), ToTensor()]) segtrans = Compose([LoadImage(image_only=True), AddChannel(), ToTensor()]) ds = ArrayDataset(images, imtrans, segs, segtrans) patch_iter = PatchIter(patch_size=(64, 64, 64), start_pos=(0, 0, 0)) def img_seg_iter(x): return (zip(patch_iter(x[0]), patch_iter(x[1])),) ds = GridPatchDataset(ds, img_seg_iter, with_coordinates=False) loader = torch.utils.data.DataLoader( ds, batch_size=10, num_workers=2, pin_memory=torch.cuda.is_available() ) im, seg = first(loader) print("image shapes:", im[0].shape, seg[0].shape) print("coordinates shapes:", im[1].shape, seg[1].shape) # - # ## Cleanup data directory # # Remove directory if a temporary was used. if directory is None: shutil.rmtree(root_dir)
modules/nifti_read_example.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 # --- # # Microlensing: Fitting for parameters # # In this notebook, we use a simple Microlensing point-source point-lens model with 3 parameters: # - $t_0$, $u_0$ time and separation during the closest approach between the lens and the source, # - $t_E$, Einstein timescale, # # to fit the microlensing candidate data. # + import matplotlib.pyplot as plt import seaborn as sns sns.set_context('talk') from fink_science.conversion import dc_mag from fink_client.avroUtils import AlertReader import numpy as np import pandas as pd from mulens_helper import fit_ml_de_simple, mulens_simple # - # ## Load microlensing candidates # # We previously found 3 microlensing candidates in ZTF data using Fink between November 2019 and June 2020. The alert data has been exported as Avro files and can be manipulated using `fink_client`: # + # Load alert data r = AlertReader('data/microlensing_object_candidates/') pdf_object = r.to_pandas() objects = np.unique(pdf_object.objectId) # - # To perform the fit, we need first to convert the PSF-fit magnitude into apparent magnitde. The fit is then done on the two bands simultaneously (g&r): # + def extract(arrays, dtype=np.float): """ extract historical and current measurements from all alerts. """ a = [] for array in arrays: a = np.concatenate((a, np.array(array, dtype=dtype))) return a # Do it object-by-object for objectid in objects: # Container for measurements subpdf = pd.DataFrame({ 'filtercode': [], 'mag_g': [], 'magerr_g': [], 'mag_r': [], 'magerr_r': [], 'time': [], 'name': [] }) pdf = pdf_object[pdf_object.objectId == objectid] # extract historical and current measurements jds_ = extract(list(pdf['cjd'].to_dict().values())) jds_, indices = np.unique(jds_, return_index=True) subpdf['time'] = jds_ subpdf['name'] = pdf['objectId'] magpsf = extract(list(pdf['cmagpsf'].to_dict().values()))[indices] sigmapsf = extract(list(pdf['csigmapsf'].to_dict().values()))[indices] diffmaglim = extract(list(pdf['cdiffmaglim'].to_dict().values()))[indices] fids = extract(list(pdf['cfid'].to_dict().values()))[indices] magnr = extract(list(pdf['cmagnr'].to_dict().values()))[indices] sigmagnr = extract(list(pdf['csigmagnr'].to_dict().values()))[indices] magzpsci = extract(list(pdf['cmagzpsci'].to_dict().values()))[indices] isdiffpos = extract(list(pdf['cisdiffpos'].to_dict().values()), dtype=str)[indices] # Compute apparent magnitude from PSF-fit magnitude mag_dc, err_dc = np.array([ dc_mag(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) for i in zip( np.array(fids), np.array(magpsf), np.array(sigmapsf), np.array(magnr), np.array(sigmagnr), np.array(magzpsci), np.array(isdiffpos)) ]).T print(len(mag_dc)) # Loop over filters fig = plt.figure(figsize=(12, 4)) conversiondict = {1.0: 'g', 2.0: 'r'} for fid in np.unique(fids): # Select filter mask_fid = fids == fid # Remove upper limits maskNone = np.array(magpsf) == np.array(magpsf) # Remove outliers maskOutlier = np.array(mag_dc) < 22 # Total mask mask = mask_fid * maskNone * maskOutlier # plot data plt.errorbar( jds_[mask], mag_dc[mask], err_dc[mask], ls='', marker='o', label='{}'.format(conversiondict[fid]), color='C{}'.format(int(fid)-1)) # Gather data for the fitter subpdf['filtercode'] = pd.Series(fids).replace(to_replace=conversiondict) subpdf[f'mag_{conversiondict[fid]}'] = mag_dc subpdf[f'magerr_{conversiondict[fid]}'] = err_dc # Nullify data which is not this filter subpdf[f'magerr_{conversiondict[fid]}'][~mask] = None subpdf[f'mag_{conversiondict[fid]}'][~mask] = None # Fit for parameters results = fit_ml_de_simple(subpdf) msg = f""" u0 = {results.u0} t0 = {results.t0} tE = {results.tE} """ print(msg) time = np.arange(jds_[0], jds_[-1], 1) plt.plot(time, mulens_simple(time, results.u0, results.t0, results.tE, results.magStar_g), color='C0') plt.plot(time, mulens_simple(time, results.u0, results.t0, results.tE, results.magStar_r), color='C1') plt.axvline(results.t0, color='C3', ls='--') plt.xlabel("Time [jd]") plt.ylabel('Apparent magnitude') plt.title(objectid) plt.gca().invert_yaxis() plt.legend() plt.show() # - # The candidate `ZTF20aaaacan` can be discarded - it does not appear as microlensing event at all (he passes all search criteria though!). As expected, only `ZTF18acvqrrf` and `ZTF20aauqwzc` give relevant results, with Einstein times around 15-20 and impact parameters around 0.4. # # We note that `ZTF18acvqrrf` has an interesting features around `jd=860` and `jd=880`. It would be interesting to use a more complex model and see if this feature means something for the object.
notebooks/Fink_microlensing_fit.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 # --- # # Package import import numpy as np import matplotlib.pyplot as plt import pandas as pd import statsmodels.api as sm import random import timeit import sklearn import sklearn.model_selection import matplotlib.pyplot as plt import matplotlib as mpl import re import string from functools import reduce from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.feature_selection import SelectPercentile from sklearn.linear_model import LogisticRegression from sklearn.model_selection import KFold from sklearn.utils import resample from sklearn import datasets from sklearn.feature_selection import RFE from sklearn.utils import shuffle from sklearn import metrics from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder from sklearn import model_selection from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from xgboost import XGBClassifier from sklearn.metrics import classification_report random.seed(9001) # For Reproducibility of Results # %matplotlib inline pd.set_option('display.max_rows', 300) # # Data Load # + #NOMIS - CENSUS DATA - DIMENSIONS population = pd.read_csv('postcodeSector/populationCount.csv', skiprows=8) # 8039*8 ethnicMinority = pd.read_csv('postcodeSector/Ethnic.csv', skiprows=8) # 8039*96 ageStructure = pd.read_csv('postcodeSector/ageStructure.csv', skiprows=8) #8039*20 relationalSituation = pd.read_csv('postcodeSector/relational.csv', skiprows=8) #8039*8 livingArrangements = pd.read_csv('postcodeSector/livingArrangements.csv', skiprows=8) #8039*9 householdComposition = pd.read_csv('postcodeSector/householdComposition.csv', skiprows=8) #8039*23 notInEmploymentDependencies = pd.read_csv('postcodeSector/notInEmploymentDependencies.csv', skiprows=8) #8039*10 loneParentDependencies = pd.read_csv('postcodeSector/loneParentDependencies.csv', skiprows=8)#8039*13 ethnicGroup = pd.read_csv('postcodeSector/ethnicGroup.csv', skiprows=8) #8039*25 industry = pd.read_csv('postcodeSector/industry.csv', skiprows=8)#8039*26 tenure = pd.read_csv('postcodeSector/tenure.csv', skiprows=8) #8039*8 hoursWorked = pd.read_csv('postcodeSector/hoursWorked.csv', skiprows=8) #8039*6 dwelling = pd.read_csv('postcodeSector/dwelling.csv', skiprows=8) #8039*5 englishProf = pd.read_csv('postcodeSector/englishProf.csv', skiprows=8) #8039*7 centralHeating = pd.read_csv('postcodeSector/centralHeating.csv', skiprows=8) #8039*9 passportHeld = pd.read_csv('postcodeSector/passportHeld.csv', skiprows=7) #8039*73 birthCountry = pd.read_csv('postcodeSector/birthCountry.csv', skiprows=8) #8039*9 religion = pd.read_csv('postcodeSector/religion.csv', skiprows=8) #8063*12 generalHealth = pd.read_csv('postcodeSector/generalHealth.csv', skiprows=8) #8039*7 yearLastWorked = pd.read_csv('postcodeSector/yearLastWorked.csv', skiprows=8) #8039*13 householdSize = pd.read_csv('postcodeSector/householdSize.csv', skiprows=8) #8039*10 carOrVanAvailability = pd.read_csv('postcodeSector/carOrVanAvailability.csv', skiprows=8) #8039*7 distanceTravelledtoWork = pd.read_csv('postcodeSector/distanceTravelledtoWork.csv', skiprows=8) #8039*14 methodofTraveltoWork = pd.read_csv('postcodeSector/methodofTraveltoWork.csv', skiprows=8) #8039*14 ageofArrival = pd.read_csv('postcodeSector/ageofArrival.csv', skiprows=8) #8039*19 lengthofResidence = pd.read_csv('postcodeSector/lengthofResidence.csv', skiprows=8) #8039*7 occupationType = pd.read_csv('postcodeSector/occupation.csv', skiprows=8) #8039*11 mainLanguage = pd.read_csv('postcodeSector/mainLanguage.csv', skiprows=8) #8039*105 bedrooms = pd.read_csv('postcodeSector/bedrooms.csv', skiprows=8) #8039*8 longTermDisability = pd.read_csv('postcodeSector/longTermDisability.csv', skiprows=8) #8039*5 economicActivity = pd.read_csv('postcodeSector/economicActivity.csv', skiprows=8) #8039*17 positionInCommunalEstablishment = pd.read_csv('postcodeSector/positionInCommunalEstablishment.csv', skiprows=8) #8039*5 accomType = pd.read_csv('postcodeSector/accomType.csv', skiprows=8) #8039*13 secondAddress = pd.read_csv('postcodeSector/secondAddress.csv', skiprows=8) #8039*6 formerIndustry = pd.read_csv('postcodeSector/formerIndustry.csv', skiprows=8) #8039*11 formerOccupation = pd.read_csv('postcodeSector/formerOccupation.csv', skiprows=8) #8039*12 religion = religion.drop(religion.index[-24:]) # line added due to notes at bottom of CSV qualification = pd.read_csv('postcodeSector/qualification.csv', skiprows=8) #8039*14 # AS A PROPORTION ONLY # - # # Set up classification problem qualification.drop(qualification.columns[[1,2,3,4,5,7,8,9,10,11,12]], axis=1, inplace=True) qualification = qualification.rename(index=str, columns={"Highest level of qualification: Level 4 qualifications and above": "target"}) qualification.quantile(0.7) # Check to see where 70 percent quartile is to setup class imbalance # + # Assign a 1 or a zero as a output depending on whether proportion of people have, or don't have a higher education degree qualification['classification'] = np.where(qualification['target']>=35, 1, 0) #Check values = qualification.groupby('classification').count() values['perc']= values['target']/values['target'].sum() values # - ax = values.plot.bar(y = 'perc',rot=0, ) # # Combine datasets ###Merge different datasets newDF = [population, ethnicMinority, ageStructure, relationalSituation, livingArrangements, householdComposition,notInEmploymentDependencies,loneParentDependencies,ethnicGroup,industry,tenure, hoursWorked,dwelling,englishProf,centralHeating,passportHeld,birthCountry,religion,generalHealth,yearLastWorked,householdSize,carOrVanAvailability,distanceTravelledtoWork,methodofTraveltoWork,ageofArrival,lengthofResidence,occupationType,mainLanguage,bedrooms,longTermDisability,economicActivity,positionInCommunalEstablishment,accomType,secondAddress,formerIndustry,formerOccupation,qualification] newDF2 = pd.concat([i.set_index('postcode sector') for i in newDF],axis=1, join='outer') #Check for dimensions newDF2.shape #drop rows without any information newDF3 = newDF2.dropna() newDF3.shape #drop duplicate columns arising from merging... newDF4 = newDF3.T.drop_duplicates().T #remove spaces from variable names to allow access to columns newDF4.columns = newDF4.columns.map(lambda x: x.replace(' ', '_')) newDF4.shape y = newDF4.classification # # TWO COMPONENT GRAPHICAL REPRESENTATION # + #RUN LOOP OF ALL PARAMETERS start_time = timeit.default_timer() x = newDF4.drop(['target','classification'], axis=1) x = StandardScaler().fit_transform(x) #REDUCE DIMENSIONS pca = PCA(n_components=2) #FIT MODEL principalComponents = pca.fit_transform(x) principalDF = pd.DataFrame(data = principalComponents , columns = ['principal component 1', 'principal component 2']) principalDF.shape y = y.to_frame().reset_index() finalDF = y.join(principalDF) finalDF.columns = finalDF.columns.map(lambda x: x.replace(' ', '_')) finalDF.head() # + groups = finalDF.groupby('classification') # Plot fig, ax = plt.subplots() fig.set_size_inches(30, 30) for name, group in groups: ax.plot(group.principal_component_1, group.principal_component_2, marker='o', linestyle='', ms=8, label=name) ax.legend() ax.set_xlabel('Principal Component 1',fontsize=30) ax.set_ylabel('Principal Component 2', fontsize=30) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.legend(loc=4, prop={'size': 60}) plt.show() elapsed = timeit.default_timer() - start_time print("Time Elapsed:") print(elapsed) # - # # ONE COMPONENT GRAPHICAL REPRESENTATION finalDF = finalDF.replace(finalDF.principal_component_1.values, finalDF.classification.values) finalDF # + groups = finalDF.groupby('classification') # Plot fig, ax = plt.subplots() fig.set_size_inches(60, 10) for name, group in groups: ax.plot(group.principal_component_2, group.principal_component_1, marker='o', linestyle='', ms=30, label=name) ax.legend() ax.set_xlabel('Principal Component 1',fontsize=60) plt.legend(loc=4, prop={'size': 60}) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.show() # -
UDL Project/A5) PCA VISUALISATION 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 # --- # #Additional Question 1 Implementation # My first additional question is basically my base question but with my disrupting galaxy's mass being a third of the main galaxy's. # %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from initial_velocities import velocities_m, velocities_S from DE_solver import derivs, equationsolver # Defining empty initial condition array: ic_add1 = np.zeros(484) # Setting values for S,M, and t: max_time_add1 = 1.5 time_step_add1 = 120 M_add1 = 1e11 S_add1 = M_add1/3 S_y_add1 = 70 S_x_add1 = -.01*S_y_add1**2+25 vxS_add1 = velocities_S(M_add1,S_add1,S_x_add1,S_y_add1)[0] vyS_add1 = velocities_S(M_add1,S_add1,S_x_add1,S_y_add1)[1] # Setting initial condition array values pertaining to S: ic_add1[0] = S_x_add1 ic_add1[1] = S_y_add1 ic_add1[2] = vxS_add1 ic_add1[3] = vyS_add1 # Loading the positions of my stars: f = open('star_positions.npz','r') r = np.load('star_positions.npz') x_y = r['arr_0'] f.close() # Putting these values into my initial condition array, as well calling the initial velocity function on each position: for i in range(0,120): ic_add1[(i+1)*4] = x_y[0][i] ic_add1[((i+1)*4)+1] = x_y[1][i] for n in range(1,int(len(ic_add1)/4)): ic_add1[n*4+2] = velocities_m(M_add1,ic_add1[n*4],ic_add1[n*4+1])[0] ic_add1[n*4+3] = velocities_m(M_add1,ic_add1[n*4],ic_add1[n*4+1])[1] # Calling my differential equation solver, and saving the data to disk: # # ####Took 1 min and 7 sec last I timed it sol_add1 = equationsolver(ic_add1,max_time_add1,time_step_add1,M_add1,S_add1) np.savez('additional_1_data.npz',sol_add1,ic_add1)
galaxy_project/Ja) Additional Question 1 Implementation.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/akashstarxs/examples/blob/master/image_classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="cHL5oenDwIzP" colab_type="code" colab={} import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt # + id="tjYxncxuwSdv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 162} outputId="9d036532-f998-460e-df9f-b45be157b14b" fashion_mnist=keras.datasets.fashion_mnist (train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data() # + id="SpBRQ42CxZql" colab_type="code" colab={} class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # + id="DuQCurqywZxo" colab_type="code" outputId="ac4ec439-24b5-461d-b135-3d9179464b1c" colab={"base_uri": "https://localhost:8080/", "height": 265} plt.figure() plt.imshow(train_images[0]) plt.colorbar() plt.grid() plt.show() # + id="XUGjOblBwdYS" colab_type="code" colab={} train_images=train_images/255.0 test_images=test_images/255.0 # + id="YBLyKBeawhhi" colab_type="code" outputId="eb76a61e-8750-4109-cf78-245c2f8b1b24" colab={"base_uri": "https://localhost:8080/", "height": 589} plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i],cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[i]]) plt.show() # + id="Q7XJNFVExdGF" colab_type="code" colab={} model=keras.Sequential([ keras.layers.Flatten(input_shape=(28,28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10) ]) # + id="tTwtxssI5bZQ" colab_type="code" colab={} model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # + id="cwvcp-3BEYiA" colab_type="code" outputId="d25ac778-bde1-4fc0-dbc8-9fbf60161983" colab={"base_uri": "https://localhost:8080/", "height": 399} model.fit(train_images,train_labels,epochs=10) # + id="7F2aBKLZE6Hu" colab_type="code" outputId="c274c6af-dccb-4500-fce5-5a20f18596a6" colab={"base_uri": "https://localhost:8080/", "height": 35} test_loss,test_acc=model.evaluate(test_images,test_labels,verbose=2) # + id="9IR2v_pqFn0w" colab_type="code" colab={} probablity_model=tf.keras.Sequential([model, tf.keras.layers.Softmax()]) # + id="CaNBNr7FGBcj" colab_type="code" colab={} predictions=probablity_model.predict(test_images) # + id="2qqV2cooGSmX" colab_type="code" outputId="e21cf0a5-a232-45ae-bba6-a67a95be3368" colab={"base_uri": "https://localhost:8080/", "height": 72} predictions[0] # + id="Ykl9tE19GblD" colab_type="code" outputId="146566a2-d2aa-4afb-f96a-e2901f776c79" colab={"base_uri": "https://localhost:8080/", "height": 35} np.argmax(predictions[0]) # + id="3Lnztd6zGirl" colab_type="code" colab={} def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array, true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array, true_label[i] plt.grid(False) plt.xticks(range(10)) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') # + id="irz6pznRYCJo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 243} outputId="d0527044-73ba-4ae4-cc23-ddb5f421628c" i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions[i], test_labels) plt.show() # + id="mHIB6cxfYE9Y" colab_type="code" colab={} i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions[i], test_labels) plt.show() # + id="pHtW4y69YIko" colab_type="code" colab={} num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions[i], test_labels, test_images) plt.subplot(num_rows, 2*num_cols, 2*i+2) plot_value_array(i, predictions[i], test_labels) plt.tight_layout() plt.show() # + id="u6FepSayYMt_" colab_type="code" colab={} # Grab an image from the test dataset. img = test_images[1] print(img.shape) # + id="gVIIivrnYVCX" colab_type="code" colab={} # Add the image to a batch where it's the only member. img = (np.expand_dims(img,0)) print(img.shape) # + id="-CaynGjgYW8a" colab_type="code" colab={} predictions_single = probability_model.predict(img) print(predictions_single) # + id="mDLNqrduYbjv" colab_type="code" colab={} plot_value_array(1, predictions_single[0], test_labels) _ = plt.xticks(range(10), class_names, rotation=45) # + id="Cwk4uub8Ydsx" colab_type="code" colab={} np.argmax(predictions_single[0])
image_classification.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 # --- # # Processor temperature # # We have a temperature sensor in the processor of our company's server. We want to analyze the data provided to determinate whether we should change the cooling system for a better one. It is expensive and as a data analyst we cannot make decisions without a basis. # # We provide the temperatures measured throughout the 24 hours of a day in a list-type data structure composed of 24 integers: # ``` # temperatures_C = [33,66,65,0,59,60,62,64,70,76,80,69,80,83,68,79,61,53,50,49,53,48,45,39] # ``` # # ## Goals # # 1. Treatment of lists # 2. Use of loop or list comprenhention # 3. Calculation of the mean, minimum and maximum. # 4. Filtering of lists. # 5. Interpolate an outlier. # 6. Logical operators. # 7. Print # ## Temperature graph # To facilitate understanding, the temperature graph is shown below. You do not have to do anything in this section. The test starts in **Problem**. # + # import import matplotlib.pyplot as plt # %matplotlib inline # axis x, axis y y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39] x = list(range(len(y))) # plot plt.plot(x, y) plt.axhline(y=70, linewidth=1, color='r') plt.xlabel('hours') plt.ylabel('Temperature ยบC') plt.title('Temperatures of our server throughout the day') # - # ## Problem # # If the sensor detects more than 4 hours with temperatures greater than or equal to 70ยบC or any temperature above 80ยบC or the average exceeds 65ยบC throughout the day, we must give the order to change the cooling system to avoid damaging the processor. # # We will guide you step by step so you can make the decision by calculating some intermediate steps: # # 1. Minimum temperature # 2. Maximum temperature # 3. Temperatures equal to or greater than 70ยบC # 4. Average temperatures throughout the day. # 5. If there was a sensor failure at 03:00 and we did not capture the data, how would you estimate the value that we lack? Correct that value in the list of temperatures. # 6. Bonus: Our maintenance staff is from the United States and does not understand the international metric system. Pass temperatures to Degrees Fahrenheit. # # Formula: F = 1.8 * C + 32 # # web: https://en.wikipedia.org/wiki/Conversion_of_units_of_temperature # # + # assign a variable to the list of temperatures # 1. Calculate the minimum of the list and print the value using print() # 2. Calculate the maximum of the list and print the value using print() # 3. Items in the list that are greater than 70ยบC and print the result # 4. Calculate the mean temperature throughout the day and print the result # 5.1 Solve the fault in the sensor by estimating a value # 5.2 Update of the estimated value at 03:00 on the list # Bonus: convert the list of ยบC to ยบFarenheit # - # ## Take the decision # Remember that if the sensor detects more than 4 hours with temperatures greater than or equal to 70ยบC or any temperature higher than 80ยบC or the average was higher than 65ยบC throughout the day, we must give the order to change the cooling system to avoid the danger of damaging the equipment: # * more than 4 hours with temperatures greater than or equal to 70ยบC # * some temperature higher than 80ยบC # * average was higher than 65ยบC throughout the day # If any of these three is met, the cooling system must be changed. # # + # Print True or False depending on whether you would change the cooling system or not # - # ## Future improvements # 1. We want the hours (not the temperatures) whose temperature exceeds 70ยบC # 2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set. Is this condition met? # 3. Average of each of the lists (ยบC and ยบF). How they relate? # 4. Standard deviation of each of the lists. How they relate? # # + # 1. We want the hours (not the temperatures) whose temperature exceeds 70ยบC # + # 2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set. Is this condition met? # + # 3. Average of each of the lists (ยบC and ยบF). How they relate? # + # 4. Standard deviation of each of the lists. How they relate? # -
temperature/temperature.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] colab_type="text" id="NaZJVtw1iyEU" # # ะ“ะตะฝะตั€ะฐั‚ะพั€ั‹ ะธ ะปะตะฝะธะฒั‹ะต ะฒั‹ั‡ะธัะปะตะฝะธั # + [markdown] colab_type="text" id="URnSv8ibiyEW" # ะ’ Python ะฟั€ะพัั‚ะพ **ะณะตะฝะตั€ะฐั‚ะพั€ั‹** (*generator*) ะธ **ะณะตะฝะตั€ะฐั‚ะพั€ั‹ ัะฟะธัะบะพะฒ** (*list comprehension*) - ั€ะฐะทะฝั‹ะต ะฒะตั‰ะธ. ะ ะฐััะผะพั‚ั€ะธะผ ะธ ั‚ะพ, ะธ ะดั€ัƒะณะพะต. # + [markdown] colab_type="text" id="rgiQ3Or1iyEW" # ## ะ“ะตะฝะตั€ะฐั‚ะพั€ั‹ ัะฟะธัะบะพะฒ # # ะ’ Python ะณะตะฝะตั€ะฐั‚ะพั€ั‹ ัะฟะธัะบะพะฒ ะฟะพะทะฒะพะปััŽั‚ ัะพะทะดะฐะฒะฐั‚ัŒ ะธ ะฑั‹ัั‚ั€ะพ ะทะฐะฟะพะปะฝัั‚ัŒ ัะฟะธัะบะธ. # # ะกะธะฝั‚ะฐะบัะธั‡ะตัะบะฐั ะบะพะฝัั‚ั€ัƒะบั†ะธั ะณะตะฝะตั€ะฐั‚ะพั€ะฐ ัะฟะธัะบะฐ ะฟั€ะตะดะฟะพะปะฐะณะฐะตั‚ ะฝะฐะปะธั‡ะธะต ะธั‚ะตั€ะธั€ัƒะตะผะพะณะพ ะพะฑัŠะตะบั‚ะฐ ะธะปะธ ะธั‚ะตั€ะฐั‚ะพั€ะฐ, ะฝะฐ ะฑะฐะทะต ะบะพั‚ะพั€ะพะณะพ ะฑัƒะดะตั‚ ัะพะทะดะฐะฒะฐั‚ัŒัั ะฝะพะฒั‹ะน ัะฟะธัะพะบ, ะฐ ั‚ะฐะบะถะต ะฒั‹ั€ะฐะถะตะฝะธะต, ะบะพั‚ะพั€ะพะต ะฑัƒะดะตั‚ ั‡ั‚ะพ-ั‚ะพ ะดะตะปะฐั‚ัŒ ั ะธะทะฒะปะตั‡ะตะฝะฝั‹ะผะธ ะธะท ะฟะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพัั‚ะธ ัะปะตะผะตะฝั‚ะฐะผะธ ะฟะตั€ะตะด ั‚ะตะผ ะบะฐะบ ะดะพะฑะฐะฒะธั‚ัŒ ะธั… ะฒ ั„ะพั€ะผะธั€ัƒะตะผั‹ะน ัะฟะธัะพะบ. # + colab={} colab_type="code" id="CvKmmPBSiyEX" outputId="2cd4db93-40f2-4608-8cab-157acb5cbc15" a = [1, 2, 3] b = [i+10 for i in a] print(a) print(b) # + [markdown] colab_type="text" id="shNzUj_6iyEa" # ะ—ะดะตััŒ ะณะตะฝะตั€ะฐั‚ะพั€ะพะผ ัะฟะธัะบะฐ ัะฒะปัะตั‚ัั ะฒั‹ั€ะฐะถะตะฝะธะต `[i+10 for i in a]`. # # `a` - ะธั‚ะตั€ะธั€ัƒะตะผั‹ะน ะพะฑัŠะตะบั‚. ะ’ ะดะฐะฝะฝะพะผ ัะปัƒั‡ะฐะต ัั‚ะพ ะดั€ัƒะณะพะน ัะฟะธัะพะบ.\ # ะ˜ะท ะฝะตะณะพ ะธะทะฒะปะตะบะฐะตั‚ัั ะบะฐะถะดั‹ะน ัะปะตะผะตะฝั‚ ะฒ ั†ะธะบะปะต for.\ # ะŸะตั€ะตะด for ะพะฟะธัั‹ะฒะฐะตั‚ัั ะดะตะนัั‚ะฒะธะต, ะบะพั‚ะพั€ะพะต ะฒั‹ะฟะพะปะฝัะตั‚ัั ะฝะฐะด ัะปะตะผะตะฝั‚ะพะผ ะฟะตั€ะตะด ะตะณะพ ะดะพะฑะฐะฒะปะตะฝะธะตะผ ะฒ ะฝะพะฒั‹ะน ัะฟะธัะพะบ. # # ะ’ ะณะตะฝะตั€ะฐั‚ะพั€ ัะฟะธัะบะฐ ะผะพะถะฝะพ ะดะพะฑะฐะฒะธั‚ัŒ ัƒัะปะพะฒะธะต: # + colab={} colab_type="code" id="NcnulnksiyEa" outputId="a9986a0d-4aef-46ec-8e66-1f2859e0ee03" from random import randint nums = [randint(10, 20) for i in range(10)] print(nums) nums = [i for i in nums if i%2 == 0] print(nums) # + [markdown] colab_type="text" id="X1XwV-J7iyEc" # ะ“ะตะฝะตั€ะฐั‚ะพั€ั‹ ัะฟะธัะบะพะฒ ะผะพะณัƒั‚ ัะพะดะตั€ะถะฐั‚ัŒ ะฒะปะพะถะตะฝะฝั‹ะต ั†ะธะบะปั‹: # + colab={} colab_type="code" id="HzA3ylUwiyEc" outputId="a4965705-89c2-4d50-f955-99f6ffdf779c" a = "12" b = "3" c = "456" comb = [i+j+k for i in a for j in b for k in c] print(comb) # + [markdown] colab_type="text" id="3Zr4QTCaiyEe" # ### ะ“ะตะฝะตั€ะฐั‚ะพั€ั‹ ัะปะพะฒะฐั€ะตะน ะธ ะผะฝะพะถะตัั‚ะฒ # # ะ•ัะปะธ ะฒ ะฒั‹ั€ะฐะถะตะฝะธะธ ะณะตะฝะตั€ะฐั‚ะพั€ะฐ ัะฟะธัะบะฐ ะทะฐะผะตะฝะธั‚ัŒ ะบะฒะฐะดั€ะฐั‚ะฝั‹ะต ัะบะพะฑะบะธ ะฝะฐ ั„ะธะณัƒั€ะฝั‹ะต, ั‚ะพ ะผะพะถะฝะพ ะฟะพะปัƒั‡ะธั‚ัŒ ะฝะต ัะฟะธัะพะบ, ะฐ ัะปะพะฒะฐั€ัŒ. # # ะŸั€ะธ ัั‚ะพะผ ัะธะฝั‚ะฐะบัะธั ะฒั‹ั€ะฐะถะตะฝะธั ะดะพ `for` ะดะพะปะถะตะฝ ะฑั‹ั‚ัŒ ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะน ัะปะพะฒะฐั€ัŽ, ั‚ะพ ะตัั‚ัŒ ะฒะบะปัŽั‡ะฐั‚ัŒ ะบะปัŽั‡ ะธ ั‡ะตั€ะตะท ะดะฒะพะตั‚ะพั‡ะธะต ะทะฝะฐั‡ะตะฝะธะต. ะ•ัะปะธ ัั‚ะพะณะพ ะฝะตั‚, ะฑัƒะดะตั‚ ัะณะตะฝะตั€ะธั€ะพะฒะฐะฝะพ ะผะฝะพะถะตัั‚ะฒะพ. # + colab={} colab_type="code" id="oWBWe1xHiyEf" outputId="8c81f542-9f5b-44aa-f093-e0d80dcaeea6" a = {i:i**2 for i in range(11,15)} print(a) a = {i for i in range(11,15)} print(a) b = {1, 2, 3} print(b) # + [markdown] colab_type="text" id="Y2a4aMApozEg" # ะŸั€ะธะผะตั‡ะฐะฝะธะต: # # ะ’ Python3 ะฒ ัะปะพะฒะฐั€ัั… ะฟั€ะธ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธะธ ะผะตั‚ะพะดะฐ `.keys()`, `.values()` ะธ `.items()` ะดะปั ะดะพัั‚ัƒะฟะฐ ะบ ะบะปัŽั‡ะฐะผ ะธ ะทะฝะฐั‡ะตะฝะธัะผ ัะพะทะดะฐั‘ั‚ัั ะฟั€ะตะดัั‚ะฐะฒะปะตะฝะธะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะตะณะพ ัะปะตะผะตะฝั‚ะฐ. ะŸะพ ััƒั‚ะธ ัั‚ะพ ะฟั€ะตะดัั‚ะฐะฒะปะตะฝะธะต ัะฒะปัะตั‚ัั ะณะตะฝะตั€ะฐั‚ะพั€ะพะผ. ะšะพะฟะธั ะดะฐะฝะฝั‹ั… ะฝะต ัะพะทะดะฐั‘ั‚ัั. # # ะขะธะฟ ัั‚ะธั… ะดะฐะฝะฝั‹ั… - dict_keys, dict_values, dict_items. # + colab={} colab_type="code" id="rfH857mspGyQ" my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} print(my_dict.keys()) print(my_dict.values()) print(my_dict.items()) # + [markdown] colab_type="text" id="yx5_ThfQiyEg" # ## ะ“ะตะฝะตั€ะฐั‚ะพั€ั‹ # # ะ›ะตะฝะธะฒั‹ะต ะฒั‹ั‡ะธัะปะตะฝะธั - ัั‚ั€ะฐั‚ะตะณะธั ะฒั‹ั‡ะธัะปะตะฝะธั, ัะพะณะปะฐัะฝะพ ะบะพั‚ะพั€ะพะน ะฒั‹ั‡ะธัะปะตะฝะธั ัะปะตะดัƒะตั‚ ะพั‚ะบะปะฐะดั‹ะฒะฐั‚ัŒ ะดะพ ั‚ะตั… ะฟะพั€, ะฟะพะบะฐ ะฝะต ะฟะพะฝะฐะดะพะฑะธั‚ัั ะธั… ั€ะตะทัƒะปัŒั‚ะฐั‚. ะ”ะปั ะปะตะฝะธะฒั‹ั… ะฒั‹ั‡ะธัะปะตะฝะธะน ะฝะฐะผ ะฟะพั‚ั€ะตะฑัƒัŽั‚ัั ะณะตะฝะตั€ะฐั‚ะพั€ั‹. # # ะ’ั‹ั€ะฐะถะตะฝะธั, ัะพะทะดะฐัŽั‰ะธะต ะพะฑัŠะตะบั‚ั‹-ะณะตะฝะตั€ะฐั‚ะพั€ั‹, ะฟะพั…ะพะถะธ ะฝะฐ ะฒั‹ั€ะฐะถะตะฝะธั, ะณะตะฝะตั€ะธั€ัƒัŽั‰ะธะต ัะฟะธัะบะธ. ะงั‚ะพะฑั‹ ัะพะทะดะฐั‚ัŒ ะณะตะฝะตั€ะฐั‚ะพั€ะฝั‹ะน ะพะฑัŠะตะบั‚, ะฝะฐะดะพ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ะบั€ัƒะณะปั‹ะต ัะบะพะฑะบะธ. # + colab={"base_uri": "https://localhost:8080/", "height": 136} colab_type="code" executionInfo={"elapsed": 1438, "status": "ok", "timestamp": 1574937028745, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="fromjY0ajnqX" outputId="4007a616-d710-4dc1-d3e5-1fecafbe3eb2" a = (i for i in range(2, 8)) print(a) for i in a: print(i) print(a) print(type(a)) for i in a: print(i) # + [markdown] colab_type="text" id="XWMxc70Cknuh" # ะ’ั‚ะพั€ะพะน ั€ะฐะท ะฟะตั€ะตะฑั€ะฐั‚ัŒ ะณะตะฝะตั€ะฐั‚ะพั€ ะฒ ั†ะธะบะปะต for ะฝะต ะฟะพะปัƒั‡ะธั‚ัั, ั‚ะฐะบ ะบะฐะบ ะพะฑัŠะตะบั‚-ะณะตะฝะตั€ะฐั‚ะพั€ ัƒะถะต ัะณะตะฝะตั€ะธั€ะพะฒะฐะป ะฒัะต ะทะฝะฐั‡ะตะฝะธั ะฟะพ ะทะฐะปะพะถะตะฝะฝะพะน ะฒ ะฝะตะณะพ "ั„ะพั€ะผัƒะปะต". ะŸะพัั‚ะพะผัƒ ะณะตะฝะตั€ะฐั‚ะพั€ั‹ ะพะฑั‹ั‡ะฝะพ ะธัะฟะพะปัŒะทัƒัŽั‚ัั, ะบะพะณะดะฐ ะฝะฐะดะพ ะตะดะธะฝะพะถะดั‹ ะฟั€ะพะนั‚ะธััŒ ะฟะพ ะธั‚ะตั€ะธั€ัƒะตะผะพะผัƒ ะพะฑัŠะตะบั‚ัƒ. # # ะšั€ะพะผะต ั‚ะพะณะพ, ะณะตะฝะตั€ะฐั‚ะพั€ั‹ ัะบะพะฝะพะผัั‚ ะฟะฐะผัั‚ัŒ, ั‚ะฐะบ ะบะฐะบ ะฒ ะฝะตะน ั…ั€ะฐะฝัั‚ัั ะฝะต ะฒัะต ะทะฝะฐั‡ะตะฝะธั, ัะบะฐะถะตะผ, ะฑะพะปัŒัˆะพะณะพ ัะฟะธัะบะฐ, ะฐ ั‚ะพะปัŒะบะพ ะฟั€ะตะดั‹ะดัƒั‰ะธะน ัะปะตะผะตะฝั‚, ะฟั€ะตะดะตะป ะธ ั„ะพั€ะผัƒะปะฐ, ะฟะพ ะบะพั‚ะพั€ะพะน ะฒั‹ั‡ะธัะปัะตั‚ัั ัะปะตะดัƒัŽั‰ะธะน ัะปะตะผะตะฝั‚. # # ะ’ั‹ั€ะฐะถะตะฝะธะต, ัะพะทะดะฐัŽั‰ะตะต ะณะตะฝะตั€ะฐั‚ะพั€, ัั‚ะพ ัะพะบั€ะฐั‰ะตะฝะฝะฐั ะทะฐะฟะธััŒ ัะปะตะดัƒัŽั‰ะตะณะพ: # # # + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" executionInfo={"elapsed": 1136, "status": "ok", "timestamp": 1574937260584, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="49M-KQKckqS0" outputId="776c2c3a-ddfc-4e8e-b0f7-7f3bebb64784" def func(start, finish): while start < finish: yield start * 0.33 start += 1 a = func(1, 4) print(a) for i in a: print(i) # + [markdown] colab_type="text" id="XWinvS2JlGnf" # ะคัƒะฝะบั†ะธั, ัะพะดะตั€ะถะฐั‰ะฐั `yield`, ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ ะพะฑัŠะตะบั‚-ะณะตะฝะตั€ะฐั‚ะพั€, ะฐ ะฝะต ะฒั‹ะฟะพะปะฝัะตั‚ ัะฒะพะน ะบะพะด ัั€ะฐะทัƒ. ะขะตะปะพ ั„ัƒะฝะบั†ะธะธ ะธัะฟะพะปะฝัะตั‚ัั ะฟั€ะธ ะบะฐะถะดะพะผ ะฒั‹ะทะพะฒะต ะผะตั‚ะพะดะฐ `__next__()`. ะ’ ั†ะธะบะปะต for ัั‚ะพ ะดะตะปะฐะตั‚ัั ะฐะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธ. # # ะŸั€ะธ ัั‚ะพะผ ะฟะพัะปะต ะฒั‹ะดะฐั‡ะธ ั€ะตะทัƒะปัŒั‚ะฐั‚ะฐ ะบะพะผะฐะฝะดะพะน yield ัะพัั‚ะพัะฝะธะต ะณะตะฝะตั€ะฐั‚ะพั€ะฐ, ะฒัะต ะตะณะพ ะฒะฝัƒั‚ั€ะตะฝะฝะธะต ะฟะตั€ะตะผะตะฝะฝั‹ะต ัะพั…ั€ะฐะฝััŽั‚ัั. ะŸั€ะธ ัะปะตะดัƒัŽั‰ะตะน ะฟะพะฟั‹ั‚ะบะต ะฒั‹ะดะตั€ะฝัƒั‚ัŒ ัะปะตะผะตะฝั‚ ะธะท ะณะตะฝะตั€ะฐั‚ะพั€ะฐ ั€ะฐะฑะพั‚ะฐ ะฝะฐั‡ะฝั‘ั‚ัั ัะพ ัั‚ั€ะพั‡ะบะธ, ัะปะตะดัƒัŽั‰ะตะน ะทะฐ yield. # + [markdown] colab_type="text" id="EIQZJ2xxld2T" # ะŸั€ะธะผะตั€ ะณะตะฝะตั€ะฐั‚ะพั€ะฐ ั‡ะธัะตะป ะคะธะฑะพะฝะฐั‡ั‡ะธ: # + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" executionInfo={"elapsed": 1351, "status": "ok", "timestamp": 1574937601981, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="oMYZrqnwlghq" outputId="e2c7a252-b05d-48be-a517-1af853e8a6ac" def fibonacci(n): fib1, fib2 = 0, 1 for i in range(n): fib1, fib2 = fib2, fib1 + fib2 yield fib1 for fib in fibonacci(20): print(fib) print('ะกัƒะผะผะฐ ะฟะตั€ะฒั‹ั… 100 ั‡ะธัะตะป ะคะธะฑะพะฝะฐั‡ั‡ะธ ั€ะฐะฒะฝะฐ', sum(fibonacci(100))) print(fibonacci(16)) print([x*x for x in fibonacci(14)]) # -
lecture_2/06. Generators.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Markov Decision Process and Dynamic Programming # # > A notebook that helps us to discover Reinforcement Learning # - toc: true # - branch: master # - badges: true # - comments: true # - metadata_key1: metadata_value1 # - metadata_key2: metadata_value2 # - image: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQChSoDYsSnyFzrYnjJXEA6d5-kRELW-lzYcA&usqp=CAU # - description: Second in a series on understanding Reinforcement Learning. # # Preliminaries # - Markov property: a process is Markov if the future is independent on the past given the present. # - State transition # $$ # p(s'|s,a)= \sum _r p(s',r|s,a) # $$ # - Expected reward # $$ # r(s,a) = \mathbb{E} [R|s,a] = \sum _r r \sum _{s'} p(r,s'|s,a) # $$ # # Markov Decision Processes (MDP) # MDPs are a classical formulations of sequential decision making, where each action influences not only immediate rewards, but also subsequent situations, or states and through those future rewards. Thus MDPs involve delayed reward and the need to trade-off immediate reward and delay reward. # # In bandit problems, we estimated the value $q_*(a)$ of each action a. In MDP, we estimate the value $q_*(s,a)$ of each action a in each state s, or we estimate the value $v_*(s)$ of each state given optimal action selections. These states dependent quantities are essential to accurately assign credit for long term consequences to individual action selections. # # MDPs are meant to be a straight forward framing of problem of learningfrom interaction to achieve a goal. The learner and decision maker is called the <i>agent. </i> The thing it interacts with, comprising everything outside the agent, is called <i>environment. </i> These interact continually, the agent selecting actions and the environment responding to these actions and presenting new situations to the agent. The environment also gives rise to rewards through choice of actions. # ![](https://miro.medium.com/max/1838/1*ywOrdJAHgSL5RP-AuxsfJQ.png) # A state s has the Markov property when for states $\forall s' \in \mathcal{S} $ and all reward $r \in \mathbb{R}$ # $$ # p(R_{t+1}=r, S_{t+1}=s' | S_t=s) = p(R_{t+1}=r, S_{t+1}=s' | S_1,...,S_{t-1},S_t=s) # $$ # Then, the distribution of the reward and the next state when we condition only the current state is the same as we would conditional all previous states. So, if we know all the previous states, this give us no additional information about what the next state and reward would be. It means that we just need to look at the current state. # # $p(r,s'|s,a)$ is the joint probability of a reward r and next state s' if we are at the state s and action a has been taken. # In a finite MDP, the sets of state, actions and rewards ($\mathcal{S}, \mathcal{A},\mathcal{R} $) all have a finite number of element. The funtion <i>p </i> gives the dynamics of MDPs and $\gamma \in [0,1]$ is a discount factor that trades off later rewards. # Then, a MDP is a tuple of $(\mathcal{S}, \mathcal{A},\mathcal{R}, p, \gamma)$. # Acting in a MDP results in returns $G_t$: total discounted reward from time-step t. # $$ # G_t = R_{t+1} + \gamma R_{t+2} + ... = \sum _{k=0} ^\infty \gamma^k R_{t+k+1} # $$ # In principle, $G_t$ is a random variables that depends on MDP and policy. # ## Polices and Value functions # Almost all reinforcement learning algorithms ilvolve estimating value functions - functions fo states (or of state-action pairs) that estimate how good it is for the agent to be in a given state (or how good it is to perform a given action in a given state). The rewards that the agent can expect to receive in the future depend on what action it will takes. Accordingly, value function are defined with respect to particular ways of acting, called <i>policy. </i> # Formally, policy maps states to probabilities of selecting each possible action. If the agent follows policy $\pi$ at time t, then $\pi(a|s)$ is the probability that $A_t=a$ if $S_t=s.$ # Recalling that the value function of a state s under policy $\pi$, $v_\pi(s)$ is the expected return when starting in state s and following $\pi$ thereafter. # $$ # v_\pi(s)= \mathbb{E}_\pi [G_t | S_t=s] = \mathbb{E}_\pi [\sum_k \gamma ^k R_{t+k+1} | S_t=s] \\\\ # =\mathbb{E}_\pi [ R_{t+1} + \gamma G_{t+1} | S_t=s, \pi] \\\\ # = \mathbb{E}_\pi [ R_{t+1} + \gamma v_\pi (S_{t+1}) | S_t=s, A_t \sim \pi(S_t)] \\\\ # = \sum _a \pi(a|s) \sum _r \sum _{s'} p(r,s'|s,a)(r+\gamma v_\pi(s')) # $$ # This recursive equation is the <i>Bellman equation </i> for $v_\pi$. It expresses a relatioship between the value of a state and the values of its successor states. It also staes that the value of the start state must equal the discounted value of the expected next state, plus the reward expected along the way. # The same principle is applied for state-action value. # $$ # q_\pi(s,a) = \mathbb{E} [G_t | S_t=s, A_t=a,\pi] # $$ # # It implies that: # $$ # q_\pi(s,a) = \mathbb{E}_\pi [ R_{t+1} + \gamma G_{t+1} | S_t=s, A_t=a] \\\\ # = \mathbb{E}_\pi [ R_{t+1} + \gamma q_\pi (S_{t+1},A_{t+1}) | S_t=s, A_t=a] \\\\ # = \sum _r \sum _{s'} p(r,s'|s,a)(r+\gamma \sum_{a'}\pi(a'|s')q_\pi(s',a')) # $$ # Then, the relationship between action value and state-action value can be represented: # # $$ # v_\pi(s) = \sum _a \pi(a|s) q_\pi (s,a) = \mathbb{E} [q_\pi (s,a) | S_t=s, \pi] # $$ # The value of a state equal to the weighted sum of state-action values. # IF we represent the Bellman Equation in the matrix form, we can see that it is a linear equation form that can be solved directly. # $$ # v= r+ \gamma P^\pi v \\\\ # = (I-\gamma P^ \pi)^{-1}r # $$ # So, if we know the transition matrix, discount factor and reward vector, we can just compute the value function as the solution of the Bellman's Equation. However, it is burdensome to make it in reality if we care about a hugh system with millions of states. # By using other iterative method such as Dynamic Programming, Monte Carlo Evaluation and Temporal Difference Learning, we can have another method to solve Bellman Equation. # ### Optimal Value Function # Solving a reinforcement learning task means finding a policy that achieves a lot of rewards over the long run or optimal policy. # The optimal state value $v_*(s)$ is the maximum value function over all policies # $$ # v_*(s) = \max _ \pi v^\pi(s) # $$ # The optimal action value function $q_*(s,a)$ is the maximum action-value function over all policies. # $$ # q_*(s,a) = \max _\pi q^\pi(s,a) # $$ # These optimal values give us what the best possible performance that we can get in a problem. MDP can be considered as solved when we can find these values. # Estimating the value of certain policy either using state value of action value is called Policy evaluation or prediction because we are are making a prediction what about happens when we follow certain policy. # Estimating their optimal values is called control because it can be used for policy optimization. # Once we can get $v_*$, it is relatively easy to determine optimal policy. For each state s, there will be one or more actions at which the maximum is obtained in the Bellman optimality equation. Any policy that assign non probability only to these actions is an optimal policy. It is related to one step search because the action appears best after a one-step search is the optimal actions. # The beauty of $v_*$ is that if one uses it to evaluate the short-term consequences of actions, then a greedy policy is actually optimal in the long term sense because $v_*$ already takes into iaccount the rewards of all possible future behaviours. # Having the $q_*$ make choosing the optimal actions easier because the agent does not have to do one-step ahead search, for any state s, it can simply find any action that maximizes $q_*(s,a)$. Hence, at the cost of representing a function of state-action pairs, insteads of the state, the optimal action-value function allows optimal action to be selected without having to know everything about possible successor states and their values (environment's dynamic) . # There are equivalences between state and action values: # $$ # v_\pi(s) = \sum _a \pi(a|s) q_\pi(s,a) # $$ # # $$ # v_*(s) = \max _a q_*(s,a) # $$ # In order to solve the Bellman Optimality Equation, because it is non linear (contain max operator) so we can not use the same matrix solution as for policy evaluation. So we will use iterative methods to deal with that. # If we use a model, it is called Dynamic Programming to get into the optimal policy. # If it is based on sample, we can use Monte Carlo, Q-learning and SARSA. # # Dynamic Programming # <b> By definition, Dynamic Programming (DP) refers to a collection of algorithms that can be used to compute optimal polices given a perfect model of the environment as a MDP. </b> # ## Policy evaluation (Prediction) # It refers to how to compute the state-value function $v_\pi$ for a policy $\pi$. # $$ # v_\pi(s) = \mathbb{E} [R_{t+1} + \gamma v_ \pi(S_{t+1}) | s, \pi] # $$ # The basic idea is to initialize the first guess to zero for all the possible states and then we are going to iterate this equation, we are going to assign values which is subscripted as k to indicate that it is an estimate at that time. The way we assign is based on the expectation of one-step ahead relying on true model and we are going to boostrap at the value of iteration k at the next state, and we will use that to find new values at k+1. # # Here, the bootstraping means we use the estimate at time k to estimate the value at time k+1. # $$ # v_{k+1} (s) = \mathbb{E}[R_{t+1} + \gamma v_k(S_{t+1}) | s, \pi] # $$ # Whenever $v_{k+1}(s) = v_k(s)$, then we must found $v_\pi$. # ## Policy improvement # By doing policy evaluation, we can evaluate the state value under the policy $\pi$. By doing that, we know how good it is to follow the current policy by choosing a particular action. However, we do not know it is better or worst to change to a new policy or not because another policy can have better value function (better policy). # # Let's consider the action value: # $$ # q_\pi(s,a) = \mathbb{E} [R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s, A_t=a] \\\\ # = \sum _{s',r} p(s',r|s,a)[r+\gamma v_\pi(s')] # $$ # By picking the greedy action according to action values, we can examine if it is better to change a policy or not. # $$ # \pi_{new}(s) = \argmax_{a} q_\pi(s,a) \\\\ # = \argmax _a \mathbb{E} [r_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s, A_t=a] # $$ # The decide of picking a new policy depends on the greedy action value according to policies. # In priciple, we can repeat these processes to change the policy to a better one and re-evaluate the value function, perform the policy improvement and so on. # By doing that, we can continually evaluate value function and improve our policy to a better ones until the value of new policy is the same as the old one, then the new policy should be the optimal one. # ![](https://miro.medium.com/max/1034/1*ilt4JYda72oe9Eit6KnHwg.png) # These processes are called <i> Policy Iteration </i>. Policy Iteration comprises 2 alternative processes which are policy evaluation and policy improvement. # # ## Value Iteration # One draw back of the policy iteration is that its policy evaluation requires multiple sweeps through the state set and we do need to compute the state values of the policy we are considering at that time. Basically, it is the inner loop to calculate the value function of current policy itself and we have the outer loop for the policy imprvoment. # In principle, we can truncate the policy evaluation step into several ways without losing the convergences guarantees of policy iteration. One special case us when policy evaluation is stopped every iteration. This algorithm is called <i>value iteration. </i> # We can turn the Bellman optimality equation into an update. # $$ # v_{k+1}(s) \leftarrow \max _a \mathbb{E} [R_{t+1} + \gamma v_k(S_{t+1}) | S_t=s, A_t=a] # $$ # This is equivalent to policy iteration, with k=1 step of policy evaluation between each two policy improvement steps. # ## Bootstraping in Dynamic Programming # Dynamic programming improves the estimates of the value at a state using the estimate of the value function at next states, it is sometimes called learning a guess from a guess and it is a core idea in Reinforcement Learning (bootstraping). #
_notebooks/2020-06-14-MDP_DP.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 # --- # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" papermill={"duration": 0.02519, "end_time": "2020-10-10T14:43:30.921892", "exception": false, "start_time": "2020-10-10T14:43:30.896702", "status": "completed"} tags=[] # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session # + papermill={"duration": 55.590022, "end_time": "2020-10-10T14:44:26.525077", "exception": false, "start_time": "2020-10-10T14:43:30.935055", "status": "completed"} tags=[] # !pip install ktrain # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" papermill={"duration": 12.302493, "end_time": "2020-10-10T14:44:38.927422", "exception": false, "start_time": "2020-10-10T14:44:26.624929", "status": "completed"} tags=[] from ktrain import text # + papermill={"duration": 67.334866, "end_time": "2020-10-10T14:45:46.373265", "exception": false, "start_time": "2020-10-10T14:44:39.038399", "status": "completed"} tags=[] zsl = text.ZeroShotClassifier() labels=['politics', 'elections', 'sports', 'films', 'television'] # + papermill={"duration": 1.501901, "end_time": "2020-10-10T14:45:47.978634", "exception": false, "start_time": "2020-10-10T14:45:46.476733", "status": "completed"} tags=[] doc = 'I am extremely dissatisfied with the President and will definitely vote in 2020.' zsl.predict(doc, labels=labels, include_labels=True) # + papermill={"duration": 1.26928, "end_time": "2020-10-10T14:45:49.360795", "exception": false, "start_time": "2020-10-10T14:45:48.091515", "status": "completed"} tags=[] doc = 'What is your favorite sitcom of all time?' zsl.predict(doc, labels=labels, include_labels=True) # + papermill={"duration": 1.503218, "end_time": "2020-10-10T14:45:50.968127", "exception": false, "start_time": "2020-10-10T14:45:49.464909", "status": "completed"} tags=[] doc = 'What is your favorite sitcom of all time?' zsl.predict(doc, labels=['politics', 'elections', 'sports', 'picture', 'movie', 'tv', 'films'], include_labels=True, multilabel=False) # + papermill={"duration": 8.935395, "end_time": "2020-10-10T14:46:00.009271", "exception": false, "start_time": "2020-10-10T14:45:51.073876", "status": "completed"} tags=[] doc = "<NAME> is an Indian politician \ serving as the 14th and current Prime Minister of India \ since 2014. He was the Chief Minister of Gujarat from \ 2001 to 2014 and is the Member of Parliament for Varanasi.\ Modi is a member of the Bharatiya Janata Party and of the \ Rashtriya Swayamsevak Sangh, a Hindu nationalist volunteer \ organisation. He is the first prime minister outside of the \ Indian National Congress to win two consecutive terms with \ a full majority and the second to complete more than five \ years in office after <NAME>payee." zsl.predict(doc, labels=['politics', 'india', 'minister', 'state', 'sports', 'human kind'], include_labels=True) # + papermill={"duration": 0.909418, "end_time": "2020-10-10T14:46:01.026128", "exception": false, "start_time": "2020-10-10T14:46:00.116710", "status": "completed"} tags=[] doc = "I will definitely not be seeing this movie again, but the acting was good." zsl.predict(doc, labels=['negative', 'positive'], include_labels=True) # + papermill={"duration": 0.909808, "end_time": "2020-10-10T14:46:02.042657", "exception": false, "start_time": "2020-10-10T14:46:01.132849", "status": "completed"} tags=[] doc = "I will definitely not be seeing this movie again, but the acting was good." zsl.predict(doc, labels=['negative', 'positive'], include_labels=True, multilabel=False) # + papermill={"duration": 4.44406, "end_time": "2020-10-10T14:46:06.595037", "exception": false, "start_time": "2020-10-10T14:46:02.150977", "status": "completed"} tags=[] doc = "<NAME> is an Indian politician \ serving as the 14th and current Prime Minister of India \ since 2014. He was the Chief Minister of Gujarat from \ 2001 to 2014 and is the Member of Parliament for Varanasi.\ Modi is a member of the Bharatiya Janata Party and of the \ Rashtriya Swayamsevak Sangh, a Hindu nationalist volunteer \ organisation. He is the first prime minister outside of the \ Indian National Congress to win two consecutive terms with \ a full majority and the second to complete more than five \ years in office after Atal Bihari Vajpayee." zsl.predict(doc, labels=['positive', 'negative', 'neutral'], include_labels=True) # + papermill={"duration": 29.286053, "end_time": "2020-10-10T14:46:35.989308", "exception": false, "start_time": "2020-10-10T14:46:06.703255", "status": "completed"} tags=[] # %%time doc = 'I am extremely dissatisfied with the President and will definitely vote in 2020.' labels=['politics', 'elections', 'sports', 'films', 'television'] predictions = zsl.predict(doc, labels=labels*10, include_labels=True, batch_size=1) # + papermill={"duration": 9.639739, "end_time": "2020-10-10T14:46:45.740196", "exception": false, "start_time": "2020-10-10T14:46:36.100457", "status": "completed"} tags=[] # %%time # As you can see, 26 seconds is slow. We can speed things up by increasing batch_size doc = 'I am extremely dissatisfied with the President and will definitely vote in 2020.' predictions = zsl.predict(doc, labels=labels*10, include_labels=True, batch_size=64) # + papermill={"duration": 0.117938, "end_time": "2020-10-10T14:46:45.970154", "exception": false, "start_time": "2020-10-10T14:46:45.852216", "status": "completed"} tags=[] # Lower batch sizes would be much slower given this many predictions. \ # The batch_size should be set based on available memory. # + papermill={"duration": 0.124754, "end_time": "2020-10-10T14:46:46.206341", "exception": false, "start_time": "2020-10-10T14:46:46.081587", "status": "completed"} tags=[]
zero_short_learning_nli/zero-short-nli-practice.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 # --- # # Funciones Python # Las funciones son fragmentos de cรณdigo que se pueden ejecutar mรบltiples veces, ademรกs pueden recibir y devolver informaciรณn para comunicarse con el proceso principal. # # def mi_funcion(): # aquรญ mi codigo pass # uso del pass es opcional # Una funciรณn, no es ejecutada hasta tanto no sea invocada. Para invocar una funciรณn, simplemente se la llama por su nombre: # defino mi funciรณn def hola(): print("<NAME>") # llamo mi funciรณn hola() # Cuando una funciรณn, haga un retorno de datos, รฉstos, pueden ser asignados a una variable: # + # Funciรณn retorna la palabra "<NAME>" def funcion(): return "<NAME>" # Almaceno el valor devuelto en una variable frase = funcion() print(frase) # - # ## Funciรณn con Parรกmetros # ----------------------------------- # <b>Un parรกmetro es un valor que la funciรณn espera recibir cuando sea llamada (invocada), a fin de ejecutar acciones en base al mismo.</b> Una funciรณn puede esperar uno o mรกs parรกmetros (que irรกn separados por una coma) o ninguno. # def mi_funcion(nombre, apellido): # algoritmo pass # Los parรกmetros que una funciรณn espera, serรกn utilizados por รฉsta, dentro de su algoritmo, a modo de variables de <b>รกmbito local</b>. Es decir, que los parรกmetros serรกn variables locales, a las cuรกles solo la funciรณn podrรก acceder: # # Ejemplo funciรณn con parรกmetros def mi_funcion(nombre, apellido): nombre_completo = nombre, apellido print(nombre_completo) mi_funcion('gonzalo','delgado') mi_funcion() # Ejemplo 2 def suma(a, b): # valores que se reciben return a + b a = 5 b = 6 resultado = suma(a, b) # valores que se envรญan print(resultado) # Cuando pasamos parรกmetros a nuestra funciรณn, esta entiende cada valor por la posiciรณn en que se ha descrito en la funciรณn # + # Ejemplo3 def resta(a, b): return a - b # argumento 30 => posiciรณn 0 => parรกmetro a # argumento 10 => posiciรณn 1 => parรกmetro b resta(30, 10) # - # Una forma de cambiar el orden en como entiende la funciรณn en que orden queremos pasar los parรกmetros es la siguiente: resta(b=30, a=10) # ## Valores por Defecto # Es posible colocar valores por defecto en nuestras funciones, asi si no se pasa un parรกmetro, nuestra funciรณn seguira funcionando # + def bar(x=2): x = x + 90 return x # my_var = 3 print(bar()) # - # pasando un valor a mi funcion print(bar(6)) # ## Desempaquetado de datos # Muchas veces se utilizan listas , tuplas o diccionarios para contener diversa cantidad de datos. En ese sentido, es posible desempaquetar los valores contenidos en este tipo de datos para que puedan ser leidos por la funcion # ### Args # Cuando no se sabe la cantidad de valores # + def indeterminados_posicion(*args): for arg in args: print(arg) indeterminados_posicion(5,"Hola",[1,2,3,4,5]) # - # Cuando se tiene los valores en lista # + # valores a ser sumados se encuentran en una lista def sumar(a,b): return a+b # lista con valores a ser sumados numeros_sumar=[23,11] print(sumar(*numeros_sumar)) # - # ### kwargs # Cuando no se sabe la cantidad de valores # + def indeterminados_nombre(**kwargs): for kwarg in kwargs: print(kwarg, "=>", kwargs[kwarg]) indeterminados_nombre(n=5, c="Hola", l=[1,2,3,4,5]) # - # Valores contenidos en diccionario # + def calcular(importe, descuento): return importe - (importe * descuento / 100) datos = { "descuento": 10, "importe": 1500 } print(calcular(**datos)) # - # Combinando ambos conceptos # + def super_funcion(*args,**kwargs): total = 0 for arg in args: total += arg print("sumatorio => ", total) for kwarg in kwargs: print(kwarg, "=>", kwargs[kwarg]) super_funcion(10, 50, -1, 1.56, 10, 20, 300, nombre="Hector", edad=27) # - # + datos_persona ={ 'nombre':'Gonzalo', 'edad': 26 } "Hola {nombre}, tu edad es {edad}".format(**datos_persona) # - # ## Paso por valor y referencia # ----------------------------------- # Dependiendo del tipo de dato que enviemos a la funciรณn, podemos diferenciar dos comportamientos: # # - <b>Paso por valor:</b> Se crea una copia local de la variable dentro de la funciรณn. # - <b>Paso por referencia:</b> Se maneja directamente la variable, los cambios realizados dentro de la funciรณn le afectarรกn tambiรฉn fuera. # # Tradicionalmente: # - <b>Los tipos simples se pasan por valor (Inmutables)</b>: Enteros, flotantes, cadenas, lรณgicos... # - <b>Los tipos compuestos se pasan por referencia (Mutables)</b>: Listas, diccionarios, conjuntos... # <center><img src='./img/tipo_dato.PNG' width="500" height="500"></center> # ## Paso por valor # + # Valor pasado por valor. Este genera una copia al valor pasado para no alterar el valor original del dato def bar(x): x = x + 90 x = 3 bar(x) print(x) # - # <center><img src='./img/valor.PNG' width="300" height="500"></center> # + # Para cambiar el valor de estos valores, podrรญamos reasignar el valor de variable en algunos casos def bar(x): return x + 90 my_var = 3 my_var = bar(my_var) print(my_var) # - # ## Paso por referencia # Las listas u otras colecciones, al ser tipos compuestos se pasan por referencia, y si las modificamos dentro de la funciรณn estaremos modificรกndolas tambiรฉn fuera: # + # Valor puede def foo(x): x[0] = x[0] * 99 # lista original my_list = [1, 2, 3] foo(my_list) # - my_list # <center><img src='./img/referencia.PNG' width="300" height="500"></center> # asi se genere una copia simple, esto no soluciona el problema my_list2 = my_list foo(my_list2) my_list2 my_list # se puede solucionar realizando una copia al objeto foo(my_list.copy()) my_list # ## รmbito de variables en funciones # ----------------------------------- # <center><img src='./img/ambito.PNG'></center> # #### Ejemplo # + # valor de variable global 'x' se mantiene x = 7 def foo(): x = 42 print(x) # llamo a la funcion foo() print(x) # - # Global indica que se va a trabar con variable global por lo que cuando redefinimos a la variable, # se cambia el valor global de esta x = 7 def foo(): global x x = 42 print(x) # llamo a la funcion foo() print(x) # ## Funciรณn Recursivas # ----------------------------------- # Se trata de funciones que se llaman a sรญ mismas durante su propia ejecuciรณn. Funcionan de forma similar a las iteraciones, pero debemos encargarnos de planificar el momento en que dejan de llamarse a sรญ mismas o tendremos una funciรณn rescursiva infinita. # # Suele utilizarse para dividir una tarea en subtareas mรกs simples de forma que sea mรกs fรกcil abordar el problema y solucionarlo. def jugar(intento=1): respuesta = input("ยฟDe quรฉ color es una naranja? ") if respuesta.lower() != "naranja": if intento < 3: print("\nFallaste! Intรฉntalo de nuevo") intento += 1 jugar(intento) # Llamada recursiva else: print("\nPerdiste!") else: print("\nGanaste!") jugar() # # Ejercicios # ### 1. # Realiza una funciรณn que indique si un nรบmero pasado por parรกmetro es par o impar. num = input("Introduce un nรบmero: ") num = int(num) if num == 0: print ("Este nรบmero es par.") elif num%2 == 0: print ("Este numero es par") else: print ("Este numero es impar") # ### 2. # Realiza una funciรณn llamada area_rectangulo(base, altura) que devuelva el รกrea del rectangulo a partir de una base y una altura. Calcula el รกrea de un rectรกngulo de 15 de base y 10 de altura: # # # + def area_rec(b, h): return b*h print(area_rec(15,10)) # - # ### 3. # Realiza una funciรณn llamada relacion(a, b) que a partir de dos nรบmeros cumpla lo siguiente: # # - Si el primer nรบmero es mayor que el segundo, debe devolver 1. # - Si el primer nรบmero es menor que el segundo, debe devolver -1. # - Si ambos nรบmeros son iguales, debe devolver un 0. # # Comprueba la relaciรณn entre los nรบmeros: '5 y 10', '10 y 5' y '5 y 5'. # + def rel(a, b): if a > b: return 1 elif a < b: return -1 else: return 0 print(rel(5,10)) print(rel(10,5)) print(rel(5,5)) # + def relacion(a,b): if a > b: return 1 elif b < a: return -1 elif a == b: return 0 a = float(input('Ingresa el primer nรบmero: ')) b = float(input('Ingresa el segundo nรบmero: ')) c = relacion(a,b) print(f'{c}') # - # ### 4. # El factorial de un nรบmero corresponde al producto de todos los nรบmeros desde 1 hasta el propio nรบmero. Es el ejemplo con retorno mรกs utilizado para mostrar la utilidad de este tipo de funciones: # # - 3! = 1 x 2 x 3 = 6 # - 5! = 1 x 2 x 3 x 4 x 5 = 120 # + def factorial(num): if num > 1: num = num * factorial(num -1) return num num = float(input('Ingresa el nรบmero: ')) c = factorial(num) print(f'{c}') # -
Modulo2/2. Funciones 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 # --- # # Exploring the UTx000 Extension EMA Data # (See the [GH repo](https://github.com/intelligent-environments-lab/utx000)) # # EMA Summary # In this notebook we look at the various EMA data with a focus on the sleep data from the morning EMAs. import warnings warnings.filterwarnings('ignore') # ## Package Import # + import sys sys.path.append('../') from src.features import build_features from src.visualization import visualize from src.reports import make_report import pandas as pd import numpy as np import scipy.stats as st import matplotlib.pyplot as plt import seaborn as sns import matplotlib.dates as mdates from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap from datetime import datetime, timedelta import math # - # ## Data Import # ### Morning Survey Data sleep_survey = pd.read_csv('../data/processed/beiwe-morning_ema-ux_s20.csv', index_col=0,parse_dates=True,infer_datetime_format=True) sleep_survey.head() # ### Evening Survey Data evening_survey = pd.read_csv('../data/processed/beiwe-evening_ema-ux_s20.csv', index_col=0,parse_dates=True,infer_datetime_format=True) evening_survey.head() # ### Weekly Survey Data weekly_survey = pd.read_csv('../data/processed/beiwe-weekly_ema-ux_s20.csv',index_col=0,parse_dates=True) weekly_survey.head() # # Survey Data Overview # Here we get a sense of the data we are using for the EMAs def limit_dataset(df,byvar="beacon",id_list=range(0,51,1)): """limits datasets to only including observations from certain participants""" return df[df[byvar].isin(id_list)] id_list=[1, 5, 6, 7, 10, 11, 15, 16, 17, 19, 21, 24, 25, 26, 28, 29, 34, 36, 38, 44] sleep_survey = limit_dataset(sleep_survey,id_list=id_list) evening_survey = limit_dataset(evening_survey,id_list=id_list) weekly_survey = limit_dataset(weekly_survey,id_list=id_list) # ## Available Data # We can take a look at how many submission for a particular questions were made in addition to how many participants submitted at least one answer to that category. for df, survey_type in zip([sleep_survey,evening_survey,weekly_survey],["Morning","Evening","Weekly"]): print(f"Working for {survey_type} EMAs - Total of",len(df)) for col in df.columns: if col not in ["beiwe","DoW"]: temp = df[["beiwe",col]] temp.dropna(subset=[col],inplace=True) n_responses = len(temp) n_pts = len(temp["beiwe"].unique()) print(f"\t{n_responses}\t{col}\t{n_pts} participants") # ## Submission # Various aspects related to the participants' submissions are summarized below # ### Time Frame # It is important to note that the survey period has been restricted from datetime(2020,5,13) to datetime(2020,9,1) since the corrected surveys were sent out on May 13th and the first appointment to return devices was on September 1st. We can check that assumption here by checking the earliest and latest date: temp = sleep_survey.sort_index() print("Earliest Submission:", temp.index[0]) print("Last Submission", temp.index[-1]) first_date = temp.index[0] - timedelta(days=1) end_date = temp.index[-1] # <div class="alert alert-block alert-success"> # Submission dates match the study window # </div> # ### Possible Submissions # Based on the time frame of EMA submission, we can determine the maximum amount of surveys that might have been submitted by counting the weekdays that those EMAs were sent out on. maxDailySurveys = np.busday_count(first_date.date(), end_date.date(), weekmask='Mon Wed Fri Sun') + 1 print(f'Maximum \"Daily\" Surveys: {maxDailySurveys}') print("Total number of morning surveys:", len(sleep_survey)) print("Total number of evening surveys:", len(evening_survey)) maxWeeklySurveys = np.busday_count(first_date.date(), end_date.date(), weekmask='Sat') print(f'Maximum Weekly Surveys: {maxWeeklySurveys}') print("Total number of weekly surveys:", len(weekly_survey)) def get_number_surveys_submitted(df): """ Gets the number of submissions per participant """ df.sort_values("beiwe",inplace=True) temp_dict = {"beiwe":[],"n":[]} new_df = pd.DataFrame() for pt in df['beiwe'].unique(): survey_by_pt = df[df['beiwe'] == pt] # adding to original df survey_by_pt["n"] = len(survey_by_pt) new_df = new_df.append(survey_by_pt) # adding to new dictionary temp_dict["beiwe"].append(pt) temp_dict["n"].append(len(survey_by_pt)) return new_df.sort_values("n",ascending=False), pd.DataFrame(temp_dict).sort_values("n",ascending=False) # Knowing these are the maximum possible submissions, now we can look at the total number of morning and evening survyes that were submitted by each participant. def plot_total_submissions(morning=sleep_survey, evening=evening_survey, max_daily_surveys=maxDailySurveys, first_date=first_date, end_date=end_date, by_id="beacon", save=False): """ Plots the number of surveys submitted for morning and evening """ legend_fs = 22 tick_fs = 24 label_fs = 26 title_fs = 32 fig, ax = plt.subplots(figsize=(16,5)) temp_dict = {by_id:[],"orange":[],"black":[]} morning.sort_values(by_id,inplace=True) evening.sort_values(by_id,inplace=True) for df, color, size in zip([morning,evening],['orange','black'],[100,50]): # Looping through beacon participants only for beiwe in df[by_id].unique(): survey_by_beiwe = df[df[by_id] == beiwe] survey_by_beiwe = survey_by_beiwe.sort_index()[first_date.date():end_date.date()] temp_dict[color].append(len(survey_by_beiwe)) temp_dict[by_id] = df[by_id].unique() df_to_plot = pd.DataFrame(temp_dict) df_to_plot[by_id] = df_to_plot[by_id].astype(str) df_to_plot.sort_values("orange",ascending=False,inplace=True) df_to_plot.set_index(by_id,inplace=True) for color, size, label in zip(df_to_plot.columns,[100,50],["Morning","Evening"]): # scattering number of surveys submitted per participant ax.scatter(df_to_plot.index,df_to_plot[color]/max_daily_surveys*100,s=size,color=color,label=label,zorder=10) # Average Line ax.axhline(np.mean(df_to_plot["black"])/max_daily_surveys*100,color="black",linewidth=2,linestyle="dashed",zorder=2) print(np.mean(df_to_plot["black"])/max_daily_surveys*100) ax.axhline(np.mean(df_to_plot["orange"])/max_daily_surveys*100,color="orange",linewidth=2,linestyle="dashed",zorder=1) print(np.mean(df_to_plot["orange"])/max_daily_surveys*100) # y-axis ax.set_yticks(np.arange(0,110,10)) ax.set_ylabel("Percent of Possible\nSurveys Submitted",fontsize=label_fs) plt.setp(ax.get_yticklabels(), ha="right", rotation=0, fontsize=tick_fs) # x-axis ax.set_xticks(df_to_plot.index.unique()) ax.set_xticklabels([num[:-2] for num in df_to_plot.index.unique()], ha="center", rotation=0, fontsize=tick_fs-4) ax.set_xlabel("Participant ID",fontsize=label_fs) #ax.legend(frameon=False,fontsize=legend_fs,title="EMA Timing",title_fontsize=legend_fs) for loc in ["top","right"]: ax.spines[loc].set_visible(False) if save: plt.savefig('../../papers/5eea5276044b790001ee5687/figures/beiwe-number_weekly_surveys_ordered-ux_s20.pdf',bbox_inches="tight") plt.show() plt.close() return df_to_plot temp = plot_total_submissions(save=True) evening_survey.groupby(["beacon"]).count().sort_values(["content"]) sleep_survey.groupby(["beacon"]).count().sort_values(["tst"]) # <div class="alert alert-block alert-info"> # <b>Possible Submissions</b><br> There are two participants who managed to turn in all possible morning surveys for the and one of those participants also turned in all evening surveys. The average line for the morning and evening submission averages are given and are nearly identical. # </div> # ### Submissions Over Time # Here we look at the fallout and see how participation wanes during the study. def plot_submission_timeline(morning=sleep_survey, evening=evening_survey, save=False): """ """ fig, ax = plt.subplots(figsize=(16,5)) for df, color, size, label in zip([sleep_survey,evening_survey],["orange","black"],[100,50],["Morning","Evening"]): df["date"] = df.index.date WoY = [] for d in df["date"]: WoY.append(d.isocalendar()[1]) df["WoY"] = WoY counts_by_date = df.groupby("WoY").count() ax.scatter(counts_by_date.index,counts_by_date["beiwe"],color=color,s=size,label=label,zorder=2) ax.legend(frameon=False) for loc in ["top","right"]: ax.spines[loc].set_visible(False) # x-axis ax.set_xticks(counts_by_date.index) ax.set_xticklabels(np.arange(1,len(counts_by_date)+1)) ax.set_xlabel("Week of Study") # y-axis ax.set_ylabel("Number of Surveys Submitted") ax.set_yticks(np.arange(0,165,15)) ax.set_ylim([0,200]) if save: plt.savefig("../reports/figures/ema_summary/beiwe-submission_timeline_by_week-ux_s20.pdf") plt.show() plt.close() plot_submission_timeline(save=False) # <div class="alert alert-block alert-info"> # <b>Submission Timeline</b><br> As the study progresses, the number of surveys does seem to diminish slightly. # </div> # ### Submission Timestamps # Here we look at the actual timestamps that the surveys were submitted for both the morning and evening surveys. def plot_submission_timestamp_strips(morning=sleep_survey, evening=evening_survey, save=False): """ """ morning["Survey"] = "Morning" evening["Survey"] = "Evening" daily_survey = morning.append(evening) daily_survey["hour"] = daily_survey.index.hour + daily_survey.index.minute/60 fig, ax = plt.subplots(figsize=(6,6)) sns.stripplot(x=daily_survey["Survey"],y=daily_survey["hour"], alpha=0.1,jitter=0.15,palette=["black","black"],ax=ax,zorder=3) for loc in ["top","right"]: ax.spines[loc].set_visible(False) ax.set_ylim([-0.5,24.5]) ax.set_yticks(np.arange(0,28,4)) ax.set_ylabel("Hour of Day") ax.axhline(9,zorder=2,linestyle="dashed",color="cornflowerblue",alpha=0.5) ax.axhline(19,zorder=1,linestyle="dashed",color="cornflowerblue",alpha=0.5) if save: plt.savefig("../reports/figures/ema_summary/beiwe-submission_timestamp-stripplot-ux_s20.pdf") plt.show() plt.close() plot_submission_timestamp_strips(save=False) # <div class="alert alert-block alert-info"> # <b>Submission Timestamps Stripplot</b><br> Looks like the majority of students submitted the corresponding survey at the time it was sent out (9:00 for morning, 19:00 for evening). There is also a small, but noticeable increase in the morning survey submissions at 19:00 corresponding to the evening surveys. # </div> def plot_submission_timestamp_histogram(morning=sleep_survey, evening=evening_survey, save=False): """ """ fig, axes = plt.subplots(1,2,figsize=(16,4),sharey="row") for df, ax, survey_type in zip([morning,evening], axes.flat, ["Morning", "Evening"]): df["hour"] = df.index.hour + df.index.minute/60 n,bins,patches = ax.hist(df["hour"],bins=np.arange(0,25,1),rwidth=0.9,color="cornflowerblue",edgecolor="black",) ax.set_xticks(np.arange(0,25,2)) for loc in ["top","right"]: ax.spines[loc].set_visible(False) ax.set_xlabel(survey_type) ax.set_ylabel("Count") plt.subplots_adjust(wspace=0.05) if save: plt.savefig("../reports/figures/ema_summary/beiwe-submission_timestamp-histogram-ux_s20.pdf") plt.show() plt.close() plot_submission_timestamp_histogram(save=False) # <div class="alert alert-block alert-info"> # <b>Submission Timestamps Histogram</b><br> Similar outcomes to the above figure # </div> # # Mood # We take a look at the mood data from the morning and evening surveys. The moods measured on these surveys are: # - content # - loneliness # - sadness # - stress # - energy level # ## Summary # Starting with summarizing the data similar to the basics summarized above. # ### Aggregate Histogram def label_hist(n, bins, ax): ''' Labels the histogram with values above the bars Inputs: - n: the counts for each bin - bins: the actual bins limits Returns void ''' k = [] # calculate the relative frequency of each bin for i in range(0,len(n)): k.append(round((bins[i+1]-bins[i])*n[i],0)) # plot the label/text to each bin for i in range(0, len(n)): x_pos = bins[i] + (bins[i+1] - bins[i]) / 2 y_pos = n[i] label = str(k[i])[:-2] # relative frequency of each bin ax.text(x_pos, y_pos, label, ha='center', va='bottom') def plot_mood_comparison_histogram(save=False): """ Plots side-by-side histogram comparisions of the mood reportings for the morning and evening surveys. """ fig, axes = plt.subplots(5,2,figsize=(16,14),sharey='row') c = 0 for df in [sleep_survey,evening_survey]: r = 0 for question, color in zip(['content','stress','lonely','sad','energy'],['goldenrod','firebrick','violet','cornflowerblue','seagreen']): ax = axes[r,c] n,bins,patches = ax.hist(df[question],bins=[-0.5,0.5,1.5,2.5,3.5,4.5],rwidth=0.9,color=color,edgecolor="black") ax.set_xlabel(question) if c == 0: ax.set_ylabel('Frequency') ax.set_ylim([0,1500]) ax.text(3.5,1000,f'n: {len(df[question])}') ax.text(3.5,800,f'Median: {np.median(df[question])}') label_hist(n, bins, ax) for loc in ["top","right"]: ax.spines[loc].set_visible(False) r += 1 c += 1 plt.subplots_adjust(wspace=0,hspace=0.35) if save: plt.savefig("../reports/figures/ema_summary/beiwe-all_moods-histogram-ux_s20.pdf") plt.show() plt.close() plot_mood_comparison_histogram(save=False) # # Sleep # Sleep portions of the survey includes: # - TST: total sleep time # - SOL: sleep onset latency # - NAW: number of awakenings # - Restful: Likert scale 0-3 # ## Summary # The following cells look at summarizing the results from the EMA surveys used to ask about sleep (distributed at 9:00 am every morning). # ### Aggregate Histogram # Combining all participants across all question types def plot_sleep_histogram(morning=sleep_survey,save=False): """ """ legend_fs = 22 tick_fs = 24 label_fs = 26 title_fs = 32 questions = ['tst','sol','naw','restful'] xlabels = ["TST (hours)","SOL (minutes)","Number of Awakenings","Restful Score"] bin_list = [np.arange(0,15,1), np.arange(0,120,10), np.arange(-0.5,11.5,1), [-0.5,0.5,1.5,2.5,3.5]] titles = ["a","b","c","d"] fig, axes = plt.subplots(1,4,figsize=(20,4),sharey="row",gridspec_kw={'width_ratios': [5,5,5,3]}) for question, bins, ax, xlabel, title in zip(questions, bin_list, axes.flat, xlabels, titles): n,bins,patches = ax.hist(morning[question],bins=bins,color="black", rwidth=0.9,align='mid') # x-axis ax.set_xlabel(xlabel,fontsize=label_fs-2) plt.setp(ax.get_xticklabels(), ha="center", rotation=0, fontsize=tick_fs-2) # y-axis ax.set_ylim([0,600]) if question == "restful": ax.set_xticks([0,1,2,3]) plt.setp(ax.get_yticklabels(), ha="right", rotation=0, fontsize=label_fs) # remainder for loc in ["top","right"]: ax.spines[loc].set_visible(False) #ax.set_title(title,fontsize=16) axes[0].set_ylabel('Count',fontsize=label_fs) plt.subplots_adjust(wspace=0.05) if save: plt.savefig("../../papers/5eea5276044b790001ee5687/figures/beiwe-sleep_metrics-histogram-ux_s20.pdf",bbox_inches="tight") plt.savefig("../reports/figures/ema_summary/beiwe-sleep_metrics-histogram-ux_s20.pdf",bbox_inches="tight") plt.show() plt.close() plot_sleep_histogram(save=True) # #### TST print("Maximum:", np.nanmax(sleep_survey['tst'])) print("Mean:", np.nanmean(sleep_survey['tst'])) sleep_survey[sleep_survey['tst'] == 0] # + p_7to9 = len(sleep_survey[(sleep_survey['tst'] >= 7) & (sleep_survey['tst'] <= 9)])/len(sleep_survey['tst']) print('Number of nights between 7 and 9 hours of sleep:\t', p_7to9*100) p_7to8 = len(sleep_survey[(sleep_survey['tst'] >= 7) & (sleep_survey['tst'] < 8)])/len(sleep_survey['tst']) print('Number of nights between 7 and 8 hours of sleep:\t', p_7to8*100) p_gt_7 = len(sleep_survey[(sleep_survey['tst'] >= 7)])/len(sleep_survey['tst']) print('Number of nights greater than 7 hours of sleep:\t\t', p_gt_7*100) p_gt_9 = len(sleep_survey[(sleep_survey['tst'] > 9)])/len(sleep_survey['tst']) print('Number of nights greater than 9 hours of sleep:\t\t', p_gt_9*100) p_lt_7 = len(sleep_survey[(sleep_survey['tst'] < 7)])/len(sleep_survey['tst']) print('Number of nights less than 7 hours of sleep:\t\t', p_lt_7*100) # - # #### SOL cutoffs = [5,10,15,20,30,45] for cutoff in cutoffs: p_lt_cutoff = sleep_survey[sleep_survey['sol'] < cutoff] print(f'Percent of SOL less than {cutoff} minutaes:', round(len(p_lt_cutoff)/len(sleep_survey)*100,1)) # #### NAWs cutoffs = [1,4] for cutoff in cutoffs: p_lt_cutoff = sleep_survey[sleep_survey['naw'] <= cutoff] print(f'Percent of NAW less than {cutoff}:', round(len(p_lt_cutoff)/len(sleep_survey)*100,1)) sleep_survey[sleep_survey['naw'] > 10] # #### Restful for val in [0,1,2,3]: p = round(len(sleep_survey[sleep_survey['restful'] == val])/len(sleep_survey)*100,1) print(f'Percent of Participants who rated their restfullness {val}: {p}') plot_sleep_histogram(sleep_survey[sleep_survey['restful'] == 0]) # + fig, axes = plt.subplots(1,3,figsize=(18,4)) for metric, ax in zip(["tst","sol","naw"],axes.flat): df_to_plot = sleep_survey[sleep_survey["restful"] >= 0] sns.stripplot(x="restful",y=metric,data=df_to_plot,ax=ax) plt.show() plt.close() # - # ### Individual Histograms # A subplot of all participants with the bottom row corresponding to the aggregate. # <div class="alert alert-block alert-danger"> # A plot with 51x4 subplots seems a bit excessive to try # </div> # ### Differences in the Day of the Week # Sleep metrics might vary by the day of the week, most notably the weekends. def plot_sleep_metrics_by_day(morning=sleep_survey, save=False): """ Plots the mean sleep metric for the day of the week with error bars """ # grouping by night sleep (survey date - 1 day) morning['DoW'] = (morning.index - timedelta(days=1)).strftime('%a') # all participants sleep_survey_dow = morning.groupby(['DoW']).mean() sleep_survey_dow = sleep_survey_dow.reindex(["Mon", "Tue", "Wed","Thu","Fri","Sat",'Sun']) # looping through both dataframes fig, axes = plt.subplots(4,1,figsize=(12,10),sharex=True) limits = [[5,9],[10,30],[0,3],[0,3]] for question, limit, ylabel, ax in zip(['tst','sol','naw','restful'],limits,['Hours','Minutes','Number','Score'],axes.flat): sleep_survey_dow_plot = sleep_survey_dow[sleep_survey_dow[question] >= 0] # Scattering for day of week ax.scatter(sleep_survey_dow_plot.index,sleep_survey_dow_plot[question],s=50,color='black',zorder=10) ax.set_title(question.upper()) ax.set_ylim(limit) ax.set_ylabel(ylabel) # Adding 95% CI for day in sleep_survey['DoW'].unique(): sleep_survey_by_day = sleep_survey[sleep_survey['DoW'] == day] sleep_survey_by_day = sleep_survey_by_day[sleep_survey_by_day[question] >= 0] ci = st.t.interval(0.95, len(sleep_survey_by_day[question])-1, loc=np.mean(sleep_survey_by_day[question]), scale=st.sem(sleep_survey_by_day[question])) ax.plot([day,day],ci,color='red',zorder=1) # adding number of surveys on top figure if question == 'tst': ax.text('Mon',8,'n: ',ha='right') ax.text(day,8,len(sleep_survey_by_day)) for loc in ["top","right"]: ax.spines[loc].set_visible(False) plt.subplots_adjust(wspace=0,hspace=0.2) if save: plt.savefig("../reports/figures/ema_summary/beiwe-sleep_metrics_by_day-scatter-ux_s20.pdf") plt.show() plt.close() plot_sleep_metrics_by_day(save=False) # # Analysis on Fully Filtered Dataset # In the following cells, we only consider the data from the fully filtered dataset - that is data from nights when we have GPS confirming pts are home, Fitbit data confirming pts are asleep, and beacon data from their environment. # ## Pre-Processing # We have the nights we need to consider, so first we have to filter the overall EMA dataframe by the nights present in the fully filtered beacon data. ff_df = pd.read_csv('../data/processed/beacon-fb_ema_and_gps_filtered-ux_s20.csv', index_col="timestamp", parse_dates=["timestamp","start_time","end_time"], infer_datetime_format=True) # Adding date columns to eventually merge on ff_df['date'] = ff_df['end_time'].dt.date sleep_survey['date'] = sleep_survey.index.date # Merging the two dataframes to get the correct number of nights. # + ff_sleep_survey_df = pd.DataFrame() # dataframe to hold the relevant sleep EMAs # looping through fully filtered data and merging dataframes on common start times for pt in ff_df['beiwe'].unique(): ff_sleep_pt = sleep_survey[sleep_survey['beiwe'] == pt] ff_pt = ff_df[ff_df['beiwe'] == pt] ff_pt_summary = ff_pt.groupby('date').mean() ff_sleep_survey_df = ff_sleep_survey_df.append(pd.merge(left=ff_sleep_pt,right=ff_pt_summary,left_on='date',right_on='date',how='inner')) print('Number of nights with EMAs completed:', len(ff_sleep_survey_df)) print("Number of participants:",len(ff_sleep_survey_df["beiwe"].unique())) # - ff_sleep_survey_df.head() # ## Summary # The following cells highlight some summary information and illustrate it with figures. def plot_individual_sleep_metric_histograms(df=ff_sleep_survey_df,save=False): """ """ fig, axes = plt.subplots(len(df["beiwe"].unique())+1,4,figsize=(17,15),sharex="col")#,sharey="row") df,_ = get_number_surveys_submitted(df) # Plotting individual histograms for i, pt in enumerate(df["beiwe"].unique()): # getting sleep metrics per pt df_pt = df[df["beiwe"] == pt] # plotting each histogram per pt for j, metric, xlimits, width in zip(np.arange(4),["tst","sol","naw","restful"],[[3,12],[0,40],[0,10],[0,4]],[1,5,1,1]): n, bins, _ = axes[i,j].hist(df_pt[metric],bins=np.arange(xlimits[0],xlimits[1]+width,width),rwidth=0.9,color="cornflowerblue",edgecolor='black') axes[i,j].set_ylim([0,20]) for loc in ["top","right"]: axes[i,j].spines[loc].set_visible(False) if j != 0: axes[i,j].spines["left"].set_visible(False) axes[i,j].set_yticks([]) # Plotting aggregate histogram (last row) for j, metric, xlimits, width in zip(np.arange(4),["tst","sol","naw","restful"],[[3,12],[0,40],[0,10],[0,4]],[1,2,1,1]): n, bins, _ = axes[len(df["beiwe"].unique()),j].hist(df[metric],bins=np.arange(xlimits[0],xlimits[1]+width,width),rwidth=0.9,color="navy",edgecolor='black') axes[len(df["beiwe"].unique()),j].set_ylim([0,120]) for loc in ["top","right"]: axes[len(df["beiwe"].unique()),j].spines[loc].set_visible(False) if j != 0: axes[len(df["beiwe"].unique()),j].spines["left"].set_visible(False) axes[len(df["beiwe"].unique()),j].set_yticks([]) for k, label in enumerate(["TST (hours)","SOL (minutes)","NAW","Restful"]): axes[len(df["beiwe"].unique()),k].set_xlabel(label) plt.subplots_adjust(hspace=0.225,wspace=0.075) if save: plt.savefig("../reports/figures/ema_ff_summary/beiwe-sleep_metrics-histogram_by_pt-ux_s20.pdf") plt.show() plt.close() plot_individual_sleep_metric_histograms(save=False) # ## Individual Sleep Metric Summary def plot_stacked_hist(df,var,limits,width=1,cmap='coolwarm',by_var='beiwe',save=False,save_dir='../reports/figures/ema_ff_summary/'): ''' Plots a stacked histogram with each color representing a unique individual. Inputs: - df: dataframe of the data - var: string specifying the column in the dataframe to plot - limits: tuple representing the lower and upper bound on the x-axis - width: integer/float for the width of each bin - by_var: string specifying the column to color the stacks by - save: boolean to save or not - save_dr: string representing the location to save the figure if save is True Returns the axes with the histogram ''' list_to_plot = [] for pt in df[by_var].unique(): temp_df = df[df[by_var] == pt] list_to_plot.append(temp_df[var].to_list()) colors = cm.get_cmap(cmap, len(list_to_plot)) fig, ax = plt.subplots(figsize=(8,4)) n, bins, _ = ax.hist(list_to_plot,bins=np.arange(limits[0],limits[1]+width,width),stacked=True,rwidth=0.9, color=colors(np.linspace(0, 1, len(list_to_plot))),edgecolor='black') for loc in ['right','top']: ax.spines[loc].set_visible(False) ax.set_ylabel('Count') if save: plt.savefig(f'{save_dir}/{var}-stacked_hist-ux_s20.pdf') return ax # ### TST # Total Sleep Time as reported by the participants # + ax = plot_stacked_hist(ff_sleep_survey_df,'tst',[2,12],by_var='beiwe') ax.set_ylim([0,100]) ax.set_xlabel('Hours') ax.axvline(7,color='black',linestyle='dashed',linewidth=2) ax.axvline(9,color='black',linestyle='dashed',linewidth=2) ax.text(8,90,"Recommended",ha='center',va='center') #plt.savefig('../reports/figures/beiwe_sleep_duration-stacked_hist-ux_s20.pdf') plt.show() plt.close() # + p_7to9 = len(ff_sleep_survey_df[(ff_sleep_survey_df['tst'] >= 7) & (ff_sleep_survey_df['tst'] <= 9)])/len(ff_sleep_survey_df['tst']) print('Number of nights between 7 and 9 hours of sleep:\t', p_7to9*100) p_6to7 = len(ff_sleep_survey_df[(ff_sleep_survey_df['tst'] >= 6) & (ff_sleep_survey_df['tst'] < 7)])/len(ff_sleep_survey_df['tst']) print('Number of nights between 6 and 7 hours of sleep:\t', p_6to7*100) p_gt_7 = len(ff_sleep_survey_df[(ff_sleep_survey_df['tst'] >= 7)])/len(ff_sleep_survey_df['tst']) print('Number of nights greater than 7 hours of sleep:\t\t', p_gt_7*100) p_gt_9 = len(ff_sleep_survey_df[(ff_sleep_survey_df['tst'] > 9)])/len(ff_sleep_survey_df['tst']) print('Number of nights greater than 9 hours of sleep:\t\t', p_gt_9*100) p_lt_7 = len(ff_sleep_survey_df[(ff_sleep_survey_df['tst'] < 7)])/len(ff_sleep_survey_df['tst']) print('Number of nights less than 7 hours of sleep:\t\t', p_lt_7*100) # - # Looking at the reported TSTs to see how participants tend to report TST. def plot_tst_raw_values(df=ff_sleep_survey_df,save=False): """ """ fig, ax = plt.subplots(figsize=(12,6)) ff_sleep_survey_df.sort_values(['tst'],inplace=True) sns.swarmplot(df["tst"],size=5,color="cornflowerblue",ax=ax) for loc in ["top","right","left"]: ax.spines[loc].set_visible(False) ax.set_xticks(np.arange(3,13,1)) ax.set_yticks([]) ax.grid(axis="x") if save: plt.savefig("../reports/figures/ema_ff_summary/beiwe-tst-swarmplot-ux_s20.pdf") plt.show() plt.close() plot_tst_raw_values() # <div class="alert alert-block alert-success"> # Participants tend to report their TST at half-hour increments with two exceptions. # </div> # ### SOL # We have SOL reported by the pts. # + ax = plot_stacked_hist(ff_sleep_survey_df,'sol',[0,60],width=5,by_var='beiwe') ax.set_ylim([0,100]) ax.set_xlabel('Minutes') ax.axvline(15,color='black',linestyle='dashed',linewidth=2) ax.axvline(30,color='black',linestyle='dashed',linewidth=2) ax.axvline(45,color='black',linestyle='dashed',linewidth=2) ax.text(7.5,80,"Great",ha='center',va='center') ax.text(22.5,80,"Good",ha='center',va='center') ax.text(52.5,80,"Poor",ha='center',va='center') #plt.savefig('../reports/figures/beiwe_sleep_sol-stacked_hist-ux_s20.pdf') plt.show() plt.close() # - cutoffs = [15,30,50] for cutoff in cutoffs: p_lt_cutoff = ff_sleep_survey_df[ff_sleep_survey_df['sol'] < cutoff] print(f'Percent of SOL less than {cutoff} minutes:', round(len(p_lt_cutoff)/len(ff_sleep_survey_df)*100,1)) high_sol = ff_sleep_survey_df[ff_sleep_survey_df['sol'] >= 30] high_sol # ### Awakenings # + ax = plot_stacked_hist(ff_sleep_survey_df,'naw',[0,11],width=1,by_var='beiwe') ax.set_ylim([0,100]) ax.set_xlabel('Number') # resetting xtick-labels ax.set_xticks(np.arange(0.5,11.5,1)) ax.set_xticklabels(np.arange(0,11,1)) ax.axvline(2,color='black',linestyle='dashed',linewidth=2) ax.axvline(4,color='black',linestyle='dashed',linewidth=2) ax.text(1,80,"Good",ha='center',va='center') ax.text(5,80,"Poor",ha='center',va='center') #plt.savefig('../reports/figures/beiwe_sleep_awakenings-stacked_hist-ux_s20.pdf') plt.show() plt.close() # - cutoffs = [2,4] for cutoff in cutoffs: p_lt_cutoff = ff_sleep_survey_df[ff_sleep_survey_df['naw'] < cutoff] print(f'Percent of NAW less than {cutoff}:', round(len(p_lt_cutoff)/len(ff_sleep_survey_df)*100,1)) # ### Restful Score # On a scale of 0-3 (not at all to very much) # + ax = plot_stacked_hist(ff_sleep_survey_df,'restful',[0,4],width=1,by_var='beiwe') ax.set_ylim([0,100]) ax.set_xticks([0.5,1.5,2.5,3.5]) ax.set_xticklabels(['0: Not at all','1: A little bit','2: Quite a bit','3: Very much']) ax.set_xlabel('Response') #plt.savefig('../reports/figures/beiwe_sleep_restful-stacked_hist-ux_s20.pdf') plt.show() plt.close() # - for val in [0,1,2,3]: p = round(len(ff_sleep_survey_df[ff_sleep_survey_df['restful'] == val])/len(ff_sleep_survey_df)*100,1) print(f'Percent of Participants who rated their restfullness {val}: {p}') # Looking at the sleep summaries for those participants who had bad restfulness scores. rest_0 = ff_sleep_survey_df[ff_sleep_survey_df['restful'] == 0] rest_0 # ### Comparing Poor Sleep Results # There are a few outlying individuals and it would be interesting to see how many of these individuals are present as outliers. # #### Bad Everything # Here we check to see if any participant was poor in all four categories. def check_sleep_results(df=ff_sleep_survey_df): """ Used to check how many participants responded a certain way to each of the four sleep metric questions """ print("Inequalities:\n\t1. <\n\t2. >\n\t3. <=\n\t4. >=\n\t5. ==") for metric in ["tst","sol","naw","restful"]: try: value = float(input(f"Value to check for {metric}: ")) inequality = int(input("Inequality: ")) except ValueError: value = -1 inequality = -1 if inequality == 1: print(f"{metric} < {value}") df = df[df[metric] < value] elif inequality == 2: print(f"{metric} > {value}") df = df[df[metric] > value] elif inequality == 3: print(f"{metric} <= {value}") df = df[df[metric] <= value] elif inequality == 4: print(f"{metric} >= {value}") df = df[df[metric] >= value] elif inequality == 5: print(f"{metric} = {value}") df = df[df[metric] == value] else: print(f"No test for {metric}") return df check_sleep_results() # + tst_lt6 = ff_sleep_survey_df[ff_sleep_survey_df['tst'] < 6] print(tst_lt6.sort_values(["beacon"])['beacon'].unique()) sol_gt30 = ff_sleep_survey_df[ff_sleep_survey_df['sol'] >= 30] print(sol_gt30.sort_values(["beacon"])['beacon'].unique()) naw_gt4 = ff_sleep_survey_df[ff_sleep_survey_df['naw'] >= 4] print(naw_gt4.sort_values(["beacon"])['beacon'].unique()) rest_0 = ff_sleep_survey_df[ff_sleep_survey_df['restful'] == 0] print(rest_0.sort_values(["beacon"])['beacon'].unique()) # - # <div class="alert alert-block alert-success"> # None of the participants scored poorly in all self-report sleep metrics. # </div> # #### Bad Restful and High NAW check_sleep_results() # <div class="alert alert-block alert-success"> # Only one person reported poor restfulness scores when considering their number of awakenings. # </div> # ## Predictors for Poor Restful Scores # We want to see which other self-report sleep measures are the best predictors for a poor or good restful sleep score. # + from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split import statsmodels.api as sm # - # ### Binary Classification - All Restful Scores # Here we consider all restful scores, but classify them as either bad (0,1) or good (2,3) to create a binary classification problem. # Massaging the data x = ff_sleep_survey_df[['tst','sol','naw']] # rescaling SOL to hours so we have similar magnitudes x['sol'] /= 60 y = ff_sleep_survey_df[['restful']] y['score'] = np.where(y['restful'] < 2, 0, 1) y.drop(['restful'],axis=1,inplace=True) # Fitting the model and getting the coefficients # SciKit model = LogisticRegression(solver='lbfgs') model.fit(x,y) # StatsModels x_sm = sm.add_constant(x) log_reg = sm.Logit(y, x_sm).fit(method='lbfgs') # Comparing results from the two models # + print("\tSKL\tSM") for sleep_metric, sklearn_c, sm_c in zip(x.columns.values,model.coef_[0],log_reg.params[1:]): print(f'{sleep_metric}:\t{round(sklearn_c,3)}\t{round(sm_c,3)}') print(f'y-int:\t{round(model.intercept_[0],3)}\t{round(log_reg.params[0],3)}') # - # <div class="alert alert-block alert-info"> # The TST seems to be the greatest predictor of restful sleep scores. # <div> # We can look at the individual contributions to the restful score but plotting a one-var logit. # + fig, axes = plt.subplots(3,1,figsize=(12,12)) xs = np.arange(0,14.1,0.1) ys = {'full':[],'tst':[],'sol':[],'naw':[]} for x_val in xs: ys['full'].append(1 / (1+math.exp(-1*(model.intercept_[0]+x_val*model.coef_[0][0]+x_val*model.coef_[0][1]+x_val*model.coef_[0][2])))) ys['tst'].append(1 / (1+math.exp(-1*(model.intercept_[0]+x_val*model.coef_[0][0])))) ys['sol'].append(1 / (1+math.exp(-1*(model.intercept_[0]+x_val*model.coef_[0][1])))) ys['naw'].append(1 / (1+math.exp(-1*(model.intercept_[0]+x_val*model.coef_[0][2])))) ax = axes[0] ax.scatter(x['tst'],y['score'],color='cornflowerblue',edgecolor='black',s=50,label='Raw Data Points') ax.plot(xs,ys['tst'],color='firebrick',linewidth=1,label='TST Only') ax.set_xlabel('TST (hours)') ax = axes[1] ax.scatter(x['sol'],y['score'],color='cornflowerblue',edgecolor='black',s=50,label='Raw Data Points') ax.plot(xs,ys['sol'],color='firebrick',linewidth=1,label='SOL Only') ax.set_xlim([0,2]) ax.set_xlabel('SOL (hours)') ax = axes[2] ax.scatter(x['naw'],y['score'],color='cornflowerblue',edgecolor='black',s=50,label='Raw Data Points') ax.plot(xs,ys['naw'],color='firebrick',linewidth=1,label='NAW Only') ax.set_xlabel('Number of Awakenings') for ax in axes: ax.set_ylim([-0.1,1.1]) ax.set_yticks([0,1]) ax.set_yticklabels(["Not Restful (0/1)","Restful (3/4)"]) plt.subplots_adjust(hspace=0.2) plt.show() plt.close() # - # #### TST Only # Since TST seems to be the greatest predictor, we can create a model that takes into account only this parameter. # + # sklearn model = LogisticRegression() model.fit(x['tst'].values.reshape(-1, 1),y) print(f'TST:', round(model.coef_[0][0],3)) print(f'Intercept: {round(model.intercept_[0],3)}') # - # Similar results to when we included the other sleep metrics.
notebooks/4.3.1-hef-ema-summary.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/KevinTheRainmaker/Recommendation_Algorithms/blob/main/colab/tf_recommender/Recommender_Using_TF_1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="llo58hyTsxdS" outputId="1e456937-0e03-464a-aed4-6906460f9261" # !pip install -q tensorflow-recommenders # + colab={"base_uri": "https://localhost:8080/"} id="NjXB1TISs4sZ" outputId="eab5e85c-d174-4ce7-9520-a216309ba195" # !pip install -q --upgrade tensorflow-datasets # + colab={"base_uri": "https://localhost:8080/"} id="dECZWaDU1wA1" outputId="d961a391-1e1c-463d-dac2-1df3a8796e63" # # !pip install wandb -q # + id="aJO4P6BA1xVR" # # !wandb login # + id="3RPI2FQa2HLb" # import wandb # wandb.init(project='wandb_recommender', # config={ # 'layer_1_activation':"relu", # 'layer_1':256, # 'layer_2_activation':"relu", # 'layer_2':64, # 'learning_rate':0.01, # 'dropout_rate':0.2 # }) # + id="AGoU56Oq2NIx" # config = wandb.config # + id="I859qMh-2NC5" # from wandb.keras import WandbCallback # + id="zf1Pl8tz2M9r" # + colab={"base_uri": "https://localhost:8080/"} id="rBZ9hJ_ts6lz" outputId="b84f256a-7ed0-47cd-ddfd-b7595f88694a" import os import pprint import tempfile from typing import Dict, Text import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_recommenders as tfrs print(tf.__version__) # + colab={"base_uri": "https://localhost:8080/", "height": 184, "referenced_widgets": ["2d98baae06fb4a81975da61e2751d2af", "31790fbc8a1347f291a72aa299881a14", "cc62cd65f07f4211abf174ca9bb7f2d7", "0000b5bd4a894dc6a5a577f94292d37d", "6cc90794f765425aac4e3e330be03f6c", "f512e2a0904b484eacadf508d1dfd5b6", "82294c03c6694484b168b05a080de214", "647463f0fd164534a1d78649d775a679", "79b3740ce82c4954baba771246267004", "<KEY>", "75d616f468294186bd9ace4cccae618c", "ed7744362b674594913959a5a4636989", "6925f9a463c743c3b96686b0ee2f8ed0", "699637197ca34da1a1bda0bc60e48230", "8522234d49f9486888c8909a260c57c1", "6a2ab3abcf57498fa01ee0fbef0d0ada", "<KEY>", "d349574d8b574e0da517fc4caa201ad1", "<KEY>", "<KEY>", "18d1192382404dd38f2f01df14c47750", "<KEY>", "f851573a127b4622a54424d1c9a2e834", "<KEY>", "b0dd9f6fbc5644ef8b59bee1be0ed538", "<KEY>", "<KEY>", "014ac10ac0024167872f974c49e968b1", "ce861ac53aec4fddbb4618efc1789ab0", "ff75daa7bdd84050b408a1b018384437", "5929e78c62134ef3b790c295a038be05", "<KEY>", "93d77e738d4041a8a2be1acb76844eb6", "e04e78131db849c490f5ab056deb83a9", "ce65afba8b06432c947043a8e6b13afc", "41985fb0a00040b398e24904c8df890c", "<KEY>", "c882ee6d5e0140899c98ca61e552882e", "c3386bef26ab4e8a923c6a90aad2139a", "9169b2317e12451da6ee274b771dd12c", "<KEY>", "<KEY>", "<KEY>", "20e054fbe6874fce92b443b5852d5e31", "e32583a8c9da403faf68befa46848454", "a02d83f39aae49e5ba5c0a2c9c54ccec", "4684b691014247c0a4709200b880e948", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "ea6d6f9a88f14a54ad95dae525a2b86f", "<KEY>", "<KEY>", "730a15baf9334e1eb0963ff2a1dbc9a1", "<KEY>", "cc41e641a97841749d1befaee549f7c1", "25306e6b55f244b2a89d3800cee820c1", "<KEY>", "<KEY>", "<KEY>", "18e02c08659c40a99056edb75e8bb16b", "a2850d81170e4d00bf4f2608662e486b"]} id="cuMiNQzAtHKG" outputId="da988b59-750b-423a-fae9-89aa89d2a87c" ratings_raw = tfds.load("movielens/100k-ratings", split="train") print(ratings_raw) # + id="78eYWd0-wPup" ratings = ratings_raw.map(lambda x: { "movie_title": x["movie_title"], "user_id": x["user_id"], "user_rating": x["user_rating"] }) # + id="wM6crU_ftOsK" shuffled = ratings.shuffle(100_000, reshuffle_each_iteration=False) train = shuffled.take(80_000) test = shuffled.skip(80_000).take(20_000) # + id="CU8hrE7mt2sQ" movie_titles = ratings.batch(1_000_000).map(lambda x: x["movie_title"]) user_ids = ratings.batch(1_000_000).map(lambda x: x["user_id"]) unique_movie_titles = np.unique(np.concatenate(list(movie_titles))) unique_user_ids = np.unique(np.concatenate(list(user_ids))) # + id="ynfjgc0ht64W" class RankingModel(tf.keras.Model): def __init__(self): super().__init__() embedding_dimension = 32 # Compute embeddings for users. self.user_embeddings = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_user_ids, mask_token=None), tf.keras.layers.Embedding(len(unique_user_ids) + 1, embedding_dimension) ]) # Compute embeddings for movies. self.movie_embeddings = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_movie_titles, mask_token=None), tf.keras.layers.Embedding(len(unique_movie_titles) + 1, embedding_dimension) ]) # Compute predictions. self.ratings = tf.keras.Sequential([ # Learn multiple dense layers. tf.keras.layers.Dense(256, activation='relu'), # tf.keras.layers.Dense(config.layer_1, activation=config.layer_1_activation), tf.keras.layers.Dense(64, activation='relu'), # tf.keras.layers.Dense(config.layer_2, activation=config.layer_2_activation), tf.keras.layers.Dropout(0.2), # Make rating predictions in the final layer. tf.keras.layers.Dense(1) ]) def call(self, inputs): user_id, movie_title = inputs user_embedding = self.user_embeddings(user_id) movie_embedding = self.movie_embeddings(movie_title) return self.ratings(tf.concat([user_embedding, movie_embedding], axis=1)) # + colab={"base_uri": "https://localhost:8080/"} id="ZDShxAUQuFgP" outputId="cec074fe-8fb2-445a-f55c-a82f781a8dae" RankingModel()((["1"], ["One Flew Over the Cuckoo's Nest (1975)"])) # + id="dT0TNRgHuMqm" task = tfrs.tasks.Ranking( loss = tf.keras.losses.MeanSquaredError(), metrics=[tf.keras.metrics.RootMeanSquaredError()] ) # + id="lwkKlD4juPqP" # + id="b8JP7KESui8k" # + [markdown] id="QMSYeOu7GpAo" # # Compact # + id="csL94S0pui3B" class MovielensModel(tfrs.models.Model): def __init__(self): super().__init__() self.ranking_model: tf.keras.Model = RankingModel() self.task: tf.keras.layers.Layer = tfrs.tasks.Ranking( loss = tf.keras.losses.MeanSquaredError(), metrics=[tf.keras.metrics.RootMeanSquaredError()] ) def call(self, features: Dict[str, tf.Tensor]) -> tf.Tensor: return self.ranking_model( (features["user_id"], features["movie_title"])) def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor: labels = features.pop("user_rating") rating_predictions = self(features) # The task computes the loss and the metrics. return self.task(labels=labels, predictions=rating_predictions) # + id="4roNFszqukY0" model = MovielensModel() model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.01)) # + id="JH-aUnmtunxu" cached_train = train.shuffle(100_000).batch(4096).cache() cached_test = test.batch(2048).cache() # + colab={"base_uri": "https://localhost:8080/"} id="ceKXt3cwupuy" outputId="a92c377a-df54-48be-988b-dcf867f758ca" model.fit(cached_train, epochs=100) # + colab={"base_uri": "https://localhost:8080/"} id="UmLL49HiurSM" outputId="2c8fdb0e-0b15-4ff2-c216-e6a482cb61c8" model.evaluate(cached_test, return_dict=True) # + colab={"base_uri": "https://localhost:8080/"} id="ARB1YKZTus-c" outputId="6c573d71-006c-4da8-ed29-11e18c6d64fb" test_ratings = {} test_movie_titles = ["M*A*S*H (1970)", "Dances with Wolves (1990)", "Speed (1994)"] for movie_title in test_movie_titles: test_ratings[movie_title] = model({ "user_id": np.array(["42"]), "movie_title": np.array([movie_title]) }) print("Ratings:") for title, score in sorted(test_ratings.items(), key=lambda x: x[1], reverse=True): print(f"{title}: {score}") # + [markdown] id="-uVKF8i0vFvK" # # Serving # + colab={"base_uri": "https://localhost:8080/"} id="EX7bvxjLuy93" outputId="3e4b901a-e5fb-48b3-d3ec-576f789bb8ce" tf.saved_model.save(model, "export") # + colab={"base_uri": "https://localhost:8080/"} id="7que-jfAvHgu" outputId="5af70d89-1ad5-4e60-99d0-fef2770ae202" # Loading loaded = tf.saved_model.load("export") loaded({"user_id": np.array(["42"]), "movie_title": ["Speed (1994)"]}).numpy() # + id="EVeA3LldvKgA"
colab/tf_recommender/Recommender_Using_TF_1.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 import numpy as np import matplotlib.pyplot as plt import datetime as dt import xarray as xr import cartopy.crs as ccrs from pyresample.geometry import AreaDefinition from pyresample.geometry import GridDefinition from pyresample import image, geometry, load_area, save_quicklook, SwathDefinition, area_def2basemap from pyresample.kd_tree import resample_nearest from scipy import spatial sys.path.append('../saildrone/subroutines/') from read_routines import read_all_usv, read_one_usv, add_den_usv, add_flux_usv sys.path.append('./../flux/') import warnings warnings.simplefilter('ignore') # filter some warning messages from glob import glob import cartopy.crs as ccrs # import projections # - # # Read in All Saildrone cruises downloaded from https://data.saildrone.com/data/sets # - 2017 onwards, note that earlier data is going to lack insruments and be poorer data quality in general # - For this code I want to develop a routine that reads in all the different datasets and creates a standardized set # - It may work best to first read each of the files individually into a dictionary # - then go through each dataset finding all variable names # - I decided to put all SST into TEMP_CTD_MEAN and same for Salinity so there is a single variable name # - this still preserves all the dataset information # + dir_data = 'C:/Users/gentemann/Google Drive/public/2019_saildrone/' #'f:/data/cruise_data/saildrone/saildrone_data/' dir_data_pattern = 'C:/Users/gentemann/Google Drive/public/2019_saildrone/*.nc' #dir_out = 'F:/data/cruise_data/saildrone/sss/sss_collocations_8day/' #dir_fig = 'F:/data/cruise_data/saildrone/sss/figs/' dir_out = '//White_home_pc/f/data/cruise_data/saildrone/sss/sss_collocations_8day/' dir_fig = '//White_home_pc/f/data/cruise_data/saildrone/sss/figs/' #get list of all filenames in directory files = [x for x in glob(dir_data+'*.nc')] print('number of file:',len(files)) # - for ifile,file in enumerate(files): # if not ifile==0: # continue print(ifile,file) ds_usv,name = read_one_usv(file) ds_usv['lat'] = ds_usv.lat.interpolate_na(dim='time',method='linear').ffill(dim='time').bfill(dim='time') ds_usv['lon'] = ds_usv.lon.interpolate_na(dim='time',method='linear').ffill(dim='time').bfill(dim='time') ds_usv = add_den_usv(ds_usv) ds_usv = add_flux_usv(ds_usv,1.0) t1,t2=ds_usv.time.min().data-np.timedelta64(8,'D'),ds_usv.time.max().data+np.timedelta64(8,'D') fin = dir_out+name+'_RSS8dy'+'.nc' ds_rss = xr.open_dataset(fin) fin = dir_out+name+'_JPL8dy'+'.nc' ds_jpl = xr.open_dataset(fin) plt.figure(figsize=(10,10)) dx,dy=3,5 t1,t2=ds_usv.time.min().data-np.timedelta64(8,'D'),ds_usv.time.max().data+np.timedelta64(8,'D') x1,x2=ds_usv.lon.min().data-dx,ds_usv.lon.max().data+dx y1,y2=ds_usv.lat.min().data-dy,ds_usv.lat.max().data+dy ax1 = plt.subplot(211) ds_usv.SAL_CTD_MEAN.plot(ax=ax1,label='USV') ds_rss.sss_smap.plot(ax=ax1,label='RSS') ds_rss.sss_smap_40km.plot(ax=ax1,label='RSS 40 km') ds_jpl.smap_sss.plot(ax=ax1,label='JPL') ax1.legend() ax2 = plt.subplot(223) ds_rss2 = ds_rss.where(ds_rss.sss_smap>-10) ax2.scatter(ds_usv.SAL_CTD_MEAN,ds_usv.SAL_CTD_MEAN-ds_rss.sss_smap,label='USV - RSS',s=.5) #to get color right ax2.scatter(ds_usv.SAL_CTD_MEAN,ds_usv.SAL_CTD_MEAN-ds_rss.sss_smap,label='USV - RSS',s=.5) ax2.scatter(ds_usv.SAL_CTD_MEAN,ds_usv.SAL_CTD_MEAN-ds_rss2.sss_smap_40km,label='USV - RSS 40 k',s=1) ax2.scatter(ds_usv.SAL_CTD_MEAN,ds_usv.SAL_CTD_MEAN-ds_jpl.smap_sss,label='USV - JPL',s=.5) ax2.set_xlabel('Saildrone (psu)') ax2.set_ylabel('$\DeltaSSS (psu)') ax3 = plt.subplot(224,projection = ccrs.PlateCarree()) ds2 = ds_usv im=ax3.scatter(ds2.lon,ds2.lat,c=ds2.SAL_CTD_MEAN,s=.15,transform=ccrs.PlateCarree(),cmap='jet') ax3.coastlines(resolution='10m') ax3.set_extent([x1,x2,y1,y2]) dir_fig = 'C:/Users/gentemann/Google Drive/public/2019_saildrone/ATOMIC/figs/' plt.savefig(dir_fig+'sss_timeseries'+name+'.png') ds_usv ds_usv # + dx,dy=3,5 t1,t2=ds_usv.time.min().data-np.timedelta64(8,'D'),ds_usv.time.max().data+np.timedelta64(8,'D') x1,x2=ds_usv.lon.min().data-dx,ds_usv.lon.max().data+dx y1,y2=ds_usv.lat.min().data-dy,ds_usv.lat.max().data+dy fig = plt.figure(figsize=(8,8)) #ax = plt.axes(projection = ccrs.NorthPolarStereo(central_longitude=180.0)) # create a set of axes with Mercator projection ax = plt.axes(projection = ccrs.PlateCarree()) # create a set of axes with Mercator projection ds2 = ds_usv im=ax.scatter(ds2.lon,ds2.lat,c=ds2.SAL_CTD_MEAN,s=.15,transform=ccrs.PlateCarree(),cmap='jet') ax.coastlines(resolution='10m') ax.set_extent([x1,x2,y1,y2]) #ax.legend() cax = fig.add_axes([0.45, 0.17, 0.3, 0.02]) cbar = fig.colorbar(im,cax=cax, orientation='horizontal') cbar.set_label('SSS (psu)') #fig.savefig(fig_dir+'figs/map_nasa'+str(i).zfill(2)+'_data.png') # - d= np.datetime64('2020-07-10') 30*6 d.astype(object).toordinal()
Plot_all_saildrone_8dy_collocations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:dev3.7] # language: python # name: conda-env-dev3.7-py # --- # # Model Persistence # Initial imports from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from pathlib import Path import pandas as pd # Read in data data = Path("Resources/Week14-Day2-Activity1-winequality.csv") df = pd.read_csv(data, delimiter=";") df.head() # Define the features X set and the target y vector X = df.iloc[:, 0:11].values y = df["quality"].values # + # Scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler().fit(X) X = scaler.transform(X) # + # Define the model - shallow neural network nn = Sequential() # Hidden layer nn.add(Dense(units=8, input_dim=11, activation="relu")) # Output layer nn.add(Dense(units=1, activation="linear")) # + # Compile the model nn.compile(loss="mean_squared_error", optimizer="adam", metrics=["mse"]) # Fit the model model = nn.fit(X, y, epochs=200, verbose=0) # + # Save model as JSON nn_json = nn.to_json() file_path = Path("Resources/Week14-Day2-Activity03-model.json") with open(file_path, "w") as json_file: json_file.write(nn_json) # Save weights file_path = "Resources/Week14-Day2-Activity03-model.h5" nn.save_weights("Resources/Week14-Day2-Activity03-model.h5") # + # Load the saved model to make predictions from tensorflow.keras.models import model_from_json # load json and create model file_path = Path("Resources/Week14-Day2-Activity03-model.json") with open(file_path, "r") as json_file: model_json = json_file.read() loaded_model = model_from_json(model_json) # load weights into new model file_path = "Resources/Week14-Day2-Activity03-model.h5" loaded_model.load_weights(file_path) # - # Make some predictions with the loaded model df["predicted"] = loaded_model.predict(X) df.head(10)
PythonJupyterNotebooks/Week14-Day2-Activity03-model_persistence.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="WM63uis-6hLT" # Grupo 03 # # 1. <NAME> # 2. <NAME> # 3. <NAME> # 4. <NAME> # 5. <NAME> # 6. <NAME> # + [markdown] id="gCwKfWEHA3I-" # Esse cรณdigo faz os seguintes passos: # # 9. Anรกlise Descritiva dos dados processados. # + id="R3NLDbOI7nB0" # Bibliotecas import pandas as pd # manipulaรงรฃo de dados import numpy as np # manipulaรงรฃo de dados import seaborn as sns # criaรงรฃo de grรกficos # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 18605, "status": "ok", "timestamp": 1639403571840, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="wv70tx1ucyrB" outputId="84958c65-95cc-46a1-8455-777fdd81b3e0" # Fazendo a conexao com o google drive (aula Mineracao) from google.colab import drive drive.mount('/content/drive') # + colab={"base_uri": "https://localhost:8080/", "height": 312} executionInfo={"elapsed": 333, "status": "ok", "timestamp": 1639404793808, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="9soo3ZOZ6Tsu" outputId="6ecfd7fd-5b9e-4df3-81fa-8bbade2b21d0" # Lendo os dados path = "XXX" arq = "dados_processados.csv" dados = pd.read_csv(path + arq) dados.head() # + [markdown] id="nhusm6rxc1ya" # # Quais os tรฉcnicos mais rodados? # # # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 357, "status": "ok", "timestamp": 1639404797996, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="WKsN6Qhn83dh" outputId="e30750e3-80fa-453f-ab4d-5c42dd9b67f5" # Numero de times por tecnico times_tec = dados.groupby(['tecnico'], as_index = False).agg({"time": "nunique"}) times_tec = times_tec.rename({'time':'num_time'}, axis = 'columns') times_tec = times_tec.sort_values(by = "num_time", ascending = False) times_tec.head(5) # + [markdown] id="RpS-ZQVV-leu" # # Quais os times que mais demitem?/Quais time tiveram mais tรฉcnicos? # + colab={"base_uri": "https://localhost:8080/", "height": 362} executionInfo={"elapsed": 260, "status": "ok", "timestamp": 1639404801832, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="j-T3t1yG-KXm" outputId="bfe3a976-89e3-46ef-ff64-3d4ff4f26e3e" # Numero de tecnicos por time tec_time = dados.groupby(['time'], as_index = False).agg({"tecnico": "nunique"}) tec_time = tec_time.rename({'tecnico':'num_tecnico'}, axis = 'columns') tec_time = tec_time.sort_values(by = "num_tecnico", ascending = False) tec_time.head(10) # + [markdown] id="U6Wkikelc88p" # # Qual tรฉcnico ficou mais tempo? # + id="p1GdFWiCIEEV" # Transformando variรกvel tempo_tec em float dados['tempo_tec'] = dados['tempo_tec'].str.replace (' days', '') dados['tempo_tec'] = dados['tempo_tec'].astype(float) # + colab={"base_uri": "https://localhost:8080/", "height": 362} executionInfo={"elapsed": 276, "status": "ok", "timestamp": 1639405322020, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="nSQ4jYYSXeDg" outputId="3313aeee-bfb1-4ca2-8e92-a9a51f8ef726" tempo_tec = dados.groupby(['tecnico', 'time'], as_index = False).agg({"tempo_tec": "max"}) # nunique tempo_tec = tempo_tec.sort_values(by = "tempo_tec", ascending = False) tempo_tec.head(10) # + [markdown] id="NxTNge7ldFJi" # # Qual o nรบmero de dias que um tรฉcnico fica em um time? # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 312, "status": "ok", "timestamp": 1639406166887, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="dtLER3pBNlU2" outputId="d17aa34f-7b43-4158-ac91-ecaa6513ceab" # Mรฉtricas metrics_list = ['min', 'mean', 'median', 'max', 'std'] tempo_tec.agg({'tempo_tec': metrics_list}) # + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 8, "status": "ok", "timestamp": 1639406175962, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="fsAIuN4qNHsO" outputId="d2320288-9aa0-4a00-c92f-94d570d3552f" # Quantis tempo_tec["tempo_tec"].quantile([.01, .05, .1, .25, .5, .75, .9, .95, .99]) # + colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"elapsed": 312, "status": "ok", "timestamp": 1639411517501, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="fXVrh8I6QY2g" outputId="11aa3169-e650-4529-963b-ef1f27901106" classes = pd.cut(x = tempo_tec.tempo_tec, bins = [0, 30, 90, 180, 360, 720, 1621], labels = ['00a01', '01a03','03a06', '06a12', '12a24', '>24']) tempo_tec['tem_tec_classe'] = classes tempo_tec # + colab={"base_uri": "https://localhost:8080/", "height": 385} executionInfo={"elapsed": 9, "status": "ok", "timestamp": 1639407223944, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="dhToR1tmN4Rk" outputId="2ff72fc7-e72c-44b1-974c-f0427a2aa368" import altair as alt alt.Chart(tempo_tec).mark_bar().encode( alt.X('tem_tec_classe', title = 'Permanรชncia do tรฉcnico (em meses)', #bin = alt.Bin(extent = [0, 100], step = 2) ), alt.Y('count()', title = 'Frequรชncia')) # + [markdown] id="o2BaunCFdQdk" # # Qual o nรบmero de dias que um tรฉcnico fica em um time POR TIME? # + colab={"base_uri": "https://localhost:8080/", "height": 425} executionInfo={"elapsed": 256, "status": "ok", "timestamp": 1639407411128, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="kHcJkR4YdYaM" outputId="c4df2148-7586-4980-9e2a-3b223e3d738d" #tempo = tempo_tec.replace("days", "") tempo_time = tempo_tec.groupby('time').agg({"tempo_tec":['min','mean', 'max']}).round(2) tempo_time#.sort_values(by = "min") # + [markdown] id="i0GMYPijdd68" # # Hรก relaรงรฃo entre a demissรฃo de um tรฉcnico e o tempo que ele estรก no time? # + colab={"base_uri": "https://localhost:8080/", "height": 387} executionInfo={"elapsed": 571, "status": "ok", "timestamp": 1639411587895, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="BHxq-sGVJfsy" outputId="b6a63d6d-df23-4b32-9782-caf7c7151a6e" import seaborn as sns sns.catplot(data = tempo_tecnico, x = 'demissao', y = 'tempo_tec') # + colab={"base_uri": "https://localhost:8080/", "height": 279} executionInfo={"elapsed": 332, "status": "ok", "timestamp": 1639411755277, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="Ro3I66TlT3Az" outputId="14d743f0-09db-4f2e-e417-7d18b56b0a2b" from matplotlib import pyplot as plt ax = sns.boxplot(x = "demissao", y = "tempo_tec", #col = "demissao", data = tempo_tecnico) # RUN PLOT plt.show() plt.clf() plt.close() # + [markdown] id="pVOKmIcFdnRG" # # Hรก relaรงรฃo entre a demissรฃo de um tรฉcnico e o nรบmero de derrotas acumuladas no campeonato (total)? # + colab={"base_uri": "https://localhost:8080/", "height": 279} executionInfo={"elapsed": 427, "status": "ok", "timestamp": 1639411976696, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="SifII8D1R-zH" outputId="9d9674bd-cc94-47e9-f5be-7f4a225330cf" from matplotlib import pyplot as plt ax = sns.boxplot(x = "demissao", y = "der_acum_tot", #col = "demissao", data = dados) # RUN PLOT plt.show() plt.clf() plt.close() # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 312, "status": "ok", "timestamp": 1639412151662, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="FfcZIV-ulAtW" outputId="ac9709b3-408c-4494-cdba-1d51184dec42" metrics_list = ['min', 'mean', 'median', 'max', 'std'] dados.query('demissao == 0').agg({'der_acum_tot': metrics_list}) # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 289, "status": "ok", "timestamp": 1639412166217, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="iKXzFkQwlE1Q" outputId="e6a0d21d-f005-4c1a-9556-7ea9c9ea0d5c" dados.query('demissao == 1').agg({'der_acum_tot': metrics_list}) # + [markdown] id="qRiwFOSdduMm" # # Hรก relaรงรฃo entre a demissรฃo de um tรฉcnico e o nรบmero de derrotas nos รบltimos 5 jogos? # + colab={"base_uri": "https://localhost:8080/", "height": 279} executionInfo={"elapsed": 311, "status": "ok", "timestamp": 1639412019980, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="ggSFJbbsSBBl" outputId="a808c691-9758-4c29-8c4d-e0cdb3a16fb1" ax = sns.boxplot(x = "demissao", y = "der_acum_ult5", #col = "demissao", data = dados) # RUN PLOT plt.show() plt.clf() plt.close() # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 424, "status": "ok", "timestamp": 1639412100476, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="vqlE8AcvkrRr" outputId="246839e7-12ef-474b-8896-6ccdc6301d3b" metrics_list = ['min', 'mean', 'median', 'max', 'std'] dados.query('demissao == 0').agg({'der_acum_ult5': metrics_list}) # + colab={"base_uri": "https://localhost:8080/", "height": 205} executionInfo={"elapsed": 339, "status": "ok", "timestamp": 1639412116544, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjzQGcK2ufV__KxTdNAt_Q676drnxJRe6-8iwjLOEI=s64", "userId": "03270260930185135567"}, "user_tz": 180} id="sXXcOY3Jk5fc" outputId="6ba1c0d8-69a9-4519-9b88-7d99ebb58860" dados.query('demissao == 1').agg({'der_acum_ult5': metrics_list})
SRC/03_descritivas.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (Data Science) # language: python # name: python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0 # --- # %matplotlib inline from matplotlib import pyplot as plt # Download train.csv from https://www.kaggle.com/c/boston-housing/ import pandas as pd import os from os.path import expanduser print(os.curdir) SRC_PATH = expanduser("~") + '/congenial-broccoli/boston-housing/' print(SRC_PATH) #housing_df = pd.read_csv(SRC_PATH + 'train.csv') #housing_df.head() column_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'] housing_df = pd.read_csv(SRC_PATH + 'train.csv', header=None, delimiter=r"\s+", names=column_names) # + from sklearn.model_selection import train_test_split training_df, test_df = train_test_split(housing_df, test_size=0.2) training_df.head() training_df.columns # + from sklearn.linear_model import LinearRegression regression = LinearRegression() training_features = ['crim', 'zn', 'indus', 'chas', 'nox', 'rm', 'age', 'dis', 'tax', 'ptratio', 'lstat'] training_features = [x.upper() for x in training_features] print(training_features) model = regression.fit(training_df[training_features], training_df['MEDV']) # - test_df['predicted_medv'] = model.predict(test_df[training_features]) test_df.head() test_df[['MEDV', 'predicted_medv']].plot(kind='scatter', x='MEDV', y='predicted_medv') model.coef_ model.intercept_ # + from sklearn.metrics import r2_score r2_score(test_df['MEDV'], test_df['predicted_medv']) # -
boston-housing/train_scikit.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="G7Xw7PNA7iqp" # **Mini Project 2 - Students Performance by <NAME>** # + [markdown] id="TJ5LNLOV7zK0" # In this project, the data collected from 9 week long online ML course which is hosted on the online learning management system Moodle will be used for developing ML algorithms. # + id="MWh-BN0v8zA5" #importing the necessary libraries import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from sklearn import model_selection from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="Ay_UAdTu7qQd" outputId="2d0f682a-b063-4a4c-fedb-bb3c69d7a7b3" #load csv file df_grades = pd.read_csv('MP2_Data.csv') df_grades.head() # + [markdown] id="pMLNM3Ul9U_q" # # Part 1 โ€“ Data Processing # + [markdown] id="gANg8f8h9fPj" # There is no need to keep ids for ML model, hence the id column is dropped. # + id="fjG5ZBsq9eA-" df_grades.drop('ID', axis=1, inplace=True) # + [markdown] id="M9TmqSi8-Eyh" # It will be checked if there any missing values or not # + colab={"base_uri": "https://localhost:8080/"} id="QlMujHcv-KIM" outputId="5b69d7d3-1ca2-45f0-bd97-4018016aa857" df_grades.isnull().any() # + [markdown] id="IKgjXHOk-zuJ" # There is no missing values. However, it should be checked for if there is a column with all values are the same. # + colab={"base_uri": "https://localhost:8080/"} id="2fyfJzNs_uVX" outputId="9aba0f5f-29f5-4036-a23a-8502b6aa3ab6" uniques = df_grades.apply(lambda x: x.nunique()) #calculates the number of unique values uniques # + [markdown] id="jKX7C-kBAO81" # All values are the same in Week1_Stat1, there is no need to have it in our data so it is dropped. # + id="n9knYC1IAdUH" df_grades.drop('Week1_Stat1', axis=1, inplace=True) # + [markdown] id="S1H1CwPcmmrq" # There are two target values in the datasets, one is Week8_Total and the other is Grade. Since the grade is calculated by Week8_Total, it should not be included as a feature. Otherwise, the model can predict the student's grade by only checking Week8_Total feature. Hence, Week8_Total is dropped and only grade is used for target. # + id="Fpaoz58EmnsU" df_grades.drop('Week8_Total', axis=1, inplace=True) # + [markdown] id="WcxmmlsEAtui" # Now, we can get info about the dataframe which will be used for machine learning # + colab={"base_uri": "https://localhost:8080/"} id="7QWUzWeGAnVG" outputId="6c3721ae-b94b-4472-8612-74e5567994a0" df_grades.info() # + [markdown] id="CpVqKTb4A4gA" # # Part 2 โ€“ Training & Test Dataset # + id="FGx7ErvsM4hb" df_x = df_grades.drop('Grade', axis=1) # these are features df_y = df_grades['Grade'] # this is the target (what we want to predict) # + id="CyYq0HosNzQv" # This will create train and test datasets from the original dataset that we have where # 75% of original dataframe will be train set and 25% of it will be test set to evaluate the model X_train, X_test, y_train, y_test = train_test_split(df_x, df_y, random_state=42, test_size=0.25) # + colab={"base_uri": "https://localhost:8080/"} id="UgHpjoNcOxOZ" outputId="84e878f7-cd4e-4a51-b8d5-e90465eaa367" print("Shape of Train Dataset: " + str(X_train.shape)) print("Shape of Test Dataset: " + str(X_test.shape)) # + [markdown] id="WJ4MSVyoPUWr" # # Part 3 โ€“ Train the Model # + [markdown] id="O_rwsQq-PY6V" # ## 1) Random Forest # + colab={"base_uri": "https://localhost:8080/"} id="N2nfT_apPdXG" outputId="5284e077-085a-462a-87f8-5bb4f3a03b92" # Load scikit's random forest classifier library from sklearn.ensemble import RandomForestClassifier RF_model = RandomForestClassifier(n_estimators=10,n_jobs=2, random_state=0).fit(X_train, y_train) RF_model # + colab={"base_uri": "https://localhost:8080/"} id="1bRahIwRQfWY" outputId="04171a31-eb12-493e-a43d-3189b9f293cf" score = RF_model.score(X_train, y_train) print("Random Forest Train Score:",str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/"} id="I6yUb22tQrAi" outputId="6bf70313-a872-4ad4-b184-c6b5976bda90" predictions = RF_model.predict(X_train) print(classification_report(y_train,predictions)) # + [markdown] id="hGgFN5pLQzPC" # Testing # + colab={"base_uri": "https://localhost:8080/"} id="TUyiGZroQ0cE" outputId="fe6870e9-c0b3-49f0-da83-6da836c71692" score = RF_model.score(X_test, y_test) print("Random Forest Test Score:", str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/"} id="fed568vLQ_rc" outputId="7654b8fa-c8b8-4859-dd2c-d63acb0a10b8" predictions = RF_model.predict(X_test) print(classification_report(y_test,predictions)) # + colab={"base_uri": "https://localhost:8080/"} id="pK4FFtNpRHVv" outputId="c007ba0d-ac9b-49d5-cc4a-1f91177bcb05" print(confusion_matrix(y_test, predictions)) # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="Cj_7dtxuRTsJ" outputId="3f58c50a-a724-4624-d8fc-10131edc2101" #Create a confusion Matrix pd.crosstab(y_test, predictions, rownames=['Actual Grades'], colnames=['Predicted Grades']) # + [markdown] id="AY7tss-ZSz2D" # ## 2) k-NN # + colab={"base_uri": "https://localhost:8080/"} id="-hMf56vxS2o0" outputId="e55fd870-731e-4893-c7d1-565e0c675241" from sklearn import neighbors knn = neighbors.KNeighborsClassifier(n_neighbors=3) #Fitting the training set knn.fit(X_train, y_train) knn # + colab={"base_uri": "https://localhost:8080/"} id="dmRz463UTk79" outputId="e2eab748-422f-48f5-8562-a710ae8cda5b" score = knn.score(X_train, y_train) print("Training score of kNN:", str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/"} id="xTv7sSJwTq0Q" outputId="a9c5ac09-dc47-4e44-afa1-2c12d4599f17" score = knn.score(X_test, y_test) print("Test score of kNN:",str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="pk8WMftyUn9m" outputId="e1a4db20-c9f3-4f75-98a4-ffc8da6add37" #Create a confusion Matrix predictions = knn.predict(X_test) pd.crosstab(y_test, predictions, rownames=['Actual Grades'], colnames=['Predicted Grades']) # + [markdown] id="02bhqZQHudrs" # ## 3) Decision Tree # + colab={"base_uri": "https://localhost:8080/"} id="zU4U7U0vug7L" outputId="5ea8042d-8e6f-43f3-c81b-67381b368a8f" from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn import tree dtree = DecisionTreeClassifier() #Fitting the training set dtree.fit(X_train, y_train) dtree # + colab={"base_uri": "https://localhost:8080/"} id="swZHZnVwu_Bp" outputId="b13f06bd-eba6-45b0-e28f-7b182ce23684" score = dtree.score(X_train, y_train) print("Training score of Decision Tree:", str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="j9i3aEYfz9KC" outputId="b364edd7-75e3-43bb-80c0-28647a30cd8f" #Create a confusion Matrix predictions = dtree.predict(X_train) pd.crosstab(y_train, predictions, rownames=['Actual Grades'], colnames=['Predicted Grades']) # + colab={"base_uri": "https://localhost:8080/"} id="rLpL5lO7vDav" outputId="debf7ce2-b12f-4e45-8f7e-053359a8e6b1" score = dtree.score(X_test, y_test) print("Test score of Decision Tree:",str(round(score,3))) # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="AVAHbppavIIs" outputId="42e9da4c-2d04-4126-a40f-efa88ef90802" #Create a confusion Matrix predictions = dtree.predict(X_test) pd.crosstab(y_test, predictions, rownames=['Actual Grades'], colnames=['Predicted Grades']) # + colab={"base_uri": "https://localhost:8080/", "height": 683} id="eMP-yiWnwZWG" outputId="7692fd38-5212-4b88-b7af-dc64d893917b" from matplotlib import pyplot as plt fig = plt.figure(figsize=(15,12)) _ = tree.plot_tree(dtree, feature_names=list(X_train.columns), class_names=["0","2","3","4","5"], filled=True) # + [markdown] id="9eCgcrQWX-pb" # ## Why Random Forest is better than kNN? # + [markdown] id="kuMvXfmWYFVL" # Students grade data is high dimensional (45 dimensions) and has a small number of samples (107 samples). # # kNN is effective when there is a large number of training samples but in this problem there is not much data. On the other hand, Random Forest can handle high dimensional spaces very well and can have good results even if the number of samples is not high. # # + [markdown] id="WMN4yk82321G" # ## Why Decision Tree is the best model for this problem? # + [markdown] id="VMHAYrQk3-6t" # The reason why Decision Tree is the best model for this problem is that there are too many features and some of them are much important than the others. Since random forest selecting the features randomly, it uses the features with has very low importance. On the other hand, the decision tree chooses only the most important features and fits the data better and as a result has a higher accuracy than random forest. # + [markdown] id="9IATuon6ZrF-" # # Part 4 โ€“ Performance Evaluation # + [markdown] id="RXbNqhZSvaxf" # Random Forest could be generated any number of trees, to decided how many trees should be used the model has been developed again and again with different number of trees. It is seen that the best result is with 15 trees, and using less then 10 trees could cause a low accuracy. # + id="HG0KoMBZ4f45" colab={"base_uri": "https://localhost:8080/", "height": 404} outputId="3a1e4001-6a17-464f-ce4a-d374e075f64a" from sklearn.metrics import accuracy_score accuracy_list_test=[] n_estimators=[5,7,9,10,13,15,18,21,24] for n in n_estimators: new_model = RandomForestClassifier(n_estimators=n,n_jobs=2, random_state=0) new_model.fit(X_train, y_train) predicted_values_test=new_model.predict(X_test) accuracy_list_test.append(accuracy_score(y_test, predicted_values_test)) plt.figure(figsize=(12, 6)) plt.plot(n_estimators, accuracy_list_test, color='green', linestyle='dashed', marker='o',markerfacecolor='blue', markersize=10, label="test_accuracy") plt.title('Test Accuracy vs # of trees') plt.xlabel('Number of Trees') plt.ylabel('Accuracy') plt.legend(loc="upper right") plt.show() # + [markdown] id="8r0p5vrEwl2F" # Another study has done for k-NN algorithm and for its number of neighbors. Using 1 or 3 neighbors leads to around 0.6 accuracy and using 5 or more is leading around 0.52 accuracy. # + colab={"base_uri": "https://localhost:8080/", "height": 404} id="7UP8Ml-rtJq_" outputId="a14902bf-5767-429a-f21a-6beb9cda36bb" accuracy_list_test=[] neighbors_=[1,3,5,7,9] for n in neighbors_: new_model = neighbors.KNeighborsClassifier(n_neighbors=n) new_model.fit(X_train, y_train) predicted_values_test=new_model.predict(X_test) accuracy_list_test.append(accuracy_score(y_test, predicted_values_test)) plt.figure(figsize=(12, 6)) plt.plot(neighbors_, accuracy_list_test, color='red', linestyle='dashed', marker='o',markerfacecolor='blue', markersize=10, label="test_accuracy") plt.title('Test Accuracy vs # of neighbors') plt.xlabel('Number of neighbors') plt.ylabel('Accuracy') plt.legend(loc="upper right") plt.show() # + [markdown] id="29B_ln6hajGM" # #Part 5 โ€“ Important features # + colab={"base_uri": "https://localhost:8080/"} id="s2-JrFouavZa" outputId="04534947-f696-4403-ca0f-f90ffa383900" from matplotlib import pyplot # get importance importance = RF_model.feature_importances_ #to be ploted feature_importance = [] # summarize feature importance for i in range(len(importance)): feature_importance.append((list(X_train.columns)[i],importance[i])) feature_importance # + colab={"base_uri": "https://localhost:8080/"} id="bdjexAyP7Y40" outputId="51811f5b-04e2-4aae-8502-1d3ed5401db0" #only the features which importance value is higher than 0.04 feature_importance_tops = [] for i in range(len(importance)): if importance[i] > 0.04: feature_importance_tops.append((list(X_train.columns)[i],importance[i])) feature_importance_tops # + colab={"base_uri": "https://localhost:8080/", "height": 320} id="QQxFCk2Z5nyW" outputId="398b395c-7bfe-46d4-97e5-851e994671f0" # plot feature importance plt.bar(range(len(feature_importance_tops)), [val[1] for val in feature_importance_tops], align='center') plt.xticks(range(len(feature_importance_tops)), [val[0] for val in feature_importance_tops]) plt.xticks(rotation=70) plt.show() # + [markdown] id="QLUhiBSG8f-A" # The most important three features are Week7_MP3, Week5_MP2 and Week4_Stat0. It was expected since Mini Project 2 and Mini Project 3 are the assignments with the highest effect on total grade.
Students Performance ML/Project_codes_melihkurtaran.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python3.9 # language: python # name: python3 # --- # # Bounding boxes # # Every word in the corpus has bounding box information stored in the features # `boxl`, `boxt`, `boxr`, `boxb`, which store the coordinates of the left, top, right, bottom boundaries. # # For top en bottom, they are the $y$-coordinates, and for left and right they are the $x$ coordinates. # # The origin is the top left of the page. # # The $x$ coordinates increase when going to the right, the $y$ coordinates increase when going down. # # We show what you can do with this information. from tf.app import use # We load version `0.4`. A = use("among/fusus/tf/Lakhnawi:clone", version="0.4", writing="ara", hoist=globals()) # # Multiple words in one box # # In version 0.4 the following was the case: # # When words are not separated by space, but by punctuation marks, they end up in one box. # # So, some words have exactly the same bounding box. # # Let's find them. # # It turns out that Text-Fabric search has a primitive that comes in handy: we can compare features # of different nodes. # # We search in each line, look for two adjacent words with the same left and right edges. templateMultiple = """ line w1:word < w2:word w1 .boxr. w2 w1 .boxl. w2 """ results = A.search(templateMultiple) A.table(results, start=1, end=10) # What if we also stipulate that the two words are adjacent, in the sense that they occupy subsequent slots? # # If more than two words occupy the same bounding box, we should get less results. templateAdjacent = """ line w1:word <: w2:word w1 .boxr. w2 w1 .boxl. w2 """ results = A.search(templateAdjacent) A.table(results, start=1, end=10) # However, from version 0.5 we have split words in an earlier stage, keeping a good connection between the words and # their bounding boxes. # # Let's load that version of the TF data and repeat the queries. A = use("among/fusus/tf/Lakhnawi:clone", version="0.5", writing="ara", hoist=globals()) results = A.search(templateMultiple) # That's better!
notebooks/Lakhnawi/boxes.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 # --- # # Configure The Physical Device # # In notebook, we configure a device as the IoT edge device. We use a NC6 Ubuntu Linux VM as the edge device, which is the same Linux VM where you run the current notebook. The goal is to configure the edge device so that it can run [Docker](https://docs.docker.com/v17.12/install/linux/docker-ee/ubuntu), [nvidia-docker](https://github.com/NVIDIA/nvidia-docker), and [IoT Edge runtime](https://docs.microsoft.com/en-us/azure/iot-edge/how-to-install-iot-edge-linux). If another device is used as the edge device, instructions need to be adjusted accordingly. # # + # %reload_ext autoreload # %autoreload 2 # %matplotlib inline import time from dotenv import set_key, get_key, find_dotenv # - # get the .env file where all the variables are stored env_path = find_dotenv(raise_error_if_not_found=True) # get previously stored variables device_connection_string = get_key(env_path, 'device_connection_string') # ### Install az-cli iot extension # accounts = !az account list --all -o tsv if "Please run \"az login\" to access your accounts." in accounts[0]: # !az login -o table else: print("Already logged in") # install az-cli iot extension # !az extension add --name azure-cli-iot-ext # ### Register Microsoft key and software repository feed # # Prepare your device for the IoT Edge runtime installation. # Install the repository configuration. Replace <release> with 16.04 or 18.04 as appropriate for your release of Ubuntu. # release = !lsb_release -r release = release[0].split('\t')[1] print(release) # !curl https://packages.microsoft.com/config/ubuntu/$release/prod.list > ./microsoft-prod.list # Copy the generated list. # !sudo cp ./microsoft-prod.list /etc/apt/sources.list.d/ #Install Microsoft GPG public key # !curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg # !sudo cp ./microsoft.gpg /etc/apt/trusted.gpg.d/ # ### Install the Azure IoT Edge Security Daemon # # The IoT Edge security daemon provides and maintains security standards on the IoT Edge device. The daemon starts on every boot and bootstraps the device by starting the rest of the IoT Edge runtime. # The installation command also installs the standard version of the iothsmlib if not already present. # Perform apt update. # !sudo apt-get update # Install the security daemon. The package is installed at /etc/iotedge/. # !sudo apt-get install iotedge -y --no-install-recommends # ### Configure the Azure IoT Edge Security # # Configure the IoT Edge runtime to link your physical device with a device identity that exists in an Azure IoT hub. # The daemon can be configured using the configuration file at /etc/iotedge/config.yaml. The file is write-protected by default, you might need elevated permissions to edit it. # Manual provisioning IoT edge device # !sudo sed -i "s#\(device_connection_string: \).*#\1\"$device_connection_string\"#g" /etc/iotedge/config.yaml # restart the daemon # !sudo systemctl restart iotedge time.sleep(20) # Wait 20 seconds for iotedge to restart # restart the daemon again # !sudo systemctl restart iotedge # ### Verify successful installation time.sleep(30) # Wait 30 seconds to let the iotedge daemon stable # check the status of the IoT Edge Daemon # !systemctl status iotedge # Examine daemon logs # !journalctl -u iotedge --no-pager --no-full # When you run `docker ps` command in the edge device, you should see `edgeAgent` container is up running. # !docker ps # Next we will proceed with notebook [031_DevAndRegisterModel.ipynb](031_DevAndRegisterModel.ipynb).
object-detection-azureml/02_IoTEdgeConfig.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 # --- # # Conditional Probability & Bayes Rule Quiz # + # load dataset import pandas as pd import numpy as np df = pd.read_csv('cancer_test_data.csv') df.head() # - # What proportion of patients who tested positive has cancer? df[df.test_result == "Positive"]["has_cancer"].mean() # What proportion of patients who tested positive doesn't have cancer? 1 - df[df.test_result == "Positive"]["has_cancer"].mean() # What proportion of patients who tested negative has cancer? df[df.test_result == "Negative"]["has_cancer"].mean() # What proportion of patients who tested negative doesn't have cancer? 1 - df[df.test_result == "Negative"]["has_cancer"].mean()
Practical Statistics/Probability/conditional_probability_bayes_rule.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 # --- # # Migrating from MySQL to Amazon Neptune using AWS Glue # This demo shows how to migrate relational data from MySQL to Amazon Neptune using AWS Glue. # # The demo uses several different migration techniques: # # - Extract data from MySQL to Amazon S3 as CSV files. Bulk load from the CSV files into Neptune. # - Extract data from MySQL and write it directly to Neptune. # - Incrementally load data from MySQL to Neptune. # # The two data models are shown below. The MySQL database contains details of products, suppliers, orders and customers. The demo shows us migrating products, suppliers and orders data, but not customer data โ€“ though there's no reason it couldn't be expanded to also migrate customer data. We leave that as an exercise for the reader. # # The scripts for the AWS Glue jobs can be found [here](https://github.com/aws-samples/amazon-neptune-samples/tree/master/gremlin/glue-neptune/glue-jobs/). The scripts use the [neptune-python-utils](https://github.com/awslabs/amazon-neptune-tools/tree/master/neptune-python-utils) Python library. # <img src="https://s3.amazonaws.com/aws-neptune-customer-samples/neptune-sagemaker/images/mysql-2-neptune-01.png"/>
gremlin/glue-neptune/notebooks/Introduction.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 # --- # # Bonus: Temperature Analysis I import pandas as pd from datetime import datetime as dt from scipy import stats # "tobs" is "temperature observations" df = pd.read_csv('Resources\hawaii_measurements.csv') df.head() # Convert the date column format from string to datetime df["date"] = pd.to_datetime(df["date"]) df.head() # Set the date column as the DataFrame index df.set_index("date") df.head() # Drop the date column nodate_df = df.reset_index(drop=True) nodate_df.head() # ### Compare June and December data across all years # Filter data for desired months june_df = df.loc[(pd.DatetimeIndex(df['date']).month == 6)] june_df.head() dec_df = df.loc[(pd.DatetimeIndex(df['date']).month == 12)] dec_df.head() june_df_avg_tobs = round(june_df["tobs"].mean(),2) june_df_avg_tobs # Identify the average temperature for December december_avg_tobs = round(dec_df["tobs"].mean(),2) december_avg_tobs june_bystation_df = june_df.groupby(['station']).mean() june_bystation_df dec_bystation_df = dec_df.groupby(['station']).mean() dec_bystation_df # Create collections of temperature data # Run paired t-test paired_t = stats.ttest_rel(june_bystation_df.tobs, dec_bystation_df.tobs) paired_t unpaired_t = stats.ttest_ind(june_df.tobs, dec_df.tobs) unpaired_t # ### Analysis # + active="" # paired ttest: p-value for June & December temperatures across all stations is significantly low. # unpaired ttest: p-value for June & December temperatures across all stations is at 3.906 # # Both tests conclude that statistically the difference is significant.
temp_analysis_bonus_1_starter.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 # --- # After downloading, install unrar on your computer # $ sudo apt-get install unrar # Unrar data # # + import os path2data = "./data" sub_folder = "hmdb51_org" sub_folder_jpg = "hmdb51_jpg" path2aCatgs = os.path.join(path2data, sub_folder) listOfCategories = os.listdir(path2aCatgs) listOfCategories, len(listOfCategories) # - for cat in listOfCategories: print("category:", cat) path2acat = os.path.join(path2aCatgs, cat) listOfSubs = os.listdir(path2acat) print("number of sub-folders:", len(listOfSubs)) print("-"*50) import myutils extension = ".avi" n_frames = 16 for root, dirs, files in os.walk(path2aCatgs, topdown=False): for name in files: if extension not in name: continue path2vid = os.path.join(root, name) frames, vlen = myutils.get_frames(path2vid, n_frames= n_frames) path2store = path2vid.replace(sub_folder, sub_folder_jpg) path2store = path2store.replace(extension, "") print(path2store) os.makedirs(path2store, exist_ok= True) myutils.store_frames(frames, path2store) print("-"*50)
Chapter10/prepare_data.ipynb
(* -*- coding: utf-8 -*- (* --- *) (* jupyter: *) (* jupytext: *) (* text_representation: *) (* extension: .ml *) (* format_name: light *) (* format_version: '1.5' *) (* jupytext_version: 1.14.4 *) (* kernelspec: *) (* display_name: OCaml *) (* language: ocaml *) (* name: iocaml *) (* --- *) (* + [markdown] deletable=true editable=true (* <h1> Assiettes cassรฉes </h1> *) (* *) (* <h2> Prรฉsentation </h2> *) (* Cinq plongeurs lavent le mรชme nombre d'assiettes. Si cinq assiettes sont cassรฉes: *) (* <ul> *) (* <li> quelle est la probabilitรฉ qu'un mรชme plongeur en ait cassรฉ quatre ? *) (* <li> quelle est la probabilitรฉ qu'il ait cassรฉ les cinq assiettes ? *) (* <li> quelle est la probabilitรฉ qu'un plongeur donnรฉ ait cassรฉ quatre assiettes ? *) (* <li> quelle est la probabilitรฉ qu'un plongeur donnรฉ ait cassรฉ cinq assiettes ? *) (* </ul> *) (* *) (* Trouver ces probabilitรฉs de faรงon analytique; puis les retrouver de faรงon numรฉrique en effectuant des simulations. *) (* + deletable=true editable=true open Random;; Random.self_init;; let array_mem cible array = let trouve = ref false in let i = ref 0 in while not !trouve && !i < Array.length array do if array.(!i)=cible then trouve :=true; incr i; done; !trouve;; (* + deletable=true editable=true let assiette() = "ร  complรฉter" (* + let essais nbre_essais = "ร  complรฉter" (* proba4 proba qu'un mรชme serveur casse 4 assiettes proba5 proba qu'un mรชme serveur casse 5 assiettes proba4b proba qu'un serveur donnรฉ casse 4 assiettes proba5b proba qu'un serveur donnรฉ casse 5 assiettes *) let p4,p5,p4b,p5b = essais (100*1000);; print_string("probabilitรฉ qu'un mรชme serveur casse 4 assiettes "^string_of_float(p4*.100.)^" %\n"); print_string("probabilitรฉ qu'un mรชme serveur casse 5 assiettes "^string_of_float(p5*.100.)^" %\n"); print_string("probabilitรฉ qu'un serveur donnรฉ casse 4 assiettes "^string_of_float(p4b*.100.)^" %\n"); print_string("probabilitรฉ qu'un serveur donnรฉ casse 5 assiettes "^string_of_float(p5b*.100.)^" %\n"); (* + let loop start stop acc op = (* itรจre de start ร  stop compris *) "ร  coplรฉter";; let combinatoire k n= (*k parmi n*) "ร  coplรฉter";; let p4b,p5b=4.*.float_of_int (combinatoire 4 5)/.(5.**5.),float_of_int (combinatoire 5 5)/.5.**5.;; let p4,p5=5.*.p4b,5.*.p5b;; print_string("probabilitรฉ qu'un mรชme serveur casse 4 assiettes "^string_of_float(p4*.100.)^" %\n"); print_string("probabilitรฉ qu'un mรชme serveur casse 5 assiettes "^string_of_float(p5*.100.)^" %\n"); print_string("probabilitรฉ qu'un serveur donnรฉ casse 4 assiettes "^string_of_float(p4b*.100.)^" %\n"); print_string("probabilitรฉ qu'un serveur donnรฉ casse 5 assiettes "^string_of_float(p5b*.100.)^" %\n"); (* + deletable=true editable=true
Assiettes_cassees/Assiettes_cassees_OCaml_sujet.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 # --- import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, neighbors # + from matplotlib.colors import ListedColormap def knn_comparison(data, n_neighbors = 15): ''' This function finds k-NN and plots the data. ''' X = data[:, :2] y = data[:,2] # grid cell size h = .02 cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#0000FF']) # the core classifier: k-NN clf = neighbors.KNeighborsClassifier(n_neighbors) clf.fit(X, y) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # we create a mesh grid (x_min,y_min) to (x_max y_max) with 0.02 grid spaces xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # we predict the value (either 0 or 1) of each element in the grid Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # xx.ravel() will give a flatten array # np.c_ : Translates slice objects to concatenation along the second axis. # > np.c_[np.array([1,2,3]), np.array([4,5,6])] # > array([[1, 4], # [2, 5], # [3, 6]]) (source: np.c_ documentation) # convert the out back to the xx shape (we need it to plot the decission boundry) Z = Z.reshape(xx.shape) # pcolormesh will plot the (xx,yy) grid with colors according to the values of Z # it looks like decision boundry plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # scatter plot of with given points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) #defining scale on both axises plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) # set the title plt.title('K value = '+str(n_neighbors)) plt.show() # - # ### Meshgrid explanation # ![title](demo_data/meshgrid_image.png) # please check this link <a href='https://stackoverflow.com/a/36014586'> stackoverflow meshgrid explanation </a> data = np.genfromtxt('demo_data/6.overlap.csv', delimiter=',') knn_comparision(data, 1) knn_comparison(data, 5) knn_comparison(data,15) knn_comparison(data, 30) knn_comparison(data, 50) data = np.genfromtxt('demo_data/1.ushape.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data,15) knn_comparison(data,30) data = np.genfromtxt('demo_data/2.concerticcir1.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data,15) knn_comparison(data,30) data = np.genfromtxt('demo_data/3.concertriccir2.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data, 15) data = np.genfromtxt('demo_data/4.linearsep.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data) data = np.genfromtxt('demo_data/5.outlier.csv', delimiter=',') knn_comparison(data,1) knn_comparison(data,5) knn_comparison(data) data = np.genfromtxt('demo_data/7.xor.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data) data = np.genfromtxt('demo_data/8.twospirals.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data) data = np.genfromtxt('demo_data/9.random.csv', delimiter=',') knn_comparison(data, 1) knn_comparison(data, 5) knn_comparison(data)
Section 5/KNN/teclov_knn.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 os.path as osp import sys from glob import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch sys.path.append("../src") from architecture_utils import LinearNet from main_low_rank_regression import calc_effective_rank def get_values_from_list_of_dict(d_list, key): return [d[key] for d in d_list] # - # Load input_dir = osp.join("../output", "low_rank_regression_20210630_105640") # low_rank_regression_20210630_151441 bottelneck csv_path = osp.join(input_dir, "results.csv") df = pd.read_csv(csv_path) df.head() theta_star = torch.load(osp.join(input_dir, "theta_star.pth")) theta_star_norm = torch.norm(theta_star) x_train, y_train, x_test, y_test = torch.load(osp.join(input_dir, "dataset.pth")) weight_dicts = [] for i, row in df.iterrows(): n_train = row["n_train"] net = LinearNet( input_size=row["input_size"], output_size=row["output_size"], intermediate_sizes=eval(row["intermediate_sizes"]), ) net.load_state_dict( torch.load(osp.join(input_dir, "net_n_train={}.pth".format(n_train))) ) weights = [layer.weight for layer in net.layers] w = weights[-1] weights_to_mul = weights[:-1] for w_i in weights_to_mul[::-1]: w = w @ w_i theta_mn = torch.tensor(eval(row["theta_mn"])) weight_dict = { "w": w, "norm": torch.norm(w), "mn_norm": torch.norm(theta_mn), "n_train": row["n_train"], "effective_ranks": [ calc_effective_rank(torch.linalg.svd(w_i)[1]).item() for w_i in weights ], "weights": weights, } weight_dicts.append(weight_dict) # + n_trains = get_values_from_list_of_dict(weight_dicts, "n_train") norms = get_values_from_list_of_dict(weight_dicts, "norm") mn_norms = get_values_from_list_of_dict(weight_dicts, "mn_norm") fig, ax = plt.subplots(1, 1) ax.plot(n_trains, norms, label="Effective net", marker=".", alpha=0.75) ax.plot(n_trains, mn_norms, label="MN", marker="*", alpha=0.75) ax.plot(n_trains, [theta_star_norm] * len(n_trains), marker=".", label="GT", alpha=0.75) ax.axvline(df.input_size[0], label="M=N", color="black", linestyle="--", linewidth=0.75) # ax.set_yscale('log') ax.set_xlabel("Training set size") ax.set_ylabel("Norm value") ax.grid() ax.legend() plt.tight_layout() plt.show() # + fig, ax = plt.subplots(1, 1) for n, weight_dict in enumerate(weight_dicts[::3]): ax.plot( weight_dict["effective_ranks"], "-", marker=".", label="N={}".format(weight_dict["n_train"]), ) ax.legend() ax.set_xlabel("Layer") ax.set_ylabel("Effective rank") ax.grid() plt.tight_layout() plt.show() for i, weight in enumerate(weights): plt.plot(torch.svd(weight)[1].detach().numpy(), "-", marker=".", label=f"Layer {i}") plt.xlabel("Singular value index") plt.xlabel("Singular value energy") plt.xscale("symlog") plt.yscale("log") plt.legend() plt.tight_layout() plt.grid() plt.show() # + fig, axs = plt.subplots(2, 1, sharex=True) ax = axs[0] ax.plot(df.n_train, df.mse_train_mn, label="MN") ax.plot(df.n_train, df.mse_train_net, label="net") ax.axvline(df.input_size[0], label="M=N", color="black", linestyle="--", linewidth=0.5) ax.set_ylabel("Train MSE") ax.set_yscale("log") ax.grid() ax.legend() ax = axs[1] ax.plot(df.n_train, df.mse_test_mn, label="MN") ax.plot(df.n_train, df.mse_test_net, label="net") ax.axvline(df.input_size[0], label="M=N", color="black", linestyle="--", linewidth=0.5) ax.set_ylabel("Test MSE") ax.set_xlabel("Training set size") ax.set_yscale("log") ax.grid() plt.tight_layout() plt.show() # - # ## Reconstructing th net # + x_train_i, y_train_i = x_train[:n_train].double(), y_train[:n_train].double() net.double() y_hat = x_test @ w.T.double() mse_net_test = torch.mean((y_hat - y_test) ** 2).item() features = [] feature_l = x_train_i for layer in net.layers: feature_l = layer(feature_l) features.append(feature_l.clone()) for feature_l in features: print(feature_l.shape) print("reconstructing theta") thetas = [] features.insert(0, x_train_i) features[-1] = y_train_i for l in range(1, len(features)): x_tilde = features[l - 1] y_tilde = features[l] theta_l = torch.linalg.inv(x_tilde.T @ x_tilde) @ x_tilde.T @ y_tilde print(theta_l.shape) thetas.append(theta_l) # - theta_effective = thetas[0] theta = thetas[-1].T thetas_to_mul = thetas[:-1] for theta_l in thetas_to_mul[::-1]: theta = theta @ theta_l.T theta = theta.T # + y_hat = x_test @ theta mse_net_reconstructed_test = torch.mean((y_hat - y_test) ** 2).item() y_hat = x_test @ torch.linalg.inv(x_train_i.T @ x_train_i) @ x_train_i.T @ y_train_i mse_mn = torch.mean((y_hat - y_test) ** 2).item() mse_net_reconstructed_test, mse_net_test, mse_mn # - for i, theta_l in enumerate(thetas): plt.plot( torch.svd(theta_l)[1].detach().numpy(), "-", marker=".", label=f"Layer {i}" ) # for i, weight in enumerate(weights): # plt.plot(torch.svd(weight)[1].detach().numpy(), "-", marker=".", label=f"Layer {i}") plt.xlabel("Singular value index") plt.xlabel("Singular value energy") plt.xscale("symlog") plt.yscale("log") plt.legend() plt.tight_layout() plt.grid() plt.show()
notebooks/low_rank_net_regression.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 # --- # # Comentarios # + #Este es mi primer codigo # - ''' Este es un codigo en bloque para escribir lo que quiera ''' var = 2 # # Variables var1 = 1 var2 = 5.5 var3 = "Hola" var4 = "clase de Python" type(var1) type(var3) saludo = var3 + ' ' + var4 saludo var1 + var2 var1 + var3 #Presentara un error porque no se puede operar tipos de variables diferentes var5 = 'adv3 sjvfnglk34567.[' type(var5) print("Esto es un ejemplo de numero: " + str(var2)) print(var2) var6 = '5' int(var6) type(int(var6)) # # Operadores var7 = 'Hola ' var8 = 'mundo' var9 = (var7 * 3) + var8 var9 var9.find("mundo") var9.upper() var9.lower() var9.replace("Hola", "Adios") x = input("Ingrese el valor de x: ")
Sesiones/1-Sesion1.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.7.2 # language: julia # name: julia-1.7 # --- # # Utility Theory # # This notebook summarizes basic utility theory and how it can be used in portfolio optimisation. # ## Load Packages and Extra Functions # + using Printf, LinearAlgebra, Optim #Optim is an optimization package include("jlFiles/printmat.jl") # + using Plots #pyplot(size=(600,400)) gr(size=(480,320)) default(fmt = :png) # - # # Utility Function # The CRRA utility function is $U(x) = \frac{x^{1-\gamma}}{1-\gamma}$ # # ### A Remark on the Code # # 1. A Julia function can be created in several ways. For a simple one-liner, it is enough to do like this: # `MySum(x,y) = x + y` # # 2. If the function `U(x,ฮณ)` is written for a scalar `x` value, then we can calculate its value at each element of a vector `x_range` by using `U.(x_range,ฮณ)`. # + """ U(x,ฮณ) CRRA utility function, ฮณ is the risk aversion. """ U(x,ฮณ) = x^(1-ฮณ)/(1-ฮณ) """ U_1(u,ฮณ) Inverse of CRRA utility function. Solves for x st. U(x,ฮณ) = u. """ U_1(u,ฮณ) = (u*(1-ฮณ))^(1/(1-ฮณ)) # + x_range = range(0.8,1.2,length=25) #possible outcomes ฮณ = 2 p1 = plot( x_range,U.(x_range,ฮณ), #notice the dot(.) linecolor = :red, linewidth = 2, legend = false, title = "Utility function, CRRA, ฮณ = $ฮณ", xlabel = "x" ) display(p1) # - # # Expected Utility # Recall: if $\pi_s$ is the probability of outcome ("state") $x_s$ and there are $S$ possible outcomes, then expected utility is # # $\text{E}U(x) = \sum\nolimits_{s=1}^{S} \pi_{s}U(x_s)$ # # ### A Remark on the Code # # When `x` is a vector, then `U.(x,ฮณ)` is a vector of the corresponding utility values. `dot(ฯ€,U.(x,ฮณ))` calculates the inner product of the two vectors, that is, summing `ฯ€[i]*U(x[i],ฮณ)` across all `i`. """ EU(ฯ€,x,ฮณ) Calculate expected CRRA utility from a vector of outcomes `x` and a vector of their probabilities `ฯ€`. """ EU(ฯ€,x,ฮณ) = dot(ฯ€,U.(x,ฮณ)) #same as sum(ฯ€.*U.(x,ฮณ)) # + ฮณ = 2 #risk aversion (xโ‚,xโ‚‚) = (0.85,1.15) #possible outcomes (ฯ€โ‚,ฯ€โ‚‚) = (0.5,0.5) #probabilities of outcomes stateโ‚ = [xโ‚,U(xโ‚,ฮณ),ฯ€โ‚] #for printing stateโ‚‚ = [xโ‚‚,U(xโ‚‚,ฮณ),ฯ€โ‚‚] printblue("Different states: wealth, utility and probability:\n") printmat([stateโ‚ stateโ‚‚],colNames=["state 1","state 2"],rowNames=["wealth","utility","probability"]) Ex = dot([ฯ€โ‚,ฯ€โ‚‚],[xโ‚,xโ‚‚]) #expected wealth ExpUtil = EU([ฯ€โ‚,ฯ€โ‚‚],[xโ‚,xโ‚‚],ฮณ) #expected utility printmat([Ex,ExpUtil],rowNames=["Expected wealth","Expected utility"]) # - p1 = plot( x_range,U.(x_range,ฮณ), linecolor = :red, linewidth = 2, label = "Utility fn", ylim = (-1.3,-0.7), legend = :topleft, title = "Utility function, CRRA, ฮณ=$ฮณ", xlabel = "x" ) scatter!([xโ‚,xโ‚‚],U.([xโ‚,xโ‚‚],ฮณ),markercolor=:green,label="possible utility outcomes") hline!([ExpUtil],linecolor=:magenta,line=(:dash,1),label="Expected utility") display(p1) # # Certainty Equivalent # The certainty equivalent (here denoted $P$) is the sure value that solves # # $U(P) = \text{E}U(x)$, # # where the right hand side is the expected utility from the random $x$. $P$ is the highest price the investor is willing to pay for "asset" $x$. # # The code below solves for $P$ by inverting the utility function, first for the same $\gamma$ as above, and later for different values of the risk aversion. # # We can think of $\textrm{E}(x)/P-1$ as the expected return on $x$ that the investor requires in order to buy the asset. It is increasing in the risk aversion $\gamma$. # + EU_i = EU([ฯ€โ‚,ฯ€โ‚‚],[xโ‚,xโ‚‚],ฮณ) #expected utility P = U_1(EU_i,ฮณ) #certainty equivalent (inverting the utility fn) p1 = plot( x_range,U.(x_range,ฮณ), linecolor = :red, linewidth = 2, label = "Utility fn", ylim = (-1.3,-0.7), legend = :bottomright, title = "Utility function, CRRA, ฮณ=$ฮณ", xlabel = "x" ) scatter!([xโ‚,xโ‚‚],U.([xโ‚,xโ‚‚],ฮณ),markercolor=:green,label="possible utility outcomes") hline!([ExpUtil],linecolor=:magenta,line=(:dash,1),label="Expected utility") vline!([P],linecolor=:blue,line=(:dash,1),label="certainty equivalent") display(p1) # + ฮณ = [0,2,5,10,25,50,100] #different risk aversions L = length(ฮณ) (P,ERx) = (fill(NaN,L),fill(NaN,L)) for i = 1:L #local EU_i #local/global is needed in script EU_i = EU([ฯ€โ‚,ฯ€โ‚‚],[xโ‚,xโ‚‚],ฮณ[i]) #expected utility with ฮณ[i] P[i] = U_1(EU_i,ฮณ[i]) #inverting the utility fn ERx[i] = Ex/P[i] - 1 #required expected net return end printblue("risk aversion and certainly equivalent (recall: E(wealth) = $Ex):\n") printmat([ฮณ P ERx],colNames= ["ฮณ","certainty eq","expected return"],width=20) # - # # Portfolio Choice with One Risky Asset # In the example below, the investor maximizes $\text{E}\ln (1+R_{p})\text{, with }R_{p}=vR_{i} + (1-v)R_{f}$ by choosing $v$. There are two possible outcomes for $R_{i}$ with equal probabilities. # # This particular problem can be solved by pen and paper, but this becomes very difficult when the number of states increases - and even worse when there are many assets. To prepare for these tricker cases, we apply a numerical optimization algorithm already to this simple problem. # # ### Remark on the Code # # To solve the optimization problem we use `optimize()` from the [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl) package. The key steps are: # # 1. Define a function for expected utility, `EUlog(v,ฯ€,Re,Rf)`. The value depends on the portfolio choice `v`, as well as the properties of the asset (probabilities and returns for different states). # # 2. To create data for the plot, we loop over `v[i]` values and calculate expected utility as `EUlog(v[i],ฯ€,Re,Rf)` where # `ฯ€` and `Re` are vectors of probabilities and returns in the different states, and the riskfree rate `Rf` is the same in all states. (Warning: you can assign a value to `ฯ€` provided you do not use the built-in constant `ฯ€` (3.14156...) first.) # # 3. For the optimization, we minimize the anonymous function `v->-EUlog(v,ฯ€,Re,Rf)`. This is a function of `v` only and we use the negative value since `optimize()` is a *minimization* routine. """ EUlog(v,ฯ€,Re,Rf) Calculate expected utility (log(1+Rp)) from investing into one risky and one riskfree asset v: scalar ฯ€: S vector probabilities of the different states Re: S vector, excess returns of the risky asset in different states Rf: scalar, riskfree rate """ function EUlog(v,ฯ€,Re,Rf) #expected utility, utility fn is logarithmic R = Re .+ Rf Rp = v*R .+ (1-v)*Rf #portfolio return eu = dot(ฯ€,log.(1.0.+Rp)) #expected utility return eu end # + ฯ€ = [0.5,0.5] #probabilities for different states Re = [-0.10,0.12] #excess returns in different states Rf = 0 #riskfree rate v_range = range(-1,1.5,length=101) #try different weights on risky asset L = length(v_range) EUv = fill(NaN,L) for i = 1:L EUv[i] = EUlog(v_range[i],ฯ€,Re,Rf) end p1 = plot( v_range,EUv, linecolor = :red, linewidth = 2, legend = false, title = "Expected utility as a function of v", xlabel = "weight (v) on risky asset" ) display(p1) # + Sol = optimize(v->-EUlog(v,ฯ€,Re,Rf),-1,1) #minimize -EUlog printlnPs("Optimum at: ",Optim.minimizer(Sol)) printred("\nCompare with the figure") # - # # Portfolio Choice with Several Risky Assets # This optimization problem has several risky assets and states and a general CRRA utility function. Numerical optimization is still straightforward. # # ### A Remark on the Code # # The code below is fairly similar to the log utility case solved before, but extended to handle CRRA utility and several assets and states. # # With several choice variables, the call to `optimize()` requires a vector of starting guesses as input. """ EUcrra(v,ฯ€,R,Rf,ฮณ) Calculate expected utility from investing into n risky assets and one riskfree asset v: n vector (weights on the n risky assets) ฯ€: S vector (S possible "states") R: nxS matrix, each column is the n vector of returns in one of the states Rf: scalar, riskfree rate ฮณ: scalar, risk aversion """ function EUcrra(v,ฯ€,R,Rf,ฮณ) S = length(ฯ€) Rp = fill(NaN,S) for i = 1:S #portfolio return in each state Rp[i] = v'R[:,i] + (1-sum(v))*Rf end eu = EU(ฯ€,1.0.+Rp,ฮณ) #expected utility when using portfolio v return eu end # + Re = [-0.03 0.08 0.20; #2 assets, 3 states -0.04 0.22 0.15] #Re[i,j] is the excess return of asset i in state j ฯ€ = [1/3,1/3,1/3] #probs of the states Rf = 0.065 ฮณ = 5 Sol = optimize(v->-EUcrra(v,ฯ€,Re,Rf,ฮณ),[-0.6,1.2]) #minimize -EUcrra v = Optim.minimizer(Sol) printblue("optimal portfolio weights from max EUcrra():\n") printmat([v;1-sum(v)],rowNames=["asset 1","asset 2","riskfree"]) # - # # Mean-Variance and the Telser Criterion # Let $\mu$ be a vector of expected returns and $\Sigma$ be the covariance matrix of the investible assets. # # The Telser criterion solves the problem # # $\max_{v} \text{E}R_{p} \: \text{ subject to} \: \text{VaR}_{95\%} < 0.1$, # # where $\text{E}R_{p} = v'\mu+(1-v)R_f$ is the expected portfolio return. # # If the returns are normally distributed then # # $\text{VaR}_{95\%} = -[\text{E}R_{p} - 1.64\text{Std}(R_p)]$, # # where $\text{Std}(R_p) = \sqrt{v'\Sigma v}$ is the standard deviation of the portfolio return. It follows that the VaR restriction can be written # # $\text{E}R_{p} > -0.1 + 1.64\text{Std}(R_p)$. # # The figure below illustrates that the optimal portfolio is on the CML (when the returns are normally distributed). include("jlFiles/MvCalculations.jl") #functions for traditional MV frontiers # + ฮผ = [9, 6]/100 #means of investable assets ฮฃ = [ 256 0; #covariance matrix 0 144]/10000 Rf = 1/100 ฮผstar_range = range(Rf,0.1,length=101) #required average returns L = length(ฮผstar_range) (ฯƒMVF,ฯƒCML) = (fill(NaN,L),fill(NaN,L)) for i = 1:L ฯƒMVF[i] = MVCalc(ฮผstar_range[i],ฮผ,ฮฃ)[1] #std of MVF (risky only) at ฮผstar ฯƒCML[i] = MVCalcRf(ฮผstar_range[i],ฮผ,ฮฃ,Rf)[1] #std of MVF (risky&riskfree) at ฮผstar end VaRRestr = -0.1 .+ 1.64*ฯƒCML; #the portfolio mean return must be above this # - p1 = plot( [ฯƒCML ฯƒMVF ฯƒCML]*100,[ฮผstar_range ฮผstar_range VaRRestr]*100, linestyle = [:dash :solid :dot], linecolor = [:blue :red :black], linewidth = 2, label = ["CML" "MVF" "VaR restriction"], xlim = (0,15), ylim = (0,10), legend = :topleft, title = "Mean vs std", xlabel = "Std(Rp), %", ylabel = "ERp, %" ) display(p1) # The next few cells shows the explicit solution of Telser problem, assuming normally distributed returns. # # It can be shown (see lecture notes) that the return of the optimal portfolio is # $R_{opt} = vR_T + (1-v)R_f$, # where $R_T$ is the return of the tangency portfolio. The $v$ value is # # $ # \begin{equation} # v=-\frac{R_{f}+V^{\ast}}{c\sigma_{T}+\mu_{T}^{e}}, # \end{equation} # $ # # where $V^{\ast}$ is the VaR restriction (here 0.1) and $c$ is the critical value corresponding to the 1-confidence level of the VaR (here $c=-1.64$ since we use the 95% confidence level). """ TelserSolution(ฮผeT,ฯƒT,Rf,Varstar,c) Calculate v in Rp = v*RT + (1-v)Rf which maximizes the Telser criterion, assuming normally distributed returns and where RT is the return on the tangency portfolio and Rf is the riskfree rate. ฮผeT and ฯƒT are the expected excess return and the standard deviation of the tangency portfolio. See the lecture notes for more details. """ function TelserSolution(ฮผeT,ฯƒT,Rf,Varstar,c) v = - (Rf+Varstar)/(c*ฯƒT+ฮผeT) return v end # + (wT,ฮผT,ฯƒT) = MVTangencyP(ฮผ,ฮฃ,Rf) #tangency portfolio from (ฮผ,ฮฃ) printlnPs("Mean and std of tangency portfolio ",ฮผT,ฯƒT) v = TelserSolution(ฮผT-Rf,ฯƒT,Rf,0.1,-1.64) printblue("\nOptimal portfolio, weight on tangency portfolio and riskfree:") printmat([v,1-v],rowNames=["tangency","riskfree"]) ฮผOpt = v*ฮผT + (1-v)*Rf #mean and std of optimal portfolio ฯƒOpt = abs(v)*ฯƒT printblue("\nMean and std of optimal portfolio:") printlnPs(ฮผOpt,ฯƒOpt) printred("\ncompare with the figure") # -
Ch10_UtilityTheory.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="1_84RVKeEjGl" # # ๋จธ์‹  ๋Ÿฌ๋‹ ๊ต๊ณผ์„œ 3ํŒ # + [markdown] id="3NwHunx5EjGp" # # 5์žฅ - ์ฐจ์› ์ถ•์†Œ๋ฅผ ์‚ฌ์šฉํ•œ ๋ฐ์ดํ„ฐ ์••์ถ• # + [markdown] id="vUWZwyuKEjGp" # **์•„๋ž˜ ๋งํฌ๋ฅผ ํ†ตํ•ด ์ด ๋…ธํŠธ๋ถ์„ ์ฃผํ”ผํ„ฐ ๋…ธํŠธ๋ถ ๋ทฐ์–ด(nbviewer.jupyter.org)๋กœ ๋ณด๊ฑฐ๋‚˜ ๊ตฌ๊ธ€ ์ฝ”๋žฉ(colab.research.google.com)์—์„œ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.** # # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://nbviewer.jupyter.org/github/rickiepark/python-machine-learning-book-3rd-edition/blob/master/ch05/ch05.ipynb"><img src="https://jupyter.org/assets/main-logo.svg" width="28" />์ฃผํ”ผํ„ฐ ๋…ธํŠธ๋ถ ๋ทฐ์–ด๋กœ ๋ณด๊ธฐ</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/rickiepark/python-machine-learning-book-3rd-edition/blob/master/ch05/ch05.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />๊ตฌ๊ธ€ ์ฝ”๋žฉ(Colab)์—์„œ ์‹คํ–‰ํ•˜๊ธฐ</a> # </td> # </table> # + [markdown] id="BKL9EjK2EjGq" # ### ๋ชฉ์ฐจ # + [markdown] id="zgkdYleMEjGq" # - ์ฃผ์„ฑ๋ถ„ ๋ถ„์„์„ ํ†ตํ•œ ๋น„์ง€๋„ ์ฐจ์› ์ถ•์†Œ # - ์ฃผ์„ฑ๋ถ„ ๋ถ„์„์˜ ์ฃผ์š” ๋‹จ๊ณ„ # - ์ฃผ์„ฑ๋ถ„ ์ถ”์ถœ ๋‹จ๊ณ„ # - ์ด๋ถ„์‚ฐ๊ณผ ์„ค๋ช…๋œ ๋ถ„์‚ฐ # - ํŠน์„ฑ ๋ณ€ํ™˜ # - ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ ์ฃผ์„ฑ๋ถ„ ๋ถ„์„ # - ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„์„ ํ†ตํ•œ ์ง€๋„ ๋ฐฉ์‹์˜ ๋ฐ์ดํ„ฐ ์••์ถ• # - ์ฃผ์„ฑ๋ถ„ ๋ถ„์„ vs ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„ # - ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„์˜ ๋‚ด๋ถ€ ๋™์ž‘ ๋ฐฉ์‹ # - ์‚ฐํฌ ํ–‰๋ ฌ ๊ณ„์‚ฐ # - ์ƒˆ๋กœ์šด ํŠน์„ฑ ๋ถ€๋ถ„ ๊ณต๊ฐ„์„ ์œ„ํ•ด ์„ ํ˜• ํŒ๋ณ„ ๋ฒกํ„ฐ ์„ ํƒ # - ์ƒˆ๋กœ์šด ํŠน์„ฑ ๊ณต๊ฐ„์œผ๋กœ ์ƒ˜ํ”Œ ํˆฌ์˜ # - ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ LDA # - ์ปค๋„ PCA๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋น„์„ ํ˜• ๋งคํ•‘ # - ์ปค๋„ ํ•จ์ˆ˜์™€ ์ปค๋„ ํŠธ๋ฆญ # - ํŒŒ์ด์ฌ์œผ๋กœ ์ปค๋„ PCA ๊ตฌํ˜„ # - ์˜ˆ์ œ 1 - ๋ฐ˜๋‹ฌ ๋ชจ์–‘ ๊ตฌ๋ถ„ํ•˜๊ธฐ # - ์˜ˆ์ œ 2 - ๋™์‹ฌ์› ๋ถ„๋ฆฌํ•˜๊ธฐ # - ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ ํฌ์ธํŠธ ํˆฌ์˜ # - ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ ์ปค๋„ PCA # - ์š”์•ฝ # + [markdown] id="zdfxyBijEjGq" # <br> # + colab={"base_uri": "https://localhost:8080/"} id="qUbLOkj_EjGq" outputId="7eaa9bce-627e-4e1b-b107-2609cc2c6c3c" # ์ฝ”๋žฉ์—์„œ ์‹คํ–‰ํ•  ๊ฒฝ์šฐ ์‚ฌ์ดํ‚ท๋Ÿฐ ๋ฒ„์ „์„ ์ตœ์‹ ์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜์„ธ์š”. # !pip install --upgrade scikit-learn # + id="nSf82FR-EjGr" from IPython.display import Image # + [markdown] id="8_p4a2DdEjGr" # # 5.1 ์ฃผ์„ฑ๋ถ„ ๋ถ„์„์„ ํ†ตํ•œ ๋น„์ง€๋„ ์ฐจ์› ์ถ•์†Œ # + [markdown] id="aMwZJrGQEjGr" # ## 5.1.1 ์ฃผ์„ฑ๋ถ„ ๋ถ„์„์˜ ์ฃผ์š” ๋‹จ๊ณ„ # + colab={"base_uri": "https://localhost:8080/", "height": 386} id="MiqBHvISEjGr" outputId="bdd67a32-14e8-4c3b-e89d-6ef4e62f5f98" Image(url='https://git.io/JtsvW', width=400) # - # $\boldsymbol{x}\boldsymbol{W}=\boldsymbol{z}$ # + [markdown] id="ZT7XQlR5EjGs" # ## 5.1.2 ์ฃผ์„ฑ๋ถ„ ์ถ”์ถœ ๋‹จ๊ณ„ # + colab={"base_uri": "https://localhost:8080/", "height": 198} id="Fod9IR5ZEjGs" outputId="cff5e68a-02f9-42d5-c9c8-eea8abe310ad" import pandas as pd df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) # UCI ๋จธ์‹  ๋Ÿฌ๋‹ ์ €์žฅ์†Œ์—์„œ Wine ๋ฐ์ดํ„ฐ์…‹์„ ๋‹ค์šด๋กœ๋“œํ•  ์ˆ˜ ์—†์„ ๋•Œ # ๋‹ค์Œ ์ฃผ์„์„ ํ•ด์ œํ•˜๊ณ  ๋กœ์ปฌ ๊ฒฝ๋กœ์—์„œ ๋ฐ์ดํ„ฐ์…‹์„ ์ ์žฌํ•˜์„ธ์š”: # df_wine = pd.read_csv('wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] df_wine.head() # + [markdown] id="d1bnkLDTEjGt" # 70%๋Š” ํ›ˆ๋ จ ์„ธํŠธ๋กœ 30%๋Š” ํ…Œ์ŠคํŠธ ์„ธํŠธ๋กœ ๋‚˜๋ˆ•๋‹ˆ๋‹ค. # + id="EA5J2XWMEjGt" from sklearn.model_selection import train_test_split X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.3, stratify=y, random_state=0) # + [markdown] id="hMMoofvmEjGt" # ๋ฐ์ดํ„ฐ๋ฅผ ํ‘œ์ค€ํ™”ํ•ฉ๋‹ˆ๋‹ค. # + id="AqQpTbYaEjGt" from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train_std = sc.fit_transform(X_train) X_test_std = sc.transform(X_test) # + [markdown] id="edcNE-glEjGt" # --- # # **๋…ธํŠธ** # # `X_test_std = sc.fit_transform(X_test)` ๋Œ€์‹ ์— `X_test_std = sc.transform(X_test)`๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ์— ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ์…‹์˜ ํ‰๊ท ๊ณผ ํ‘œ์ค€ํŽธ์ฐจ๊ฐ€ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹๊ณผ ๋งค์šฐ ๋น„์Šทํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํฐ ์ฐจ์ด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ 3์žฅ์—์„œ ๋ณด์•˜๋“ฏ์ด ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€ํ™˜ํ•  ๋•Œ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์—์„œ ํ•™์Šตํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์˜ฌ๋ฐ”๋ฅธ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ์…‹์€ "์ƒˆ๋กœ์šด ๋ณธ ์  ์—†๋Š”" ๋ฐ์ดํ„ฐ๋ฅผ ์˜๋ฏธํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. # # ์ดˆ๊ธฐ์— `fit_transform(X_test)`๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ์ด๊ฒƒ์€ ๋ชจ๋ธ ํ›ˆ๋ จ์—์„œ ์–ป์€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜์—ฌ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋ฅผ ํ‘œ์ค€ํ™”ํ•˜์ง€ ์•Š๋Š” ์ผ๋ฐ˜์ ์ธ ์‹ค์ˆ˜์ž…๋‹ˆ๋‹ค. ์™œ ์ด๊ฒƒ์ด ๋ฌธ์ œ๊ฐ€ ๋˜๋Š”์ง€ ๊ฐ„๋‹จํ•œ ์˜ˆ๋ฅผ ์‚ดํŽด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. # # ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์— 1๊ฐœ์˜ ํŠน์„ฑ("๊ธธ์ด")์„ ๊ฐ€์ง„ ์ƒ˜ํ”Œ 3๊ฐœ๊ฐ€ ๋“ค์–ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด์ฃ : # # - train_1: 10 cm -> class_2 # - train_2: 20 cm -> class_2 # - train_3: 30 cm -> class_1 # # mean: 20, std.: 8.2 # # ํ‘œ์ค€ํ™”๋ฅผ ํ•œ ํ›„์— ๋ณ€ํ™˜๋œ ํŠน์„ฑ ๊ฐ’์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค: # # - train_std_1: -1.22 -> class_2 # - train_std_2: 0 -> class_2 # - train_std_3: 1.22 -> class_1 # # ๊ทธ๋‹ค์Œ ํ‘œ์ค€ํ™”๋œ ๊ธธ์ด๊ฐ€ 0.6๋ณด๋‹ค ์ž‘์€ ์ƒ˜ํ”Œ์„ class_2๋กœ ๋ถ„๋ฅ˜ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด์ฃ (๊ทธ ์™ธ์—๋Š” class_1). ์ง€๊ธˆ๊นŒ์ง€๋Š” ์ข‹์Šต๋‹ˆ๋‹ค. ์ด์ œ ๋ ˆ์ด๋ธ”์ด ์—†๋Š” 3๊ฐœ์˜ ํฌ์ธํŠธ๋ฅผ ๋ถ„๋ฅ˜ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด์ฃ : # # - new_4: 5 cm -> class ? # - new_5: 6 cm -> class ? # - new_6: 7 cm -> class ? # # ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์— ์žˆ๋Š” ํ‘œ์ค€ํ™”๋˜๊ธฐ ์ „์˜ "๊ธธ์ด" ๊ฐ’๊ณผ ๋น„๊ตํ•ด ๋ณด๋ฉด ์ง๊ด€์ ์œผ๋กœ ์ด ์ƒ˜ํ”Œ๋“ค์€ class_2๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์—์„œ ํ–ˆ๋˜ ๊ฒƒ์ฒ˜๋Ÿผ ํ‰๊ท ๊ณผ ํ‘œ์ค€ํŽธ์ฐจ๋ฅผ ๋‹ค์‹œ ๊ณ„์‚ฐํ•˜์—ฌ ํ‘œ์ค€ํ™”ํ•˜๋ฉด ์•„๋งˆ๋„ ๋ถ„๋ฅ˜๊ธฐ๊ฐ€ ์ƒ˜ํ”Œ 4๋ฒˆ๊ณผ 5๋ฒˆ๋งŒ class_2๋กœ ๋ถ„๋ฅ˜ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. # # - new_std_4: -1.22 -> class 2 # - new_std_5: 0 -> class 2 # - new_std_6: 1.22 -> class 1 # # ํ•˜์ง€๋งŒ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์˜ ํ‘œ์ค€ํ™”์— ์‚ฌ์šฉํ–ˆ๋˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฐ’์„ ์–ป์Šต๋‹ˆ๋‹ค: # # - example5: -1.84 -> class 2 # - example6: -1.71 -> class 2 # - example7: -1.59 -> class 2 # # 5 cm, 6 cm, 7 cm๋Š” ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์— ์žˆ๋Š” ์–ด๋–ค ๊ฒƒ๋ณด๋‹ค๋„ ์ž‘์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ์…‹์„ ํ‘œ์ค€ํ™”ํ•œ ๊ฐ’๋ณด๋‹ค๋„ ํ›จ์”ฌ ์ž‘์€ ๊ฐ’์œผ๋กœ ํ‘œ์ค€ํ™”๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. # # --- # + [markdown] id="cKUsKeCWEjGu" # ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์˜ ๊ณ ์œณ๊ฐ’ ๋ถ„ํ•ด # + colab={"base_uri": "https://localhost:8080/"} id="C1p8pEbVEjGu" outputId="ed0c049d-4438-48a6-cc37-be09df425fbc" import numpy as np cov_mat = np.cov(X_train_std.T) eigen_vals, eigen_vecs = np.linalg.eig(cov_mat) print('\n๊ณ ์œณ๊ฐ’ \n%s' % eigen_vals) # + [markdown] id="sWQdxyAFEjGu" # **๋…ธํŠธ**: # # ์œ„์—์„œ [`numpy.linalg.eig`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html) ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ๋Œ€์นญ ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์„ ๊ณ ์œณ๊ฐ’๊ณผ ๊ณ ์œ ๋ฒกํ„ฐ๋กœ ๋ถ„ํ•ดํ–ˆ์Šต๋‹ˆ๋‹ค. # # <pre>>>> eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)</pre> # # ์ด๊ฒƒ์ด ์ž˜๋ชป๋œ ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ ์ตœ์ ์€ ์•„๋‹™๋‹ˆ๋‹ค. [์—๋ฅด๋ฏธํŠธ(Hermetian) ํ–‰๋ ฌ](https://en.wikipedia.org/wiki/Hermitian_matrix)๋ฅผ ์œ„ํ•ด์„œ ์„ค๊ณ„๋œ [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์Šต๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ํ•ญ์ƒ ์‹ค์ˆ˜ ๊ณ ์œณ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ˆ˜์น˜์ ์œผ๋กœ ์•ฝ๊ฐ„ ๋œ ์•ˆ์ •์ ์ธ `np.linalg.eig`๋Š” ๋น„๋Œ€์นญ ์ •๋ฐฉํ–‰๋ ฌ์„ ๋ถ„ํ•ดํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์–ด๋–ค ๊ฒฝ์šฐ์— ๋ณต์†Œ์ˆ˜ ๊ณ ์œณ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # + [markdown] id="v5uHAyy7EjGu" # <br> # + [markdown] id="6Ziezfe6EjGu" # ## 5.1.3 ์ด๋ถ„์‚ฐ๊ณผ ์„ค๋ช…๋œ ๋ถ„์‚ฐ # + id="VrKFIi3ZEjGu" tot = sum(eigen_vals) var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)] cum_var_exp = np.cumsum(var_exp) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="iQmRwT46EjGu" outputId="b089124c-d719-4a94-e953-0d79274a1a60" import matplotlib.pyplot as plt plt.bar(range(1, 14), var_exp, alpha=0.5, align='center', label='Individual explained variance') plt.step(range(1, 14), cum_var_exp, where='mid', label='Cumulative explained variance') plt.ylabel('Explained variance ratio') plt.xlabel('Principal component index') plt.legend(loc='best') plt.tight_layout() # plt.savefig('images/05_02.png', dpi=300) plt.show() # + [markdown] id="-03gKjrPEjGv" # <br> # + [markdown] id="KWhLM7GoEjGv" # ## 5.1.4 ํŠน์„ฑ ๋ณ€ํ™˜ # + id="1F3O3rx-EjGv" # (๊ณ ์œณ๊ฐ’, ๊ณ ์œ ๋ฒกํ„ฐ) ํŠœํ”Œ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค eigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i]) for i in range(len(eigen_vals))] # ๋†’์€ ๊ฐ’์—์„œ ๋‚ฎ์€ ๊ฐ’์œผ๋กœ (๊ณ ์œณ๊ฐ’, ๊ณ ์œ ๋ฒกํ„ฐ) ํŠœํ”Œ์„ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค eigen_pairs.sort(key=lambda k: k[0], reverse=True) # + colab={"base_uri": "https://localhost:8080/"} id="bvcxCj6REjGv" outputId="04e9e4d6-dce1-4433-e229-70b1631fcb46" w = np.hstack((eigen_pairs[0][1][:, np.newaxis], eigen_pairs[1][1][:, np.newaxis])) print('ํˆฌ์˜ ํ–‰๋ ฌ W:\n', w) # + [markdown] id="tuaO_K8cEjGv" # **๋…ธํŠธ:** # # ์‚ฌ์šฉํ•˜๋Š” Numpy์™€ LAPACK ๋ฒ„์ „์— ๋”ฐ๋ผ ํ–‰๋ ฌ W์˜ ๋ถ€ํ˜ธ๊ฐ€ ๋ฐ”๋€” ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ๋ฌธ์ œ๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. $v$๊ฐ€ ํ–‰๋ ฌ $\Sigma$์˜ ๊ณ ์œ ๋ฒกํ„ฐ๋ผ๋ฉด ๋‹ค์Œ์„ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # # $$\Sigma v = \lambda v,$$ # # ์—ฌ๊ธฐ์—์„œ $\lambda$๋Š” ๊ณ ์œณ๊ฐ’์ž…๋‹ˆ๋‹ค. # # $$\Sigma \cdot (-v) = -\Sigma v = -\lambda v = \lambda \cdot (-v).$$์ด๊ธฐ ๋•Œ๋ฌธ์— $-v$๋„ ๋™์ผํ•œ ๊ณ ์œณ๊ฐ’์„ ๊ฐ€์ง„ ๊ณ ์œ ๋ฒกํ„ฐ์ž…๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/"} id="BvUbmNzoEjGv" outputId="092dd545-a5c2-4ad1-e644-bc20bacf9219" X_train_std[0].dot(w) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="KxFGjRojEjGw" outputId="8e0b7fb8-05d0-4943-8250-20b1e3c3ce0a" X_train_pca = X_train_std.dot(w) colors = ['r', 'b', 'g'] markers = ['s', 'x', 'o'] for l, c, m in zip(np.unique(y_train), colors, markers): plt.scatter(X_train_pca[y_train == l, 0], X_train_pca[y_train == l, 1], c=c, label=l, marker=m) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.legend(loc='lower left') plt.tight_layout() # plt.savefig('images/05_03.png', dpi=300) plt.show() # + [markdown] id="5GFN87VuEjGw" # <br> # + [markdown] id="M_KY060EEjGw" # ## 5.1.5 ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ ์ฃผ์„ฑ๋ถ„ ๋ถ„์„ # + [markdown] id="f5vqSfXIEjGw" # **๋…ธํŠธ** # # ์ด์–ด์ง€๋Š” ๋„ค ๊ฐœ์˜ ์…€์€ ์ฑ…์— ์—†๋Š” ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค. ์‚ฌ์ดํ‚ท๋Ÿฐ์—์„œ ์•ž์˜ PCA ๊ตฌํ˜„ ๊ฒฐ๊ณผ๋ฅผ ์žฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="SrIDFuzvEjGw" outputId="0c4b5915-1b82-4ed0-b95d-0733d930edc7" from sklearn.decomposition import PCA pca = PCA() X_train_pca = pca.fit_transform(X_train_std) pca.explained_variance_ratio_ # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="Bdlq_npKEjGw" outputId="6a3e9d6a-c290-4073-a4ca-a3654842e984" plt.bar(range(1, 14), pca.explained_variance_ratio_, alpha=0.5, align='center') plt.step(range(1, 14), np.cumsum(pca.explained_variance_ratio_), where='mid') plt.ylabel('Explained variance ratio') plt.xlabel('Principal components') plt.show() # + id="siTpt9sXEjGx" pca = PCA(n_components=2) X_train_pca = pca.fit_transform(X_train_std) X_test_pca = pca.transform(X_test_std) # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="xc8dWtb5EjGx" outputId="16812cac-7264-4fe7-964e-bba97e9b2f03" plt.scatter(X_train_pca[:, 0], X_train_pca[:, 1]) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.show() # + id="audMeNXmEjGx" from matplotlib.colors import ListedColormap def plot_decision_regions(X, y, classifier, resolution=0.02): # ๋งˆ์ปค์™€ ์ปฌ๋Ÿฌ๋งต์„ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # ๊ฒฐ์ • ๊ฒฝ๊ณ„๋ฅผ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # ํด๋ž˜์Šค๋ณ„๋กœ ์ƒ˜ํ”Œ์„ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.6, color=cmap(idx), edgecolor='black', marker=markers[idx], label=cl) # + [markdown] id="7beQNiiFEjGx" # ์ฒ˜์Œ ๋‘ ๊ฐœ์˜ ์ฃผ์„ฑ๋ถ„์„ ์‚ฌ์šฉํ•˜์—ฌ ๋กœ์ง€์Šคํ‹ฑ ํšŒ๊ท€ ๋ถ„๋ฅ˜๊ธฐ๋ฅผ ํ›ˆ๋ จํ•ฉ๋‹ˆ๋‹ค. # + id="3E1HW9RlEjGy" from sklearn.linear_model import LogisticRegression pca = PCA(n_components=2) X_train_pca = pca.fit_transform(X_train_std) X_test_pca = pca.transform(X_test_std) lr = LogisticRegression(random_state=1) lr = lr.fit(X_train_pca, y_train) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="KljC04RyEjGy" outputId="40036fdf-d136-48c8-d48c-b013ee047378" plot_decision_regions(X_train_pca, y_train, classifier=lr) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.legend(loc='lower left') plt.tight_layout() # plt.savefig('images/05_04.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="Q190-SbDEjGy" outputId="d166df02-8109-45e2-aa77-99ae123ebca0" plot_decision_regions(X_test_pca, y_test, classifier=lr) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.legend(loc='lower left') plt.tight_layout() # plt.savefig('images/05_05.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="nYN0rAe2EjGy" outputId="74f218eb-0d3d-4e51-cca3-b75e6525683a" pca = PCA(n_components=None) X_train_pca = pca.fit_transform(X_train_std) pca.explained_variance_ratio_ # + [markdown] id="bwBzhFTHEjGy" # `n_components`์— (0, 1) ์‚ฌ์ด ์‹ค์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์„ค๋ช…๋œ ๋ถ„์‚ฐ์˜ ๋น„์œจ์„ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค. ์ด ๋น„์œจ์„ ๋‹ฌ์„ฑํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜๋ฅผ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/"} id="hAudlTvIEjGz" outputId="b96693e0-3c89-44a4-87ee-4d88e5146ecb" pca = PCA(n_components=0.95) pca.fit(X_train_std) print('์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜:', pca.n_components_) print('์„ค๋ช…๋œ ๋ถ„์‚ฐ ๋น„์œจ:', np.sum(pca.explained_variance_ratio_)) # + [markdown] id="vVqwwK7TEjGz" # `n_components='mle'`๋กœ ์ง€์ •ํ•˜๋ฉด ํ† ๋งˆ์Šค ๋ฏผ์นด(Thomas Minka)๊ฐ€ ์ œ์•ˆํ•œ ์ฐจ์› ์„ ํƒ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค(Minka, <NAME>. โ€œAutomatic choice of dimensionality for PCAโ€. In NIPS, pp. 598-604). # + colab={"base_uri": "https://localhost:8080/"} id="aq0ejdBgEjGz" outputId="050d4797-2aec-4386-edda-90d8139b70e9" pca = PCA(n_components='mle') pca.fit(X_train_std) print('์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜:', pca.n_components_) print('์„ค๋ช…๋œ ๋ถ„์‚ฐ ๋น„์œจ:', np.sum(pca.explained_variance_ratio_)) # + [markdown] id="6AKyi0DfEjGz" # `PCA`์˜ ๊ฐ€์žฅ ํฐ ์ œ์•ฝ ์‚ฌํ•ญ ์ค‘ ํ•˜๋‚˜๋Š” ๋ฐฐ์น˜๋กœ๋งŒ ์‹คํ–‰๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ์…‹์„ ์ฒ˜๋ฆฌํ•˜๋ ค๋ฉด ๋งŽ์€ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. `IncrementalPCA`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฐ์ดํ„ฐ์…‹์˜ ์ผ๋ถ€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ˜๋ณต์ ์œผ๋กœ ํ›ˆ๋ จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # # `partial_fit()` ๋ฉ”์„œ๋“œ๋Š” ๋„คํŠธ์›Œํฌ๋‚˜ ๋กœ์ปฌ ํŒŒ์ผ ์‹œ์Šคํ…œ์œผ๋กœ๋ถ€ํ„ฐ ์กฐ๊ธˆ์”ฉ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์™€ ํ›ˆ๋ จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `fit()` ๋ฉ”์„œ๋“œ๋Š” `numpy.memmap`์„ ์‚ฌ์šฉํ•˜์—ฌ ๋กœ์ปฌ ํŒŒ์ผ๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ ์กฐ๊ธˆ์”ฉ ์ฝ์–ด ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•œ ๋ฒˆ์— ์ฝ์–ด ์˜ฌ ๋ฐ์ดํ„ฐ ํฌ๊ธฐ๋Š” `IncrementalPCA` ํด๋ž˜์Šค์˜ `batch_size`๋กœ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ ํŠน์„ฑ ๊ฐœ์ˆ˜์˜ 5๋ฐฐ์ž…๋‹ˆ๋‹ค. # # `IncrementalPCA`์˜ `n_components` ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ •์ˆ˜ ๊ฐ’๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ์€ `partial_fit()` ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์•ž์˜ `PCA`๋กœ ์ฐพ์€ ์ฃผ์„ฑ๋ถ„์˜ ๊ฒฐ๊ณผ์™€ ๋น„๊ตํ•˜๋Š” ๊ฐ„๋‹จํ•œ ์˜ˆ์ž…๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/"} id="1DcUF_ySEjGz" outputId="0c69d29b-6329-44fe-c9e1-574095c0c498" from sklearn.decomposition import IncrementalPCA ipca = IncrementalPCA(n_components=9) for batch in range(len(X_train_std)//25+1): X_batch = X_train_std[batch*25:(batch+1)*25] ipca.partial_fit(X_batch) print('์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜:', ipca.n_components_) print('์„ค๋ช…๋œ ๋ถ„์‚ฐ ๋น„์œจ:', np.sum(ipca.explained_variance_ratio_)) # + [markdown] id="A75qiYlzEjGz" # <br> # + [markdown] id="vrV-l0OtEjG0" # # 5.2 ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„์„ ํ†ตํ•œ ์ง€๋„๋ฐฉ์‹์˜ ๋ฐ์ดํ„ฐ ์••์ถ• # + [markdown] id="rZ1yv2kdEjG0" # ## 5.2.1 ์ฃผ์„ฑ๋ถ„ ๋ถ„์„ vs ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„ # + colab={"base_uri": "https://localhost:8080/", "height": 366} id="BwDzcypZEjG0" outputId="df66dbad-e6e5-4060-926c-21e3308d5603" Image(url='https://git.io/Jtsv8', width=400) # + [markdown] id="dqNYW_1JEjG0" # ## ์„ ํ˜• ํŒ๋ณ„ ๋ถ„์„์˜ ๋‚ด๋ถ€ ๋™์ž‘ ๋ฐฉ์‹ # + [markdown] id="73eS4jTgEjG0" # <br> # <br> # + [markdown] id="swEC9tzxEjG0" # ## ์‚ฐํฌ ํ–‰๋ ฌ ๊ณ„์‚ฐ # + [markdown] id="v_bJB6JaEjG0" # ๊ฐ ํด๋ž˜์Šค์— ๋Œ€ํ•œ ํ‰๊ท  ๋ฒกํ„ฐ๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="3LeJnkK_EjG0" outputId="e52d8219-9a53-4945-ec3a-dcf2c48a0768" np.set_printoptions(precision=4) mean_vecs = [] for label in range(1, 4): mean_vecs.append(np.mean(X_train_std[y_train == label], axis=0)) print('MV %s: %s\n' % (label, mean_vecs[label - 1])) # + [markdown] id="c-nwJBF5EjG1" # ํด๋ž˜์Šค ๋‚ด ์‚ฐํฌ ํ–‰๋ ฌ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="TRb957tiEjG1" outputId="48d79cf5-11d0-4983-de96-c38155144131" d = 13 # ํŠน์„ฑ์˜ ์ˆ˜ S_W = np.zeros((d, d)) for label, mv in zip(range(1, 4), mean_vecs): class_scatter = np.zeros((d, d)) # ๊ฐ ํด๋ž˜์Šค์— ๋Œ€ํ•œ ์‚ฐํฌ ํ–‰๋ ฌ for row in X_train_std[y_train == label]: row, mv = row.reshape(d, 1), mv.reshape(d, 1) # ์—ด ๋ฒกํ„ฐ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค class_scatter += (row - mv).dot((row - mv).T) S_W += class_scatter # ํด๋ž˜์Šค ์‚ฐํฌ ํ–‰๋ ฌ์„ ๋”ํ•ฉ๋‹ˆ๋‹ค print('ํด๋ž˜์Šค ๋‚ด์˜ ์‚ฐํฌ ํ–‰๋ ฌ: %sx%s' % (S_W.shape[0], S_W.shape[1])) # + [markdown] id="Dalrtl0AEjG1" # ํด๋ž˜์Šค๊ฐ€ ๊ท ์ผํ•˜๊ฒŒ ๋ถ„ํฌ๋˜์–ด ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ๋‚ซ์Šต๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="2xb6G0WKEjG1" outputId="51f73a4d-09e5-4cc9-a38e-f8444908410d" print('ํด๋ž˜์Šค ๋ ˆ์ด๋ธ” ๋ถ„ํฌ: %s' % np.bincount(y_train)[1:]) # + colab={"base_uri": "https://localhost:8080/"} id="XWzi_qzwEjG1" outputId="749af11c-1002-4b86-d7db-5cbc95e23986" d = 13 # ํŠน์„ฑ์˜ ์ˆ˜ S_W = np.zeros((d, d)) for label, mv in zip(range(1, 4), mean_vecs): class_scatter = np.cov(X_train_std[y_train == label].T) S_W += class_scatter print('์Šค์ผ€์ผ ์กฐ์ •๋œ ํด๋ž˜์Šค ๋‚ด์˜ ์‚ฐํฌ ํ–‰๋ ฌ: %sx%s' % (S_W.shape[0], S_W.shape[1])) # + [markdown] id="7dBT2KJKEjG1" # ํด๋ž˜์Šค ๊ฐ„ ์‚ฐํฌ ํ–‰๋ ฌ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="xdPoDmAZEjG1" outputId="6a5fc4e2-2d8b-484d-9cba-417b770b0e92" mean_overall = np.mean(X_train_std, axis=0) mean_overall = mean_overall.reshape(d, 1) # ์—ด ๋ฒกํ„ฐ๋กœ ๋งŒ๋“ค๊ธฐ d = 13 # ํŠน์„ฑ ๊ฐœ์ˆ˜ S_B = np.zeros((d, d)) for i, mean_vec in enumerate(mean_vecs): n = X_train_std[y_train == i + 1, :].shape[0] mean_vec = mean_vec.reshape(d, 1) # ์—ด ๋ฒกํ„ฐ๋กœ ๋งŒ๋“ค๊ธฐ S_B += n * (mean_vec - mean_overall).dot((mean_vec - mean_overall).T) print('ํด๋ž˜์Šค ๊ฐ„์˜ ์‚ฐํฌ ํ–‰๋ ฌ: %sx%s' % (S_B.shape[0], S_B.shape[1])) # + [markdown] id="cCw6Yv1sEjG1" # <br> # <br> # + [markdown] id="M_7csaMHEjG2" # ## ์ƒˆ๋กœ์šด ํŠน์„ฑ ๋ถ€๋ถ„ ๊ณต๊ฐ„์„ ์œ„ํ•ด ์„ ํ˜• ํŒ๋ณ„ ๋ฒกํ„ฐ ์„ ํƒํ•˜๊ธฐ # + [markdown] id="CDTcT3twEjG2" # ํ–‰๋ ฌ $S_W^{-1}S_B$์˜ ์ผ๋ฐ˜์ ์ธ ๊ณ ์œณ๊ฐ’ ๋ถ„ํ•ด ๋ฌธ์ œ๋ฅผ ํ’‰๋‹ˆ๋‹ค: # + id="jdm4jT5EEjG2" eigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B)) # + [markdown] id="EVG_3zgIEjG2" # **๋…ธํŠธ**: # # ์œ„์—์„œ [`numpy.linalg.eig`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html) ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ๋Œ€์นญ ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์„ ๊ณ ์œณ๊ฐ’๊ณผ ๊ณ ์œ ๋ฒกํ„ฐ๋กœ ๋ถ„ํ•ดํ–ˆ์Šต๋‹ˆ๋‹ค. # # <pre>>>> eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)</pre> # # ์ด๊ฒƒ์ด ์ž˜๋ชป๋œ ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ ์ตœ์ ์€ ์•„๋‹™๋‹ˆ๋‹ค. [์—๋ฅด๋ฏธํŠธ(Hermetian) ํ–‰๋ ฌ](https://en.wikipedia.org/wiki/Hermitian_matrix)๋ฅผ ์œ„ํ•ด์„œ ์„ค๊ณ„๋œ [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์Šต๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ํ•ญ์ƒ ์‹ค์ˆ˜ ๊ณ ์œณ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ˆ˜์น˜์ ์œผ๋กœ ์•ฝ๊ฐ„ ๋œ ์•ˆ์ •์ ์ธ `np.linalg.eig`๋Š” ๋น„๋Œ€์นญ ์ •๋ฐฉํ–‰๋ ฌ์„ ๋ถ„ํ•ดํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์–ด๋–ค ๊ฒฝ์šฐ์— ๋ณต์†Œ์ˆ˜ ๊ณ ์œณ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # + [markdown] id="2lJf-i8oEjG2" # ๊ณ ์œณ๊ฐ’์˜ ์—ญ์ˆœ์œผ๋กœ ๊ณ ์œ  ๋ฒกํ„ฐ๋ฅผ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค: # + colab={"base_uri": "https://localhost:8080/"} id="cFCra1wjEjG2" outputId="775b06b3-9fb2-4cec-9109-d2776246a743" # (๊ณ ์œณ๊ฐ’, ๊ณ ์œ ๋ฒกํ„ฐ) ํŠœํ”Œ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. eigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i]) for i in range(len(eigen_vals))] # (๊ณ ์œณ๊ฐ’, ๊ณ ์œ ๋ฒกํ„ฐ) ํŠœํ”Œ์„ ํฐ ๊ฐ’์—์„œ ์ž‘์€ ๊ฐ’ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. eigen_pairs = sorted(eigen_pairs, key=lambda k: k[0], reverse=True) # ๊ณ ์œณ๊ฐ’์˜ ์—ญ์ˆœ์œผ๋กœ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ •๋ ฌ๋˜์—ˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. print('๋‚ด๋ฆผ์ฐจ์ˆœ์˜ ๊ณ ์œณ๊ฐ’:\n') for eigen_val in eigen_pairs: print(eigen_val[0]) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="QTBSkyVPEjG2" outputId="840a7495-3090-4466-f9e1-ee7bd45ffda4" tot = sum(eigen_vals.real) discr = [(i / tot) for i in sorted(eigen_vals.real, reverse=True)] cum_discr = np.cumsum(discr) plt.bar(range(1, 14), discr, alpha=0.5, align='center', label='Individual "discriminability"') plt.step(range(1, 14), cum_discr, where='mid', label='Cumulative "discriminability"') plt.ylabel('"Discriminability" ratio') plt.xlabel('Linear discriminants') plt.ylim([-0.1, 1.1]) plt.legend(loc='best') plt.tight_layout() 'images/05_07.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="KDxlXzVBEjG2" outputId="42e634f6-e845-46b7-9793-34e2a28a7589" w = np.hstack((eigen_pairs[0][1][:, np.newaxis].real, eigen_pairs[1][1][:, np.newaxis].real)) print('ํ–‰๋ ฌ W:\n', w) # + [markdown] id="tu490rQsEjG3" # <br> # <br> # + [markdown] id="D21vo1QlEjG3" # ## ์ƒˆ๋กœ์šด ํŠน์„ฑ ๊ณต๊ฐ„์œผ๋กœ ์ƒ˜ํ”Œ ํˆฌ์˜ํ•˜๊ธฐ # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="8rtNnz74EjG3" outputId="f11c4708-ec50-4d71-e292-a0f1e4368f55" X_train_lda = X_train_std.dot(w) colors = ['r', 'b', 'g'] markers = ['s', 'x', 'o'] for l, c, m in zip(np.unique(y_train), colors, markers): plt.scatter(X_train_lda[y_train == l, 0], X_train_lda[y_train == l, 1] * (-1), c=c, label=l, marker=m) plt.xlabel('LD 1') plt.ylabel('LD 2') plt.legend(loc='lower right') plt.tight_layout() # plt.savefig('images/05_08.png', dpi=300) plt.show() # + [markdown] id="15asQXTuEjG3" # <br> # <br> # + [markdown] id="2CbXbBQ7EjG3" # ## ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ LDA # + id="gHB0KzvjEjG3" from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA lda = LDA(n_components=2) X_train_lda = lda.fit_transform(X_train_std, y_train) # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="ykehu9ocEjG3" outputId="81a748dd-3e92-44eb-9846-519589e9c4a7" from sklearn.linear_model import LogisticRegression lr = LogisticRegression(random_state=1) lr = lr.fit(X_train_lda, y_train) plot_decision_regions(X_train_lda, y_train, classifier=lr) plt.xlabel('LD 1') plt.ylabel('LD 2') plt.legend(loc='lower left') plt.tight_layout() # plt.savefig('images/05_09.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="2vpC6hmuEjG3" outputId="2cd55a21-c2a6-4c9b-8da8-018dc9254b19" X_test_lda = lda.transform(X_test_std) plot_decision_regions(X_test_lda, y_test, classifier=lr) plt.xlabel('LD 1') plt.ylabel('LD 2') plt.legend(loc='lower left') plt.tight_layout() # plt.savefig('images/05_10.png', dpi=300) plt.show() # + [markdown] id="Y27NfOE6EjG4" # ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ LDA ๊ตฌํ˜„ ๋ฐฉ์‹ # + colab={"base_uri": "https://localhost:8080/"} id="LqX58-YBEjG4" outputId="8bc35653-7dc4-4113-e27a-1a7bc75b5a10" y_uniq, y_count = np.unique(y_train, return_counts=True) priors = y_count / X_train_std.shape[0] priors # + [markdown] id="Au9anyYvEjG4" # $\sigma_{jk} = \frac{1}{n} \sum_{i=1}^n (x_j^{(i)}-\mu_j)(x_k^{(i)}-\mu_k)$ # # $m = \sum_{i=1}^c \frac{n_i}{n} m_i$ # # $S_W = \sum_{i=1}^c \frac{n_i}{n} S_i = \sum_{i=1}^c \frac{n_i}{n} \Sigma_i$ # + id="3fmRyzDIEjG4" s_w = np.zeros((X_train_std.shape[1], X_train_std.shape[1])) for i, label in enumerate(y_uniq): # 1/n๋กœ ๋‚˜๋ˆˆ ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์„ ์–ป๊ธฐ ์œ„ํ•ด bias=True๋กœ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. s_w += priors[i] * np.cov(X_train_std[y_train == label].T, bias=True) # + [markdown] id="NXQShs0DEjG4" # $ S_B = S_T-S_W = \sum_{i=1}^{c}\frac{n_i}{n}(m_i-m)(m_i-m)^T $ # + id="PBu3Ajq5EjG4" s_b = np.zeros((X_train_std.shape[1], X_train_std.shape[1])) for i, mean_vec in enumerate(mean_vecs): n = X_train_std[y_train == i + 1].shape[0] mean_vec = mean_vec.reshape(-1, 1) s_b += priors[i] * (mean_vec - mean_overall).dot((mean_vec - mean_overall).T) # + id="De00twRIEjG4" import scipy ei_val, ei_vec = scipy.linalg.eigh(s_b, s_w) ei_vec = ei_vec[:, np.argsort(ei_val)[::-1]] # + colab={"base_uri": "https://localhost:8080/"} id="515DAp_oEjG4" outputId="27b44a23-aee6-49f1-8348-a659f67edccf" lda_eigen = LDA(solver='eigen') lda_eigen.fit(X_train_std, y_train) # + colab={"base_uri": "https://localhost:8080/"} id="Wdo7kBhhEjG5" outputId="56639d4f-5464-478d-df2b-fc9430d3c1f9" # ํด๋ž˜์Šค ๋‚ด์˜ ์‚ฐํฌ ํ–‰๋ ฌ์€ covariance_ ์†์„ฑ์— ์ €์žฅ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. np.allclose(s_w, lda_eigen.covariance_) # + colab={"base_uri": "https://localhost:8080/"} id="PFBAWEaQEjG5" outputId="0710c005-a848-4b8a-a122-eda4a8bec7e5" Sb = np.cov(X_train_std.T, bias=True) - lda_eigen.covariance_ np.allclose(Sb, s_b) # + colab={"base_uri": "https://localhost:8080/"} id="Kjks6O2NEjG5" outputId="4d4143fb-3018-4b71-f96e-dd86523af30b" np.allclose(lda_eigen.scalings_[:, :2], ei_vec[:, :2]) # + colab={"base_uri": "https://localhost:8080/"} id="YQ_v9IPfEjG5" outputId="10b4bc51-d029-493c-df02-f9382125f712" np.allclose(lda_eigen.transform(X_test_std), np.dot(X_test_std, ei_vec[:, :2])) # + [markdown] id="F12wsUaYEjG5" # <br> # <br> # + [markdown] id="QmdF0zmSEjG5" # # ์ปค๋„ PCA๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋น„์„ ํ˜• ๋งคํ•‘ํ•˜๊ธฐ # + colab={"base_uri": "https://localhost:8080/", "height": 230} id="LeKVh3F0EjG5" outputId="da47165d-f069-4008-d097-4f815b4e10b6" Image(url='https://git.io/JtsvB', width=500) # + [markdown] id="bZKSwJLtEjG6" # <br> # <br> # + [markdown] id="Z8OlvQunEjG6" # ## ํŒŒ์ด์ฌ์œผ๋กœ ์ปค๋„ PCA ๊ตฌํ˜„ํ•˜๊ธฐ # + id="AWwSJwROEjG6" from scipy.spatial.distance import pdist, squareform from scipy.linalg import eigh import numpy as np from distutils.version import LooseVersion as Version from scipy import __version__ as scipy_version # scipy 2.0.0์—์„œ ์‚ญ์ œ๋  ์˜ˆ์ •์ด๋ฏ€๋กœ ๋Œ€์‹  numpy.exp๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. if scipy_version >= Version('1.4.1'): from numpy import exp else: from scipy import exp def rbf_kernel_pca(X, gamma, n_components): """ RBF ์ปค๋„ PCA ๊ตฌํ˜„ ๋งค๊ฐœ๋ณ€์ˆ˜ ------------ X: {๋„˜ํŒŒ์ด ndarray}, shape = [n_samples, n_features] gamma: float RBF ์ปค๋„ ํŠœ๋‹ ๋งค๊ฐœ๋ณ€์ˆ˜ n_components: int ๋ฐ˜ํ™˜ํ•  ์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜ ๋ฐ˜ํ™˜๊ฐ’ ------------ X_pc: {๋„˜ํŒŒ์ด ndarray}, shape = [n_samples, k_features] ํˆฌ์˜๋œ ๋ฐ์ดํ„ฐ์…‹ """ # MxN ์ฐจ์›์˜ ๋ฐ์ดํ„ฐ์…‹์—์„œ ์ƒ˜ํ”Œ ๊ฐ„์˜ ์œ ํด๋ฆฌ๋””์•ˆ ๊ฑฐ๋ฆฌ์˜ ์ œ๊ณฑ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. sq_dists = pdist(X, 'sqeuclidean') # ์ƒ˜ํ”Œ ๊ฐ„์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ •๋ฐฉ ๋Œ€์นญ ํ–‰๋ ฌ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค. mat_sq_dists = squareform(sq_dists) # ์ปค๋„ ํ–‰๋ ฌ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. K = exp(-gamma * mat_sq_dists) # ์ปค๋„ ํ–‰๋ ฌ์„ ์ค‘์•™์— ๋งž์ถฅ๋‹ˆ๋‹ค. N = K.shape[0] one_n = np.ones((N, N)) / N K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n) # ์ค‘์•™์— ๋งž์ถฐ์ง„ ์ปค๋„ ํ–‰๋ ฌ์˜ ๊ณ ์œณ๊ฐ’๊ณผ ๊ณ ์œ ๋ฒกํ„ฐ๋ฅผ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. # scipy.linalg.eigh ํ•จ์ˆ˜๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. eigvals, eigvecs = eigh(K) eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1] # ์ตœ์ƒ์œ„ k ๊ฐœ์˜ ๊ณ ์œ ๋ฒกํ„ฐ๋ฅผ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค(๊ฒฐ๊ณผ๊ฐ’์€ ํˆฌ์˜๋œ ์ƒ˜ํ”Œ์ž…๋‹ˆ๋‹ค). X_pc = np.column_stack([eigvecs[:, i] for i in range(n_components)]) return X_pc # + [markdown] id="q5LH1FhQEjG6" # <br> # + [markdown] id="-7CDFufCEjG6" # ### ์˜ˆ์ œ 1: ๋ฐ˜๋‹ฌ ๋ชจ์–‘ ๊ตฌ๋ถ„ํ•˜๊ธฐ # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="eK5WLaYkEjG6" outputId="558efbb9-c906-4fee-a59f-7cf8f1a7203f" import matplotlib.pyplot as plt from sklearn.datasets import make_moons X, y = make_moons(n_samples=100, random_state=123) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='red', marker='^', alpha=0.5) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='blue', marker='o', alpha=0.5) plt.tight_layout() # plt.savefig('images/05_12.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 225} id="3XUrxsG1EjG6" outputId="5e15c1de-93dd-47d1-b82e-975850ede617" from sklearn.decomposition import PCA scikit_pca = PCA(n_components=2) X_spca = scikit_pca.fit_transform(X) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3)) ax[0].scatter(X_spca[y == 0, 0], X_spca[y == 0, 1], color='red', marker='^', alpha=0.5) ax[0].scatter(X_spca[y == 1, 0], X_spca[y == 1, 1], color='blue', marker='o', alpha=0.5) ax[1].scatter(X_spca[y == 0, 0], np.zeros((50, 1)) + 0.02, color='red', marker='^', alpha=0.5) ax[1].scatter(X_spca[y == 1, 0], np.zeros((50, 1)) - 0.02, color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1') ax[0].set_ylabel('PC2') ax[1].set_ylim([-1, 1]) ax[1].set_yticks([]) ax[1].set_xlabel('PC1') plt.tight_layout() # plt.savefig('images/05_13.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 225} id="CKQnqpCuEjG6" outputId="c865662b-7e55-4b0f-edc3-210a4249a6c0" X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3)) ax[0].scatter(X_kpca[y==0, 0], X_kpca[y==0, 1], color='red', marker='^', alpha=0.5) ax[0].scatter(X_kpca[y==1, 0], X_kpca[y==1, 1], color='blue', marker='o', alpha=0.5) ax[1].scatter(X_kpca[y==0, 0], np.zeros((50, 1))+0.02, color='red', marker='^', alpha=0.5) ax[1].scatter(X_kpca[y==1, 0], np.zeros((50, 1))-0.02, color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1') ax[0].set_ylabel('PC2') ax[1].set_ylim([-1, 1]) ax[1].set_yticks([]) ax[1].set_xlabel('PC1') plt.tight_layout() # plt.savefig('images/05_14.png', dpi=300) plt.show() # + [markdown] id="MhgMuq_2EjG7" # <br> # + [markdown] id="EWhZCKfMEjG7" # ### ์˜ˆ์ œ 2: ๋™์‹ฌ์› ๋ถ„๋ฆฌํ•˜๊ธฐ # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="PHt9XURIEjG7" outputId="ec0df3bd-981d-4884-c2cd-8432610265de" from sklearn.datasets import make_circles X, y = make_circles(n_samples=1000, random_state=123, noise=0.1, factor=0.2) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='red', marker='^', alpha=0.5) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='blue', marker='o', alpha=0.5) plt.tight_layout() # plt.savefig('images/05_15.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 225} id="vAzJy-ojEjG7" outputId="0cac0528-9bf9-4d92-af17-68bf6d0d7a5e" scikit_pca = PCA(n_components=2) X_spca = scikit_pca.fit_transform(X) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3)) ax[0].scatter(X_spca[y == 0, 0], X_spca[y == 0, 1], color='red', marker='^', alpha=0.5) ax[0].scatter(X_spca[y == 1, 0], X_spca[y == 1, 1], color='blue', marker='o', alpha=0.5) ax[1].scatter(X_spca[y == 0, 0], np.zeros((500, 1)) + 0.02, color='red', marker='^', alpha=0.5) ax[1].scatter(X_spca[y == 1, 0], np.zeros((500, 1)) - 0.02, color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1') ax[0].set_ylabel('PC2') ax[1].set_ylim([-1, 1]) ax[1].set_yticks([]) ax[1].set_xlabel('PC1') plt.tight_layout() # plt.savefig('images/05_16.png', dpi=300) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 225} id="lnVjnP93EjG7" outputId="d2309854-bc48-442f-c941-e5fb6f46155e" X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3)) ax[0].scatter(X_kpca[y == 0, 0], X_kpca[y == 0, 1], color='red', marker='^', alpha=0.5) ax[0].scatter(X_kpca[y == 1, 0], X_kpca[y == 1, 1], color='blue', marker='o', alpha=0.5) ax[1].scatter(X_kpca[y == 0, 0], np.zeros((500, 1)) + 0.02, color='red', marker='^', alpha=0.5) ax[1].scatter(X_kpca[y == 1, 0], np.zeros((500, 1)) - 0.02, color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1') ax[0].set_ylabel('PC2') ax[1].set_ylim([-1, 1]) ax[1].set_yticks([]) ax[1].set_xlabel('PC1') plt.tight_layout() # plt.savefig('images/05_17.png', dpi=300) plt.show() # + [markdown] id="X7mOuyN_EjG7" # <br> # <br> # + [markdown] id="4-NJGCOhEjG7" # ## ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ ํฌ์ธํŠธ ํˆฌ์˜ํ•˜๊ธฐ # + id="I6mzj4vMEjG7" from scipy.spatial.distance import pdist, squareform from numpy import exp from scipy.linalg import eigh import numpy as np def rbf_kernel_pca(X, gamma, n_components): """ RBF ์ปค๋„ PCA ๊ตฌํ˜„ ๋งค๊ฐœ๋ณ€์ˆ˜ ------------ X: {๋„˜ํŒŒ์ด ndarray}, shape = [n_samples, n_features] gamma: float RBF ์ปค๋„ ํŠœ๋‹ ๋งค๊ฐœ๋ณ€์ˆ˜ n_components: int ๋ฐ˜ํ™˜ํ•  ์ฃผ์„ฑ๋ถ„ ๊ฐœ์ˆ˜ Returns ------------ alphas: {๋„˜ํŒŒ์ด ndarray}, shape = [n_samples, k_features] ํˆฌ์˜๋œ ๋ฐ์ดํ„ฐ์…‹ lambdas: list ๊ณ ์œณ๊ฐ’ """ # MxN ์ฐจ์›์˜ ๋ฐ์ดํ„ฐ์…‹์—์„œ ์ƒ˜ํ”Œ ๊ฐ„์˜ ์œ ํด๋ฆฌ๋””์•ˆ ๊ฑฐ๋ฆฌ์˜ ์ œ๊ณฑ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. sq_dists = pdist(X, 'sqeuclidean') # ์ƒ˜ํ”Œ ๊ฐ„์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ •๋ฐฉ ๋Œ€์นญ ํ–‰๋ ฌ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค. mat_sq_dists = squareform(sq_dists) # ์ปค๋„ ํ–‰๋ ฌ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. K = exp(-gamma * mat_sq_dists) # ์ปค๋„ ํ–‰๋ ฌ์„ ์ค‘์•™์— ๋งž์ถฅ๋‹ˆ๋‹ค. N = K.shape[0] one_n = np.ones((N, N)) / N K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n) # ์ค‘์•™์— ๋งž์ถฐ์ง„ ์ปค๋„ ํ–‰๋ ฌ์˜ ๊ณ ์œณ๊ฐ’๊ณผ ๊ณ ์œ  ๋ฒกํ„ฐ๋ฅผ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. # scipy.linalg.eigh ํ•จ์ˆ˜๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. eigvals, eigvecs = eigh(K) eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1] # ์ตœ์ƒ์œ„ k ๊ฐœ์˜ ๊ณ ์œ  ๋ฒกํ„ฐ๋ฅผ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค(ํˆฌ์˜ ๊ฒฐ๊ณผ). alphas = np.column_stack([eigvecs[:, i] for i in range(n_components)]) # ๊ณ ์œ  ๋ฒกํ„ฐ์— ์ƒ์‘ํ•˜๋Š” ๊ณ ์œณ๊ฐ’์„ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค. lambdas = [eigvals[i] for i in range(n_components)] return alphas, lambdas # + id="BSuLhPTBEjG8" X, y = make_moons(n_samples=100, random_state=123) alphas, lambdas = rbf_kernel_pca(X, gamma=15, n_components=1) # + colab={"base_uri": "https://localhost:8080/"} id="-DYnonckEjG8" outputId="9b9899f0-c17c-4ef7-ce6c-3dc9f8ab00a9" x_new = X[25] x_new # + colab={"base_uri": "https://localhost:8080/"} id="t2lcwezdEjG8" outputId="977f0c94-092e-4c01-cf6c-f5f936ea1989" x_proj = alphas[25] # ์›๋ณธ ํˆฌ์˜ x_proj # + colab={"base_uri": "https://localhost:8080/"} id="K67SPqwPEjG8" outputId="b45b08fc-7cc4-4f73-ab89-cc2d8bbdee7a" def project_x(x_new, X, gamma, alphas, lambdas): pair_dist = np.array([np.sum((x_new - row)**2) for row in X]) k = np.exp(-gamma * pair_dist) return k.dot(alphas / lambdas) # ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐํฌ์ธํŠธ๋ฅผ ํˆฌ์˜ํ•ฉ๋‹ˆ๋‹ค. x_reproj = project_x(x_new, X, gamma=15, alphas=alphas, lambdas=lambdas) x_reproj # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="NqAizbQcEjG8" outputId="4b74167c-2c5c-4b68-e798-57cc3200da54" plt.scatter(alphas[y == 0, 0], np.zeros((50)), color='red', marker='^', alpha=0.5) plt.scatter(alphas[y == 1, 0], np.zeros((50)), color='blue', marker='o', alpha=0.5) plt.scatter(x_proj, 0, color='black', label='Original projection of point X[25]', marker='^', s=100) plt.scatter(x_reproj, 0, color='green', label='Remapped point X[25]', marker='x', s=500) plt.yticks([], []) plt.legend(scatterpoints=1) plt.tight_layout() # plt.savefig('images/05_18.png', dpi=300) plt.show() # + [markdown] id="kifU6Zl1EjG8" # <br> # <br> # + [markdown] id="QRFvGBFJEjG8" # ## ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ ์ปค๋„ PCA # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="9oStyswlEjG9" outputId="bc003b7a-bc55-4cbe-cd4a-af5188970fa1" from sklearn.decomposition import KernelPCA X, y = make_moons(n_samples=100, random_state=123) scikit_kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15) X_skernpca = scikit_kpca.fit_transform(X) plt.scatter(X_skernpca[y == 0, 0], X_skernpca[y == 0, 1], color='red', marker='^', alpha=0.5) plt.scatter(X_skernpca[y == 1, 0], X_skernpca[y == 1, 1], color='blue', marker='o', alpha=0.5) plt.xlabel('PC1') plt.ylabel('PC2') plt.tight_layout() # plt.savefig('images/05_19.png', dpi=300) plt.show() # + [markdown] id="0aHpcz4zEjG9" # ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ ๋งค๋‹ˆํด๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋ฐ˜๋‹ฌ ๋ชจ์–‘ ๋ฐ์ดํ„ฐ์…‹๊ณผ ๋™์‹ฌ์› ๋ฐ์ดํ„ฐ์…‹์— ์ ์šฉํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๋จผ์ € ๋ณ€ํ™˜๋œ 2์ฐจ์› ๋ฐ์ดํ„ฐ์…‹์„ ๊ทธ๋ž˜ํ”„๋กœ ๊ทธ๋ฆฌ๊ธฐ ์œ„ํ•œ ๊ฐ„๋‹จํ•œ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. # + id="4siFOwEDEjG9" def plot_manifold(X, y, savefig_name): plt.scatter(X[y == 0, 0], X[y == 0, 1], color='red', marker='^', alpha=0.5) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='blue', marker='o', alpha=0.5) plt.xlabel('PC1') plt.ylabel('PC2') plt.tight_layout() # plt.savefig(savefig_name, dpi=300) plt.show() # + [markdown] id="DqzS7onvEjG9" # ์ง€์—ญ ์„ ํ˜• ์ž„๋ฒ ๋”ฉ(Locally Linear Embedding)์€ ์ด์›ƒํ•œ ์ƒ˜ํ”Œ ๊ฐ„์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์œ ์ง€ํ•˜๋Š” ์ €์ฐจ์› ํˆฌ์˜์„ ์ฐพ์Šต๋‹ˆ๋‹ค. ์ง€์—ญ ์„ ํ˜• ์ž„๋ฒ ๋”ฉ์„ ๊ตฌํ˜„ํ•œ ์‚ฌ์ดํ‚ท๋Ÿฐ์˜ `LocallyLinearEmbedding` ํด๋ž˜์Šค๋ฅผ ์•ž์—์„œ ์ ์žฌํ•œ ๋ฐ˜๋‹ฌ ๋ชจ์–‘ ๋ฐ์ดํ„ฐ์…‹์— ์ ์šฉํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="fbIHXIAsEjG9" outputId="da28e631-a0f1-41b0-b594-424267e18881" from sklearn.manifold import LocallyLinearEmbedding lle = LocallyLinearEmbedding(n_components=2, random_state=1) X_lle = lle.fit_transform(X) plot_manifold(X_lle, y, 'images/05_lle_moon.png') # + [markdown] id="2pGF6ts1EjG9" # t-SNE(t-distributed Stochastic Neighbor Embedding)๋Š” ๋ฐ์ดํ„ฐ ํฌ์ธํŠธ ๊ฐ„์˜ ์œ ์‚ฌ๋„๋ฅผ ๊ฒฐํ•ฉ ํ™•๋ฅ (joint probability)๋กœ ๋ณ€ํ™˜ํ•˜๊ณ , ์ €์ฐจ์›๊ณผ ๊ณ ์ฐจ์›์˜ ํ™•๋ฅ  ์‚ฌ์ด์—์„œ ์ฟจ๋ฐฑ-๋ผ์ด๋ธ”๋Ÿฌ(Kullback-Leibler) ๋ฐœ์‚ฐ์„ ์ตœ์†Œํ™”ํ•ฉ๋‹ˆ๋‹ค. t-SNE๋Š” ํŠนํžˆ ๊ณ ์ฐจ์› ๋ฐ์ดํ„ฐ์…‹์„ ์‹œ๊ฐํ™”ํ•˜๋Š”๋ฐ ๋›ฐ์–ด๋‚œ ์„ฑ๋Šฅ์„ ๋ƒ…๋‹ˆ๋‹ค. ์‚ฌ์ดํ‚ท๋Ÿฐ์—๋Š” `TSNE` ํด๋ž˜์Šค์— ๊ตฌํ˜„๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="pqZx-bjGEjG9" outputId="569d31dc-8383-4c97-8653-8481dc9e860e" from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=1) X_tsne = tsne.fit_transform(X) plot_manifold(X_tsne, y, 'images/05_tsne_moon.png') # + [markdown] id="UtmSZYnKEjG9" # ์œ„์™€ ๋น„์Šทํ•œ ๋ฐฉ์‹์œผ๋กœ `KernelPCA`, `LocallyLinearEmbedding`, `TSNE`๋ฅผ ๋™์‹ฌ์› ๋ฐ์ดํ„ฐ์…‹์— ์ ์šฉํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="iRCNOjo6EjG-" outputId="b97cf6b5-550b-4ddc-e703-a3b42a5a4934" from sklearn.datasets import make_circles X, y = make_circles(n_samples=1000, random_state=123, noise=0.1, factor=0.2) scikit_kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15) X_skernpca = scikit_kpca.fit_transform(X) plot_manifold(X_skernpca, y, 'images/05_kpca_circles.png') # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="Awt6SJtlEjG-" outputId="96422162-4ac7-4ccc-f1d3-dd1d4484766a" from sklearn.manifold import LocallyLinearEmbedding lle = LocallyLinearEmbedding(n_components=2, random_state=1) X_lle = lle.fit_transform(X) plot_manifold(X_lle, y, 'images/05_lle_circles.png') # + colab={"base_uri": "https://localhost:8080/", "height": 297} id="j2LjGy2nEjG-" outputId="dd01a991-d73f-41ff-d4da-27272daefdb0" from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=1) X_tsne = tsne.fit_transform(X) plot_manifold(X_tsne, y, 'images/05_tsne_circles.png') # + [markdown] id="-dk15nRbEjG-" # <br> # <br>
ch05/ch05.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: hasr # language: python # name: hasr # --- import numpy as np import os import sys import copy import math import csv dataset_names = ['gtea', '50salads', 'breakfast'] backbone_names = ['asrf', 'mstcn', 'sstda', 'mgru'] num_splits = dict() num_splits['gtea'] = 4 num_splits['50salads']=5 num_splits['breakfast']=4 # + record_root = './record' refiner_best_epoch = dict() backbone_best_epoch = dict() for dir_name in sorted([x for x in os.listdir(record_root) if x[0]!='.']): backbone_name = ''.join([t for t in dir_name if t.isupper()]).lower() if len(backbone_name) > 0: refiner_best_epoch[dir_name] = {dn:[] for dn in dataset_names} backbone_best_epoch[backbone_name] = {dn:[] for dn in dataset_names} for data_name in os.listdir(os.path.join(record_root, dir_name)): print(backbone_name, '/\t', dir_name, '/\t', data_name) csv_list = os.listdir(os.path.join(record_root, dir_name, data_name)) plot_flag = True for i in range(num_splits[data_name]): if 'split_{}_best.csv'.format(i+1) not in csv_list: plot_flag = False if plot_flag: curr_score = np.asarray([0.0 for _ in range(5)]) backbone_score = np.asarray([0.0 for _ in range(5)]) for i in range(num_splits[data_name]): curr_csv_fp = os.path.join(record_root, dir_name, data_name, 'split_{}_best.csv'.format(i+1)) backbone_csv_fp = os.path.join(record_root, backbone_name, data_name, 'split_{}_best.csv'.format(i+1)) with open(curr_csv_fp, 'r') as f: reader = csv.reader(f, delimiter='\t') for ri, row in enumerate(reader): if ri>0: refiner_best_epoch[dir_name][data_name].append(int(row[0])) curr_score += np.asarray([float(r) for r in row[1:]]) / num_splits[data_name] with open(backbone_csv_fp, 'r') as f: reader = csv.reader(f, delimiter='\t') for ri, row in enumerate(reader): if ri>0: backbone_best_epoch[backbone_name][data_name].append(int(row[0])) backbone_score += np.asarray([float(r) for r in row[1:]]) / num_splits[data_name] print('backbone:\t %.1f / %.1f / %.1f / %.1f /%.1f ' %(backbone_score[2], backbone_score[3], backbone_score[4], backbone_score[1], backbone_score[0])) print('refined:\t %.1f / %.1f / %.1f / %.1f /%.1f ' %(curr_score[2], curr_score[3], curr_score[4], curr_score[1], curr_score[0])) print('gain: \t\t %.1f / %.1f / %.1f / %.1f /%.1f ' %( curr_score[2] - backbone_score[2], curr_score[3]-backbone_score[3], curr_score[4]-backbone_score[4], curr_score[1]-backbone_score[1], curr_score[0]-backbone_score[0])) print('-'*80) # - # ####
show_quantitative_results.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.3.1 # language: julia # name: julia-1.3 # --- # # Learning: algorithms, objectives, and assumptions # (c) <NAME> 2019 # # In this notebook we will analyze three classic learning algorithms. # * **Perceptron:** ([Rosenblatt, 1957](https://en.wikipedia.org/wiki/Perceptron)) a neuron model trained with a simple algorithm that updates model weights using the input when the prediction is wrong. # * **Adaline:** ([<NAME>, 1960](https://en.wikipedia.org/wiki/ADALINE)) a neuron model trained with a simple algorithm that updates model weights using the error multiplied by the input (aka least mean square (LMS), delta learning rule, or the Widrow-Hoff rule). # * **Softmax classification:** ([Cox, 1958](https://en.wikipedia.org/wiki/Multinomial_logistic_regression)) a multiclass generalization of the logistic regression model from statistics (aka multinomial LR, softmax regression, maxent classifier etc.). # # We will look at these learners from three different perspectives: # * **Algorithm:** First we ask only **how** the learner works, i.e. how it changes after observing each example. # * **Objectives:** Next we ask **what** objective guides the algorithm, whether it is optimizing a particular objective function, and whether we can use a generic *optimization algorithm* instead. # * **Assumptions:** Finally we ask **why** we think this algorithm makes sense, what prior assumptions does this imply and whether we can use *probabilistic inference* for optimal learning. using Knet, Plots, Statistics, LinearAlgebra, Random Base.argmax(a::KnetArray) = argmax(Array(a)) Base.argmax(a::AutoGrad.Value) = argmax(value(a)) ENV["COLUMNS"] = 72 # ### Data include(Knet.dir("data/mnist.jl")) xtrn, ytrn, xtst, ytst = mnist() ARRAY = Array{Float32} xtrn, xtst = ARRAY(mat(xtrn)), ARRAY(mat(xtst)) onehot(y) = (m=ARRAY(zeros(maximum(y),length(y))); for i in 1:length(y); m[y[i],i]=1; end; m) ytrn, ytst = onehot(ytrn), onehot(ytst); println.(summary.((xtrn, ytrn, xtst, ytst))); NTRN,NTST,XDIM,YDIM = size(xtrn,2), size(xtst,2), size(xtrn,1), size(ytrn,1) # ### Prediction # Model weights w = ARRAY(randn(YDIM,XDIM)) # Class scores w * xtrn # Predictions [ argmax(w * xtrn[:,i]) for i in 1:NTRN ]' # Correct answers [ argmax(ytrn[:,i]) for i in 1:NTRN ]' # Accuracy acc(w,x,y) = mean(argmax(w * x, dims=1) .== argmax(y, dims=1)) acc(w,xtrn,ytrn), acc(w,xtst,ytst) # ## Algorithms # Training loop function train(algo,x,y,T=2^20) w = ARRAY(zeros(size(y,1),size(x,1))) nexamples = size(x,2) nextprint = 1 for t = 1:T i = rand(1:nexamples) algo(w, x[:,i], y[:,i]) # <== this is where w is updated if t == nextprint println((iter=t, accuracy=acc(w,x,y), wnorm=norm(w))) nextprint = min(2t,T) end end w end # ### Perceptron function perceptron(w,x,y) guess = argmax(w * x) class = argmax(y) if guess != class w[class,:] .+= x w[guess,:] .-= x end end # (iter = 1048576, accuracy = 0.8950333333333333, wnorm = 1321.2463f0) in 7 secs @time wperceptron = train(perceptron,xtrn,ytrn); # ### Adaline function adaline(w,x,y; lr=0.0001) error = w * x - y w .-= lr * error * x' end # (iter = 1048576, accuracy = 0.8523, wnorm = 1.2907721f0) in 31 secs with lr=0.0001 @time wadaline = train(adaline,xtrn,ytrn); # ### Softmax classifier function softmax(w,x,y; lr=0.01) probs = exp.(w * x) probs ./= sum(probs) error = probs - y w .-= lr * error * x' end # (iter = 1048576, accuracy = 0.9242166666666667, wnorm = 26.523603f0) in 32 secs with lr=0.01 @time wsoftmax = train(softmax,xtrn,ytrn); # ## Objectives # Training via optimization function optimize(loss,x,y; lr=0.1, iters=2^20) w = Param(ARRAY(zeros(size(y,1),size(x,1)))) nexamples = size(x,2) nextprint = 1 for t = 1:iters i = rand(1:nexamples) L = @diff loss(w, x[:,i], y[:,i]) โˆ‡w = grad(L,w) w .-= lr * โˆ‡w if t == nextprint println((iter=t, accuracy=acc(w,x,y), wnorm=norm(w))) nextprint = min(2t,iters) end end w end # ### Perceptron minimizes the score difference between the correct class and the prediction function perceptronloss(w,x,y) score = w * x guess = argmax(score) class = argmax(y) score[guess] - score[class] end # (iter = 1048576, accuracy = 0.8908833333333334, wnorm = 1322.4888f0) in 62 secs with lr=1 @time wperceptron2 = optimize(perceptronloss,xtrn,ytrn,lr=1); # ### Adaline minimizes the squared error function quadraticloss(w,x,y) 0.5 * sum(abs2, w * x - y) end # (iter = 1048576, accuracy = 0.8498333333333333, wnorm = 1.2882874f0) in 79 secs with lr=0.0001 @time wadaline2 = optimize(quadraticloss,xtrn,ytrn,lr=0.0001); # ### Softmax classifier maximizes the probabilities of correct answers # (or minimizes negative log likelihood, aka cross-entropy or softmax loss) function negloglik(w,x,y) probs = exp.(w * x) probs = probs / sum(probs) class = argmax(y) -log(probs[class]) end # (iter = 1048576, accuracy = 0.9283833333333333, wnorm = 26.593485f0) in 120 secs with lr=0.01 @time wsoftmax2 = optimize(negloglik,xtrn,ytrn,lr=0.01);
tutorial/23.learning.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: forallpurposes # language: python # name: forallpurposes # --- # + import numpy as np import matplotlib.pyplot as plt # %matplotlib inline for att in ['axes.labelsize', 'axes.titlesize', 'legend.fontsize', 'legend.fontsize', 'xtick.labelsize', 'ytick.labelsize']: plt.rcParams[att] = 15 from altaipony.ffd import _calculate_percentile_max_ed # + #Plot for docs size, emin, emax = 100 , 10, 1000 data = np.linspace(emin,emax,size) alpha = 2. n = 10000 percentile = 2.5 # apply function vals, edcrit = _calculate_percentile_max_ed(data, alpha, n, percentile) plt.figure(figsize=(8,6)) plt.hist(vals, bins=np.linspace(emin,emax*10, 100),histtype="step", linewidth=1.5, edgecolor="r", label="maximum ED of infinite power law" ) plt.axvline(edcrit, c='k', linestyle="dashed", label=f"critical ED at p={percentile:.1f}%") plt.xlabel("ED [s]", fontsize=15) plt.ylabel("# distributions", fontsize=15) plt.legend(frameon=False, fontsize=15) plt.title(rf"$\alpha={alpha}$, n={size}, $ED = 10 - 1000$ s", fontsize=15) plt.xlim(0,emax*10) plt.savefig("../truncation.png", dpi=300) # -
docs/source/tutorials/plot_source/exceedance_statistic.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 # --- # %matplotlib inline import pandas as pd from IPython.core.display import HTML css = open('style-table.css').read() + open('style-notebook.css').read() HTML('<style>{}</style>'.format(css)) cast = pd.DataFrame.from_csv('data/cast.csv', index_col=None) cast.head() release_dates = pd.DataFrame.from_csv('data/release_dates.csv', index_col=None, parse_dates=['date'], infer_datetime_format=True) release_dates.head() # ### Make a bar plot of the months in which movies with "Christmas" in their title tend to be released in the USA. r=release_dates[(release_dates.title.str.contains('Christmas')) & (release_dates.country == 'USA')] r.date.dt.month.value_counts().sort_index().plot(kind='bar') # ### Make a bar plot of the months in which movies whose titles start with "The Hobbit" are released in the USA. r=release_dates[(release_dates.title.str.startswith('The Hobbit')) & (release_dates.country == 'USA')] r.date.dt.month.value_counts().sort_index().plot(kind='bar') # ### Make a bar plot of the day of the week on which movies with "Romance" in their title tend to be released in the USA. r=release_dates[(release_dates.title.str.contains('Romance')) & (release_dates.country == 'USA')] r.date.dt.dayofweek.value_counts().sort_index().plot(kind='bar') # ### Make a bar plot of the day of the week on which movies with "Action" in their title tend to be released in the USA. r=release_dates[(release_dates.title.str.contains('Action')) & (release_dates.country == 'USA')] r.date.dt.dayofweek.value_counts().sort_index().plot(kind='bar') # ### On which date was each Judi Dench movie from the 1990s released in the USA? # ### In which months do films with <NAME> tend to be released in the USA? # ### In which months do films with <NAME> tend to be released in the USA?
Exercises-5.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 # --- # # ็ฌฌ21็ซ  PageRank็ฎ—ๆณ• # 1. PageRankๆ˜ฏไบ’่”็ฝ‘็ฝ‘้กต้‡่ฆๅบฆ็š„่ฎก็ฎ—ๆ–นๆณ•๏ผŒๅฏไปฅๅฎšไน‰ๆŽจๅนฟๅˆฐไปปๆ„ๆœ‰ๅ‘ๅ›พ็ป“็‚น็š„้‡่ฆๅบฆ่ฎก็ฎ—ไธŠใ€‚ๅ…ถๅŸบๆœฌๆ€ๆƒณๆ˜ฏๅœจๆœ‰ๅ‘ๅ›พไธŠๅฎšไน‰้šๆœบๆธธ่ตฐๆจกๅž‹๏ผŒๅณไธ€้˜ถ้ฉฌๅฐ”ๅฏๅคซ้“พ๏ผŒๆ่ฟฐๆธธ่ตฐ่€…ๆฒฟ็€ๆœ‰ๅ‘ๅ›พ้šๆœบ่ฎฟ้—ฎๅ„ไธช็ป“็‚น็š„่กŒไธบ๏ผŒๅœจไธ€ๅฎšๆกไปถไธ‹๏ผŒๆž้™ๆƒ…ๅ†ต่ฎฟ้—ฎๆฏไธช็ป“็‚น็š„ๆฆ‚็އๆ”ถๆ•›ๅˆฐๅนณ็จณๅˆ†ๅธƒ๏ผŒ่ฟ™ๆ—ถๅ„ไธช็ป“็‚น็š„ๆฆ‚็އๅ€ผๅฐฑๆ˜ฏๅ…ถ PageRankๅ€ผ๏ผŒ่กจ็คบ็ป“็‚น็›ธๅฏน้‡่ฆๅบฆใ€‚ # # 2. ๆœ‰ๅ‘ๅ›พไธŠๅฏไปฅๅฎšไน‰้šๆœบๆธธ่ตฐๆจกๅž‹๏ผŒๅณไธ€้˜ถ้ฉฌๅฐ”ๅฏๅคซ้“พ๏ผŒๅ…ถไธญ็ป“็‚น่กจ็คบ็Šถๆ€๏ผŒๆœ‰ๅ‘่พน่กจ็คบ็Šถๆ€ไน‹้—ด็š„่ฝฌ็งป๏ผŒๅ‡่ฎพไธ€ไธช็ป“็‚นๅˆฐ่ฟžๆŽฅๅ‡บ็š„ๆ‰€ๆœ‰็ป“็‚น็š„่ฝฌ็งปๆฆ‚็އ็›ธ็ญ‰ใ€‚่ฝฌ็งปๆฆ‚็އ็”ฑ่ฝฌ็งป็Ÿฉ้˜ต$M$่กจ็คบ # $$M = [ m _ { i j } ] _ { n \times n }$$ # ็ฌฌ$i$่กŒ็ฌฌ$j$ๅˆ—็š„ๅ…ƒ็ด $m _ { i j }$่กจ็คบไปŽ็ป“็‚น$j$่ทณ่ฝฌๅˆฐ็ป“็‚น$i$็š„ๆฆ‚็އใ€‚ # # 3. ๅฝ“ๅซๆœ‰$n$ไธช็ป“็‚น็š„ๆœ‰ๅ‘ๅ›พๆ˜ฏๅผบ่ฟž้€šไธ”้žๅ‘จๆœŸๆ€ง็š„ๆœ‰ๅ‘ๅ›พๆ—ถ๏ผŒๅœจๅ…ถๅŸบ็ก€ไธŠๅฎšไน‰็š„้šๆœบๆธธ่ตฐๆจกๅž‹๏ผŒๅณไธ€้˜ถ้ฉฌๅฐ”ๅฏๅคซ้“พๅ…ทๆœ‰ๅนณ็จณๅˆ†ๅธƒ๏ผŒๅนณ็จณๅˆ†ๅธƒๅ‘้‡$R$็งฐไธบ่ฟ™ไธชๆœ‰ๅ‘ๅ›พ็š„ PageRankใ€‚่‹ฅ็Ÿฉ้˜ต$M$ๆ˜ฏ้ฉฌๅฐ”ๅฏๅคซ้“พ็š„่ฝฌ็งป็Ÿฉ้˜ต๏ผŒๅˆ™ๅ‘้‡Rๆปก่ถณ$$MR=R$$ๅ‘้‡$R$็š„ๅ„ไธชๅˆ†้‡็งฐ PageRankไธบๅ„ไธช็ป“็‚น็š„ๅ€ผใ€‚ # $$R = \left[ \begin{array} { c } { P R ( v _ { 1 } ) } \\ { P R ( v _ { 2 } ) } \\ { \vdots } \\ { P R ( v _ { n } ) } \end{array} \right]$$ # ๅ…ถไธญ$P R ( v _ { i } ) , i = 1,2 , \cdots , n$๏ผŒ่กจ็คบ็ป“็‚น$v_i$็š„ PageRankๅ€ผใ€‚่ฟ™ๆ˜ฏ PageRank็š„ๅŸบๆœฌๅฎšไน‰ใ€‚ # # 4. PageRankๅŸบๆœฌๅฎšไน‰็š„ๆกไปถ็Žฐๅฎžไธญๅพ€ๅพ€ไธ่ƒฝๆปก่ถณ๏ผŒๅฏนๅ…ถ่ฟ›่กŒๆ‰ฉๅฑ•ๅพ—ๅˆฐ PageRank็š„ไธ€่ˆฌๅฎšไน‰ใ€‚ไปปๆ„ๅซๆœ‰$n$ไธช็ป“็‚น็š„ๆœ‰ๅ‘ๅ›พไธŠ๏ผŒๅฏไปฅๅฎšไน‰ไธ€ไธช้šๆœบๆธธ่ตฐๆจกๅž‹๏ผŒๅณไธ€้˜ถ้ฉฌๅฐ”ๅฏๅคซ้“พ๏ผŒ่ฝฌ็งป็Ÿฉ้˜ต็”ฑไธค้ƒจๅˆ†็š„็บฟๆ€ง็ป„ๅˆ็ป„ๆˆ๏ผŒๅ…ถไธญไธ€้ƒจๅˆ†ๆŒ‰็…ง่ฝฌ็งป็Ÿฉ้˜ต$M$๏ผŒไปŽไธ€ไธช็ป“็‚นๅˆฐ่ฟžๆŽฅๅ‡บ็š„ๆ‰€ๆœ‰็ป“็‚น็š„่ฝฌ็งปๆฆ‚็އ็›ธ็ญ‰๏ผŒๅฆไธ€้ƒจๅˆ†ๆŒ‰็…งๅฎŒๅ…จ้šๆœบ่ฝฌ็งป็Ÿฉ้˜ต๏ผŒไปŽไปปไธ€็ป“็‚นๅˆฐไปปไธ€็ป“็‚น็š„่ฝฌ็งปๆฆ‚็އ้ƒฝๆ˜ฏ$1/n$ใ€‚่ฟ™ไธช้ฉฌๅฐ”ๅฏๅคซ้“พๅญ˜ๅœจๅนณ็จณๅˆ†ๅธƒ๏ผŒๅนณ็จณๅˆ†ๅธƒๅ‘้‡R็งฐไธบ่ฟ™ไธชๆœ‰ PageRankๅ‘ๅ›พ็š„ไธ€่ˆฌ๏ผŒๆปก่ถณ # $$R = d M R + \frac { 1 - d } { n } 1$$ # # ๅ…ถไธญ$d ( 0 \leq d \leq 1 )$ๆ˜ฏ้˜ปๅฐผๅ› ๅญ๏ผŒ1ๆ˜ฏๆ‰€ๆœ‰ๅˆ†้‡ไธบ1็š„$n$็ปดๅ‘้‡ใ€‚ # # 5. PageRank็š„่ฎก็ฎ—ๆ–นๆณ•ๅŒ…ๆ‹ฌ่ฟญไปฃ็ฎ—ๆณ•ใ€ๅน‚ๆณ•ใ€ไปฃๆ•ฐ็ฎ—ๆณ•ใ€‚ # # ๅน‚ๆณ•ๅฐ† PageRank็š„็ญ‰ไปทๅผๅ†™ๆˆ$$R = ( d M + \frac { 1 - d } { n } E ) R = A R$$ # ๅ…ถไธญ$d$ๆ˜ฏ้˜ปๅฐผๅ› ๅญ๏ผŒ$E$ๆ˜ฏๆ‰€ๆœ‰ๅ…ƒ็ด ไธบ1็š„$n$้˜ถๆ–น้˜ตใ€‚ # # PageRank็ฎ—ๆณ•ๅฏไปฅ็œ‹ๅ‡บ$R$ๆ˜ฏไธ€่ˆฌ่ฝฌ็งป็Ÿฉ้˜ต$A$็š„ไธป็‰นๅพๅ‘้‡๏ผŒๅณๆœ€ๅคง็š„็‰นๅพๅ€ผๅฏนๅบ”็š„็‰นๅพๅ‘้‡ใ€‚ # ๅน‚ๆณ•ๅฐฑๆ˜ฏไธ€ไธช่ฎก็ฎ—็Ÿฉ้˜ต็š„ไธป็‰นๅพๅ€ผๅ’Œไธป็‰นๅพๅ‘้‡็š„ๆ–นๆณ•ใ€‚ # # ๆญฅ้ชคๆ˜ฏ๏ผš้€‰ๆ‹ฉๅˆๅง‹ๅ‘้‡$x_0$๏ผ›่ฎก็ฎ—ไธ€่ˆฌ่ฝฌ็งป็Ÿฉ้˜ต$A$๏ผ›่ฟ›่กŒ่ฟญไปฃๅนถ่ง„่ŒƒๅŒ–ๅ‘้‡ # $$y _ { t + 1 } = A x _ { t }$$ # $$x _ { t + 1 } = \frac { y _ { t + 1 } } { \| y _ { t + 1 } \| }$$ # ็›ด่‡ณๆ”ถๆ•›ใ€‚ # + [markdown] colab_type="text" id="iWOZV94kYsbM" # --- # ๅœจๅฎž้™…ๅบ”็”จไธญ่ฎธๅคšๆ•ฐๆฎ้ƒฝไปฅๅ›พ(graph)็š„ๅฝขๅผๅญ˜ๅœจ๏ผŒๆฏ”ๅฆ‚๏ผŒไบ’่”็ฝ‘ใ€็คพไบค็ฝ‘็ปœ้ƒฝๅฏไปฅ็œ‹ไฝœๆ˜ฏไธ€ไธชๅ›พใ€‚ๅ›พๆ•ฐๆฎไธŠ็š„ๆœบๅ™จๅญฆไน ๅ…ทๆœ‰็†่ฎบไธŽๅบ”็”จไธŠ็š„้‡่ฆๆ„ไน‰ใ€‚pageRank็ฎ—ๆณ•ๆ˜ฏๅ›พ็š„้“พๆŽฅๅˆ†ๆž (link analysis)็š„ไปฃ่กจๆ€ง็ฎ—ๆณ•๏ผŒๅฑžไบŽๅ›พๆ•ฐๆฎไธŠ็š„ๆ— ็›‘็ฃๅญฆไน ๆ–นๆณ•ใ€‚ # # pageRank็ฎ—ๆณ•ๆœ€ๅˆไฝœไธบไบ’่”็ฝ‘็ฝ‘้กต้‡่ฆๅบฆ็š„่ฎก็ฎ—ๆ–นๆณ•๏ผŒ1996ๅนด็”ฑpageๅ’ŒBrinๆๅ‡บ๏ผŒๅนถ็”จไบŽ่ฐทๆญŒๆœ็ดขๅผ•ๆ“Ž็š„็ฝ‘้กตๆŽ’ๅบใ€‚ไบ‹ๅฎžไธŠ๏ผŒpageRankๅฏไปฅๅฎšไน‰ๅœจไปปๆ„ๆœ‰ๅ‘ๅ›พไธŠ๏ผŒๅŽๆฅ่ขซๅบ”็”จๅˆฐ็คพไผšๅฝฑๅ“ๅŠ›ๅˆ†ๆžใ€ๆ–‡ๆœฌๆ‘˜่ฆ็ญ‰ๅคšไธช้—ฎ้ข˜ใ€‚ # # pageRank็ฎ—ๆณ•็š„ๅŸบๆœฌๆƒณๆณ•ๆ˜ฏๅœจๆœ‰ๅ‘ๅ›พไธŠๅฎšไน‰ไธ€ไธช้šๆœบๆธธ่ตฐๆจกๅž‹๏ผŒๅณไธ€้˜ถ้ฉฌๅฐ”ๅฏๅคซ้“พ๏ผŒๆ่ฟฐ้šๆœบๆธธ่ตฐ่€…ๆฒฟ็€ๆœ‰ๅ‘ๅ›พ้šๆœบ่ฎฟ้—ฎๅ„ไธช็ป“็‚น็š„่กŒไธบใ€‚ๅœจไธ€ๅฎšๆกไปถไธ‹๏ผŒๆž้™ๆƒ…ๅ†ต่ฎฟ้—ฎๆฏไธช็ป“็‚น็š„ๆฆ‚็އๆ”ถๆ•›ๅˆฐๅนณ็จณๅˆ†ๅธƒ๏ผŒ ่ฟ™ๆ—ถๅ„ไธช็ป“็‚น็š„ๅนณ็จณๆฆ‚็އๅ€ผๅฐฑๆ˜ฏๅ…ถ pageRankๅ€ผ๏ผŒ่กจ็คบ็ป“็‚น็š„้‡่ฆๅบฆใ€‚ pageRankๆ˜ฏ้€’ๅฝ’ๅฎšไน‰็š„๏ผŒpageRank็š„่ฎก็ฎ—ๅฏไปฅ้€š่ฟ‡่ฟญไปฃ็ฎ—ๆณ•่ฟ›่กŒใ€‚ # + colab={} colab_type="code" id="fAN4q0cqYn-f" #https://gist.github.com/diogojc/1338222/84d767a68da711a154778fb1d00e772d65322187 import numpy as np from scipy.sparse import csc_matrix def pageRank(G, s=.85, maxerr=.0001): """ Computes the pagerank for each of the n states Parameters ---------- G: matrix representing state transitions Gij is a binary value representing a transition from state i to j. s: probability of following a transition. 1-s probability of teleporting to another state. maxerr: if the sum of pageranks between iterations is bellow this we will have converged. """ n = G.shape[0] # transform G into markov matrix A A = csc_matrix(G, dtype=np.float) rsums = np.array(A.sum(1))[:, 0] ri, ci = A.nonzero() A.data /= rsums[ri] # bool array of sink states sink = rsums == 0 # Compute pagerank r until we converge ro, r = np.zeros(n), np.ones(n) while np.sum(np.abs(r - ro)) > maxerr: ro = r.copy() # calculate each pagerank at a time for i in range(0, n): # inlinks of state i Ai = np.array(A[:, i].todense())[:, 0] # account for sink states Di = sink / float(n) # account for teleportation to state i Ei = np.ones(n) / float(n) r[i] = ro.dot(Ai * s + Di * s + Ei * (1 - s)) # return normalized pagerank return r / float(sum(r)) # + colab={"base_uri": "https://localhost:8080/", "height": 53} colab_type="code" id="Ds-wQEFFZ1F7" outputId="b2860902-8712-4583-ab47-bec602c6791b" # Example extracted from 'Introduction to Information Retrieval' G = np.array([[0,0,1,0,0,0,0], [0,1,1,0,0,0,0], [1,0,1,1,0,0,0], [0,0,0,1,1,0,0], [0,0,0,0,0,0,1], [0,0,0,0,0,1,1], [0,0,0,1,1,0,1]]) print(pageRank(G,s=.86)) # - # ---- # ๆœฌ็ซ ไปฃ็ ๆฅๆบ๏ผšhttps://github.com/hktxt/Learn-Statistical-Learning-Method # # ๆœฌๆ–‡ไปฃ็ ๆ›ดๆ–ฐๅœฐๅ€๏ผšhttps://github.com/fengdu78/lihang-code # # ไธญๆ–‡ๆณจ้‡Šๅˆถไฝœ๏ผšๆœบๅ™จๅญฆไน ๅˆๅญฆ่€…ๅ…ฌไผ—ๅท๏ผšID:ai-start-com # # ้…็ฝฎ็Žฏๅขƒ๏ผšpython 3.5+ # # ไปฃ็ ๅ…จ้ƒจๆต‹่ฏ•้€š่ฟ‡ใ€‚ # ![gongzhong](../gongzhong.jpg)
src/awesome_python/algorithm/staic_learn/็ฌฌ21็ซ  PageRank็ฎ—ๆณ•/21.PageRank.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 # --- # # Fine-tune a reaction BERT for classification # # > Train a reaction BERT on the USPTO 1k TPL data set. The task is to predict the 1 out of 1000 template classes given the chemical reaction SMILES. The data set is strongly imbalanced and contains noisy reactions. # + # optional import os import numpy as np import pandas as pd import torch import logging import random import pkg_resources import sklearn from rxnfp.models import SmilesClassificationModel logger = logging.getLogger(__name__) # - # ## Track the training # # We will be using wandb to keep track of our training. You can use the an account on [wandb](https://www.wandb.com) or create an own instance following the instruction in the [documentation](https://docs.wandb.com/self-hosted). # # If you then create an `.env` file in the root folder and specify the `WANDB_API_KEY=` (and the `WANDB_BASE_URL=`), you can use dotenv to load those enviroment variables. # optional from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) # ## Loading the training data # + # optional df = pd.read_csv('../data/uspto_1k_TPL/data_set/uspto_1k_TPL_train_valid.tsv.gzip', compression='gzip', sep='\t', index_col=0) df[['canonical_rxn', 'labels']].head() # - # ## Make splits # The data was already shuffled. We take 10% as test set and a small validation set of 604 reactions to keep track of the performance during training. # + # optional train_df = df.iloc[:400000] eval_df = df[['canonical_rxn', 'labels']].iloc[400000:400604] eval_df.columns = ['text', 'labels'] all_train_reactions = train_df.canonical_rxn_with_fragment_info.values.tolist() + train_df.canonical_rxn.values.tolist() corresponding_labels = train_df.labels.values.tolist() + train_df.labels.values.tolist() final_train_df = pd.DataFrame({'text': all_train_reactions, 'labels': corresponding_labels }) final_train_df = final_train_df.sample(frac=1., random_state=42) # - # ## Load model pretrained on a Masked Language Modeling task and train # # This will currently only work if you have installed the library from the github repo with `pip install -e .`, # as the `models/transformers/bert_mlm_1k_tpl` and `models/transformers/bert_class_1k_tpl` model are not included in the pip package. # # optional model_args = { 'wandb_project': 'nmi_uspto_1000_class', 'num_train_epochs': 5, 'overwrite_output_dir': True, 'learning_rate': 2e-5, 'gradient_accumulation_steps': 1, 'regression': False, "num_labels": len(final_train_df.labels.unique()), "fp16": False, "evaluate_during_training": True, 'manual_seed': 42, "max_seq_length": 512, "train_batch_size": 8,"warmup_ratio": 0.00, 'output_dir': '../out/bert_class_1k_tpl'} # optional model_path = pkg_resources.resource_filename("rxnfp", "models/transformers/bert_mlm_1k_tpl") model = SmilesClassificationModel("bert", model_path, num_labels=len(final_train_df.labels.unique()), args=model_args, use_cuda=torch.cuda.is_available()) # optional model.train_model(final_train_df, eval_df=eval_df, acc=sklearn.metrics.accuracy_score, mcc=sklearn.metrics.matthews_corrcoef) # ## Load trained model (that we've trained using this script) # + # optional train_model_path = pkg_resources.resource_filename("rxnfp", "models/transformers/bert_class_1k_tpl") model = SmilesClassificationModel("bert", train_model_path, use_cuda=torch.cuda.is_available()) # - # ## Predictions on test set # optional y_preds = model.predict(test_df.text.values)
nbs/09_fine_tune_bert_on_uspto_1k_tpl.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="8Jc8GPqX_bWH" # # Image Segmentation U-Net # # # + [https://ithelp.ithome.com.tw/articles/10240314](https://ithelp.ithome.com.tw/articles/10240314) # # + [https://www.kaggle.com/tikutiku/hubmap-tilespadded-inference-v2](https://www.kaggle.com/tikutiku/hubmap-tilespadded-inference-v2) # # ็”ฑ ResNet34-CBAM-Hypercol.ipynb ๅ†ๅš่ชฟๆ•ด๏ผŒๅฐ‡ CBAM ๆๅ‰่‡ณ Encoding ้šŽๆฎตๅŸท่กŒ # + [markdown] id="GxlQIguZHOup" # # Load data # + colab={"base_uri": "https://localhost:8080/"} id="N8cxLz_TG4SX" outputId="d47ecb48-ab3d-485d-d815-cdb722e8dafd" from google.colab import drive drive.mount('/content/drive') # + id="ti7b8VbKG6pn" # !tar -xf "/content/drive/MyDrive/Colab Notebooks/annotations.tar.gz" -C /content # !tar -xf "/content/drive/MyDrive/Colab Notebooks/images.tar.gz" -C /content # + id="zUkLAM4lc8FO" import os # https://stackoverflow.com/questions/60058588/tesnorflow-2-0-tf-random-set-seed-not-working-since-i-am-getting-different-resul SEED = 2021 os.environ['PYTHONHASHSEED'] = str(SEED) # + id="sdr4XCqUGW06" import numpy import math import random VERSION = 'ResNet34-UNet-v2' DATA_ROOT_DIR = '/content/' SEED = 2021 IMG_SIZE = (160, 160) NUM_CLASSES = 4 BATCH_SIZE = 25 EPOCHES = 50 import tensorflow.keras as keras import keras.layers as layers import tensorflow as tf def reset_random_seed(): os.environ['PYTHONHASHSEED'] = str(SEED) numpy.random.seed(SEED) random.seed(SEED) tf.random.set_seed(SEED) reset_random_seed() # + id="wjgdgMWsJazR" files = [] for file in os.listdir(DATA_ROOT_DIR + 'images'): # file = Abyssinian_1.jpg if file.endswith('jpg'): fn = file.split('.')[0] if os.path.isfile(DATA_ROOT_DIR + 'annotations/trimaps/' + fn + '.png'): files.append(fn) files = sorted(files) # + colab={"base_uri": "https://localhost:8080/", "height": 417} id="FB58nHX1_YDr" outputId="e6c8d0c3-98f0-4b09-ea36-b616b9e38f80" from IPython.display import display from tensorflow.keras.preprocessing.image import load_img from PIL import ImageOps import PIL # ImageOps.autocontrast() method maximizes (normalize) image contrast. # This function calculates a histogram of the input image, # removes cutoff percent of the lightest and darkest pixels from the histogram, # and remaps the image so that the darkest pixel becomes black (0), # and the lightest becomes white (255). img = PIL.ImageOps.autocontrast(load_img(DATA_ROOT_DIR + 'annotations/trimaps/' + files[0] + '.png')) display(img) # + [markdown] id="1u-iT7E-qCzo" # ## Data Generator # + id="OP7biCTyl3lf" # reference: https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence class OxfordPets(keras.utils.Sequence): def __init__(self, files): self.files = files def __len__(self): return math.ceil(len(self.files) / BATCH_SIZE) def __getitem__(self, index): x, y = [], [] for i in range(index * BATCH_SIZE, min((index+1) * BATCH_SIZE, len(self.files))): # target size in load_img # (img_height, img_width) x.append(numpy.array(load_img(DATA_ROOT_DIR + 'images/' + self.files[i] + '.jpg', target_size = IMG_SIZE), dtype='float32')) y.append(numpy.array(load_img(DATA_ROOT_DIR + 'annotations/trimaps/' + self.files[i] + '.png', target_size = IMG_SIZE, color_mode="grayscale"), dtype='uint8')) return numpy.array(x), numpy.array(y) # + [markdown] id="qKrmNzRtu9t1" # ## Build model # + id="lJwS6xfzYy8x" class ResBlock(keras.Model): def __init__(self, channels, strides=1): super().__init__() self.conv1 = layers.Conv2D(channels, 3, strides=strides, padding='same', use_bias=False) self.bn1 = layers.BatchNormalization() self.conv2 = layers.Conv2D(channels, 3, strides=1, padding='same', use_bias=False) self.bn2 = layers.BatchNormalization() if strides != 1: self.shortcut = keras.Sequential([ layers.Conv2D(channels, 1, strides, padding='same', use_bias=False) ]) else: self.shortcut = keras.Sequential() def call(self, inputs): x = self.conv1(inputs) x = self.bn1(x) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x) shortcut = self.shortcut(inputs) return tf.nn.relu(tf.add(x, shortcut)) def get_config(self): return {} class Encoder(keras.Model): def __init__(self, channels, repeat, strides): super().__init__() self.resBlocks = keras.Sequential() self.resBlocks.add(ResBlock(channels, strides)) for _ in range(1, repeat): self.resBlocks.add(ResBlock(channels, strides=1)) def call(self, inputs): return self.resBlocks(inputs) def get_config(self): return {} class ChannelAttention(keras.Model): def __init__(self, reduction): super().__init__() self.globalMaxPool = layers.GlobalMaxPooling2D(keepdims=True) self.globalAvgPool = layers.GlobalAveragePooling2D(keepdims=True) self.reduction = reduction def build(self, input_shape): self.fc = keras.Sequential([ layers.Conv2D(input_shape[-1]//self.reduction, 3, padding='same'), layers.ReLU(), layers.Conv2D(input_shape[-1], 1, padding='valid') ]) def call(self, inputs): x1 = self.globalMaxPool(inputs) x2 = self.globalAvgPool(inputs) x1 = self.fc(x1) x2 = self.fc(x2) x = tf.nn.sigmoid(layers.add([x1, x2])) return x class SpatialAttention(keras.Model): def __init__(self): super().__init__() self.conv3x3 = layers.Conv2D(1, 3, padding='same') def call(self, inputs): # https://github.com/kobiso/CBAM-tensorflow/blob/master/attention_module.py#L95 x1 = tf.math.reduce_max(inputs, axis=3, keepdims=True) x2 = tf.math.reduce_mean(inputs, axis=3, keepdims=True) x = tf.concat([x1, x2], 3) x = self.conv3x3(x) x = tf.nn.sigmoid(x) return x class CBAM(keras.Model): def __init__(self, reduction): super().__init__() self.channelAttention = ChannelAttention(reduction) self.spaialAttention = SpatialAttention() def call(self, inputs): x = inputs * self.channelAttention(inputs) x = x * self.spaialAttention(x) return x class Decoder(keras.Model): def __init__(self, channels, upsample=True): super().__init__() self.bn1 = layers.BatchNormalization() self.bn2 = layers.BatchNormalization() if upsample: self.upsample = keras.Sequential([ layers.UpSampling2D(2, interpolation='nearest') ]) else: self.upsample = keras.Sequential() self.conv3x3_2 = layers.Conv2D( channels, 3, padding='same', use_bias=False) self.conv1x1 = layers.Conv2D(channels, 1, use_bias=False) def build(self, input_shape): self.conv3x3_1 = layers.Conv2D( input_shape[-1], 3, padding='same', use_bias=False) def call(self, inputs): x = self.bn1(inputs) x = tf.nn.relu(x) x = self.upsample(x) x = self.conv3x3_1(x) x = self.bn2(x) x = tf.nn.relu(x) x = self.conv3x3_2(x) shortcut = self.conv1x1(self.upsample(inputs)) x += shortcut return x def get_config(self): return {} def ResNet34UNetV2(input_shape, num_classes): inputs = keras.Input(shape=input_shape) # Encode by ResNet34 x = layers.Conv2D(64, 7, strides=2, padding='same', use_bias=False)(inputs) x = layers.BatchNormalization()(x) x = tf.nn.relu(x) x0 = layers.MaxPooling2D(3, strides=2, padding='same')(x) # ResNet34 x1 = Encoder(64, 3, strides=1)(CBAM(reduction=16)(x0)) x2 = Encoder(128, 4, strides=2)(CBAM(reduction=16)(x1)) x3 = Encoder(256, 6, strides=2)(CBAM(reduction=16)(x2)) x4 = Encoder(512, 3, strides=2)(CBAM(reduction=16)(x3)) # Center Block y5 = layers.Conv2D(512, 3, padding='same', use_bias=False)(x4) # Decode y4 = Decoder(64)(layers.Concatenate(axis=3)([x4, y5])) y3 = Decoder(64)(layers.Concatenate(axis=3)([x3, y4])) y2 = Decoder(64)(layers.Concatenate(axis=3)([x2, y3])) y1 = Decoder(64)(layers.Concatenate(axis=3)([x1, y2])) y0 = Decoder(64)(y1) # Hypercolumn y4 = layers.UpSampling2D(16, interpolation='bilinear')(y4) y3 = layers.UpSampling2D(8, interpolation='bilinear')(y3) y2 = layers.UpSampling2D(4, interpolation='bilinear')(y2) y1 = layers.UpSampling2D(2, interpolation='bilinear')(y1) hypercolumn = layers.Concatenate(axis=3)([y0, y1, y2, y3, y4]) # Final conv outputs = keras.Sequential([ layers.Conv2D(64, 3, padding='same', use_bias=False), layers.ELU(), layers.Conv2D(num_classes, 1, use_bias=False) ])(hypercolumn) outputs = tf.nn.softmax(outputs) return keras.Model(inputs, outputs) # + [markdown] id="g8EYat7Qnl_h" # ## Start Training! # + colab={"base_uri": "https://localhost:8080/"} id="N3pl6heQGyda" outputId="5386e116-03f3-402f-fd18-36c98ef1af90" keras.backend.clear_session() reset_random_seed() m = ResNet34UNetV2(IMG_SIZE+(3,), NUM_CLASSES) m.summary() # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="HCBsdenDkt5H" outputId="8bedd81c-876e-4e16-b45f-e7893f3c3026" keras.utils.plot_model(m, show_shapes=True) # + colab={"base_uri": "https://localhost:8080/"} id="Fz032A15Yibm" outputId="0d97b3b9-e224-4143-b6fa-cdf883ab4cb2" files = sorted(files) rng = numpy.random.default_rng(SEED) rng.shuffle(files) middle = math.ceil(len(files) * 0.8) train = OxfordPets(files[:middle]) test = OxfordPets(files[middle:]) # ็ขบๅฎšๆฏๆฌก่จ“็ทดๆ™‚ files ็š„้ †ๅบ็š†็›ธๅŒ print(files[:10]) # + colab={"base_uri": "https://localhost:8080/"} id="vP5JiDzoHGF0" outputId="aab7855f-e6ac-4a4d-dc52-205e4cf39b3f" keras.backend.clear_session() reset_random_seed() callbacks = [ keras.callbacks.ModelCheckpoint(DATA_ROOT_DIR + VERSION + ".h5", monitor='val_loss', save_best_only=True, save_weights_only=True) ] m.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy']) history = m.fit(train, validation_data=test, epochs=EPOCHES, callbacks=callbacks) # + [markdown] id="DkebBiCwnrN_" # # Evaluate # + id="6_q6kJKkxlTt" colab={"base_uri": "https://localhost:8080/", "height": 300} outputId="911f286b-e408-4905-c0dc-baccbfd6e165" import matplotlib.pyplot as plt plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label = 'val_loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.ylim([0, 2]) plt.legend(loc='upper right') print(min(history.history['val_loss'])) # + colab={"base_uri": "https://localhost:8080/", "height": 300} id="4SxKc67l22Ve" outputId="1e915d7f-d077-4743-93eb-c442a62d3d3f" plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label='val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.ylim([0, 1]) plt.legend(loc='lower right') print(max(history.history['val_accuracy'])) # + id="KOcUXUSettFI" import json with open(DATA_ROOT_DIR + VERSION + '.json', 'w') as f: data = { 'loss': history.history['loss'], 'val_loss': history.history['val_loss'] } json.dump(data, f) # + [markdown] id="D9n9IpQo3CFc" # ## Show result # + id="wvFFQR-clnMR" def mask_to_img(predict): mask = numpy.argmax(predict, axis=-1) # numpy.expand_dims() expand the shape of an array. # Insert a new axis that will appear at the axis position in the expanded # array shape. mask = numpy.expand_dims(mask, axis = -1) return PIL.ImageOps.autocontrast(keras.preprocessing.image.array_to_img(mask)) # + id="BdcW1UktgyUu" colab={"base_uri": "https://localhost:8080/", "height": 578} outputId="89f03a43-8b4e-42f4-82c5-a541b6a4d57f" demo_data = OxfordPets(files[:20]) demo_res = m.predict(demo_data) plt.figure(figsize=(8, 10)) for i in range(20): plt.subplot(5, 4, i+1) plt.xticks([]) plt.yticks([]) plt.imshow(keras.preprocessing.image.array_to_img(demo_data.__getitem__(0)[0][i])) plt.imshow(mask_to_img(demo_res[i]), cmap='jet', alpha=0.3) plt.show() plt.close() # + id="lsNrNLKuHi3A" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="edbc9dfa-6ced-44d1-dbaa-25d892e394d1" import shutil val_loss = min(history.history['val_loss']) shutil.copy(DATA_ROOT_DIR + VERSION + '.json', '/content/drive/MyDrive/Models/%s-%.4f.json' % (VERSION, val_loss)) shutil.copy(DATA_ROOT_DIR + VERSION + '.h5', '/content/drive/MyDrive/Models/%s-%.4f.h5' % (VERSION, val_loss))
Image-segmentation/OxfordPets/ResNet34-v2/ResNet34-v2.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 # --- # # Adult Dataset # ## Importing the necessary libraries # + # Libraries to work with the datasets import re import numpy as np import pandas as pd # Libraries to plot data import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline # - # ### Importing the normalized dataset # - Importing the CSV resulting file of normalized data. file_name = 'adult_dataset.csv' file_path = 'Results/' + file_name data = pd.read_csv(file_path) data.head() # ### Creating the variables to work with the models. # - Dependent variable: "salary". # - Independent variables: "age", "fnlwgt", "education-num", "capital-gain", "capital-loss", "hours-per-week", # - Dummy variables: "workclass_ Never-worked", "workclass_ Private", "workclass_ Self-employed", "workclass_ Unknown", "workclass_ Without-pay", "marital-status_ Married", "marital-status_ Widowed", "race_ Asian-Pac-Islander, "race_ Black", "race_ Other", "race_ White", "sex_ Male. X = data.drop('salary', axis=1) y = data['salary'] # ### Checking the size of predictors (X) and predictable (y) features (Same quantity of rows) X.shape,y.shape # ### Defining a variable to change the predictors (X) if needed X.columns resources = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week', 'workclass_ Never-worked', 'workclass_ Private', 'workclass_ Self-employed', 'workclass_ Unknown', 'workclass_ Without-pay', 'marital-status_ Married', 'marital-status_ Widowed', 'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White', 'sex_ Male'] X = X[resources] # ### Spliting the dataset into training and test datasets. The test dataset will be 30% of the original dataset. # Library to split the dataset into train and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123) # - New shape of train dataset. X_train.shape, y_train.shape # - New shape of test dataset. X_test.shape, y_test.shape # ### Defining a default class to fit all the models # - Creating class to use for loop all the models. class AuxiliarModel(object): def __init__(self, clf, seed=123, params=None): if params: params['random_state'] = seed self.clf = clf(**params) else: self.clf = clf() def predict(self, x): return self.clf.predict(x) def fit(self,x,y): return self.clf.fit(x,y) def feature_importances(self,x,y): return self.clf.fit(x,y).feature_importances_ def score(self,x,y): return self.clf.score(x,y) def predict_proba(self,x): return self.clf.predict_proba(x) # Libraries to apply the ML models from sklearn.ensemble import (AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier, RandomForestClassifier) from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC, LinearSVC from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import Perceptron from sklearn.linear_model import SGDClassifier from sklearn.tree import DecisionTreeClassifier modelos = [{'name': 'logreg', 'model': LogisticRegression}, {'name': 'etree', 'model': ExtraTreesClassifier}, {'name': 'gradboost', 'model': GradientBoostingClassifier}, {'name': 'adaboost', 'model': AdaBoostClassifier}, {'name': 'SVC', 'model': SVC}, {'name': 'KNN', 'model': KNeighborsClassifier}, {'name': 'GaussianNB', 'model': GaussianNB}, {'name': 'Perceptron', 'model': Perceptron}, {'name': 'LinearSVC', 'model': LinearSVC}, {'name': 'SGD', 'model': SGDClassifier}, {'name': 'Dtree', 'model': DecisionTreeClassifier}, {'name': 'RForest', 'model': RandomForestClassifier} ] # ### Fitting one dataset for all models to check the best ones # - Loop of all models. results = [] for model in modelos: x = AuxiliarModel(clf=model['model']) # train the o model x.fit(X_train, y_train) # generate predictions x_pred = x.predict(X_test) # generate score accuracy = round(x.score(X_test,y_test)*100,2) name_model = re.findall(r"^\w+",str(x.clf)) # features importance if name_model[0] in ['ExtraTreesClassifier', 'GradientBoostingClassifier', 'AdaBoostClassifier', 'DecisionTreeClassifier', 'RandomForestClassifier']: imp_features = x.feature_importances(X_train, y_train) else: imp_features = 'N/A' results.append({'name': model['name'], 'model': model['model'], 'score': accuracy, 'pred': x_pred, 'features_importance': imp_features}) # ### Creating dataframe with results # - The dataframe contains the name of the model, the $R^2$ score for each model, predicted values for each model and the importance of features for the models (for models with this feature available). models = pd.DataFrame(results) # ### Comparing the results among the models # - Returns the coefficient of determination $R^2$ of the prediction by using the score method of each model. models[['name','score']].sort_values(by='score', ascending=False) # - Defining the **two best scores** from database dataframe into new variables. best_1 = models.sort_values(by='score', ascending=False).iloc[0] best_2 = models.sort_values(by='score', ascending=False).iloc[1] # ### Feature Importance # - Collecting **features values** from database based on the **two best models**. best_1_features = best_1['features_importance'] best_2_features = best_2['features_importance'] # - Creating a dataframe from feature importance values collected from database **to plot** the results. # + cols = X_train.columns.values feature_dataframe = pd.DataFrame({'Feature': cols, # Transforming data into percentage of importance of each feature. 'Feature Importance ({})'.format(best_1['name']): best_1_features*100.00, 'Feature Importance ({})'.format(best_2['name']): best_2_features*100.00}) # - feature_dataframe # - Collecting **the 10 best features** to plot for each model (Total features is X variables). # + best_1_top10 = feature_dataframe[['Feature','Feature Importance ({})'.format(best_1['name'])]].\ sort_values(by='Feature Importance ({})'.format(best_1['name']), ascending=False).head(10) best_2_top10 = feature_dataframe[['Feature','Feature Importance ({})'.format(best_2['name'])]].\ sort_values(by='Feature Importance ({})'.format(best_2['name']), ascending=False).head(10) # - # - Plotting the **feature importance** data of the **two best models**. # + fig, (ax1, ax2) = plt.subplots(nrows=2,ncols=1,constrained_layout=True) fig.suptitle('Top 10 - Feature Importance', fontsize=16) fig.set_figheight(8) fig.set_figwidth(8) # Best model 1 ax1.set_title('Model: {}'.format(best_1['name'])) sns.set_color_codes("pastel") sns.barplot(x="Feature Importance ({})".format(best_1['name']), y="Feature", data=best_1_top10, color="b", ax=ax1) # Best model 2 ax2.set_title('Model: {}'.format(best_2['name'])) sns.set_color_codes("pastel") sns.barplot(x="Feature Importance ({})".format(best_2['name']), y="Feature", data=best_2_top10, color="b", ax=ax2) plt.savefig('Figures/adult_feature_importance.png') plt.show() # - # ### Confusion Matrix # Library to work with Confusion Matrix from sklearn.metrics import confusion_matrix from sklearn.metrics import (recall_score, accuracy_score, precision_score, f1_score) # - Collecting predictive values to use with **Confusion Matrix** of the **two best models**. best_1_pred = np.array(best_1['pred']) best_2_pred = np.array(best_2['pred']) # - Plotting the **confusion matrix** of the **two best models**. # + fig, (ax1, ax2) = plt.subplots(nrows=1,ncols=2,constrained_layout=True) fig.suptitle('Confusion Matrix', fontsize=16) fig.set_figheight(5) fig.set_figwidth(10) # Best 1 plot sns.heatmap(confusion_matrix(y_test, best_1_pred), cmap='Blues', annot=True, fmt='2.0f', ax=ax1) ax1.set_title('Model: {}'.format(best_1['name'])) ax1.set_ylabel('F O R E S E E N') ax1.set_xlabel('R E A L') # Best 2 plot sns.heatmap(confusion_matrix(y_test, best_2_pred), cmap='Blues', annot=True, fmt='2.0f', ax=ax2) ax2.set_title('Model: {}'.format(best_2['name'])) ax2.set_ylabel('F O R E S E E N') ax2.set_xlabel('R E A L') plt.savefig('Figures/adult_confusion_matrix.png') plt.show() # - # ### Evaluating Confusion Matrix # - Calculating **precision**, **recall**, **accuracy** and **F1 scores** of the **two best models**. # + # Precision p_score_1 = precision_score(y_test,best_1_pred) p_score_2 = precision_score(y_test,best_2_pred) # Recall r_score_1 = recall_score(y_test,best_1_pred) r_score_2 = recall_score(y_test,best_2_pred) # Accuracy a_score_1 = accuracy_score(y_test,best_1_pred) a_score_2 = accuracy_score(y_test,best_2_pred) # F1 Score f_score_1 = f1_score(y_test,best_1_pred) f_score_2 = f1_score(y_test,best_2_pred) # - # - Creating dataframe with the **precision**, **recall**, **accuracy** and **F1 scores** of the **two best models**. score_results = {'model':['{}'.format(best_1['name']), '{}'.format(best_2['name'])], 'precision':[p_score_1, p_score_2], 'recall': [r_score_1, r_score_2], 'accuracy': [a_score_1, a_score_2], 'f1_score': [f_score_1, f_score_2]} confusion_matrix = pd.DataFrame(score_results) # - Showing **precision**, **recall**, **accuracy** and **F1 scores** results of the **two best models**. confusion_matrix
bsil19151608-DMML1_P_Model_Dataset_1.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] slideshow={"slide_type": "slide"} # # Title: Sample Investigation - Linux, Windows, Network, Office # ### Demo version # **Notebook Version:** 1.0<br> # **Python Version:** Python 3.6 (including Python 3.6 - AzureML)<br> # **Required Packages**: kqlmagic, msticpy, pandas, numpy, matplotlib, networkx, ipywidgets, ipython, scikit_learn, dnspython, ipwhois, folium, maxminddb_geolite2<br> # **Platforms Supported**: # - Azure Notebooks Free Compute # - Azure Notebooks DSVM # - OS Independent # # **Data Sources Required**: # - Log Analytics - SecurityAlert, SecurityEvent (EventIDs 4688 and 4624/25), AuditLog_CL (Linux Auditd), OfficeActivity, AzureNetworkAnalytics_CL, Heartbeat # - (Optional) - VirusTotal (with API key) # # ## Description: # This is an example notebook demonstrating techniques to trace the path of an attacker in an organization. Most of the steps use relatively simple _Log Analytics_ queries but it also includes a few advanced procedures such as: # - Unpacking and decoding Linux Audit logs # - Clustering # # From an initial alert (or suspect IP address) examine activity on a Linux host, a Windows and Office subscription. # Discover malicious activity related to the ip address in each of these. # # The notebook is intended to illustrate the kinds of steps and data query and analysis that you might do in a real hunt or investigation. # # - # <a id='toc'></a> # ## Table of Contents # - [Setup and Authenticate](#setup) # # - [Get Alerts List](#getalertslist) # - [Choose an Alert to investigate](#enteralertid) # - [Extract Properties and entities from alert](#extractalertproperties) # - [Basic IP Checks](#basic_ip_checks) # - [Check the IP Address for known C2 addresses](#check_ip_ti) # - [See What's going on on the Affected Host - Linux](#alerthost) # - [Event Types collected](#linux_event_types) # - [Failure Events](#linux_failure_events) # - [Extract IPs from all Events](#linux_extract_ips) # - [Get Logins with IP Address Recorded](#linux_login_ips) # - [What's happening in these sessions?](#linux_login_sessions) # - [Find Distinctive Process Patterns - Clustering](#linux_proc_cluster) # - [Alert Host Network Data](#alert_host_net) # - [Check Communications with Other Hosts](#comms_to_other_hosts) # - [GeoLocation Mapping](#geomap_lx_ips) # - [Have any other hosts been communicating with this address(es)?](#other_hosts_to_ips) # - [Other Hosts Communicating with IP](#other_host_investigate) # - [Check Host Logons](#host_logons) # - [Examine a Logon Session](#examine_win_logon_sess) # - [Unusual Processes on Host - Clustering](#process_clustering) # - [Processes for Selected LogonId](#process_session) # - [Other Events on the Host](#other_win_events) # - [Office 365 Activity](#o365) # - [Summary](#summary) # - [Appendices](#appendices) # - [Saving data to Excel](#appendices) # # <a id='setup'></a>[Contents](#toc) # # Setup # # Make sure that you have installed packages specified in the setup (uncomment the lines to execute) # # ## Install Packages # The first time this cell runs for a new Azure Notebooks project or local Python environment it will take several minutes to download and install the packages. In subsequent runs it should run quickly and confirm that package dependencies are already installed. Unless you want to upgrade the packages you can feel free to skip execution of the next cell. # # If you see any import failures (```ImportError```) in the notebook, please re-run this cell and answer 'y', then re-run the cell where the failure occurred. # # Note you may see some warnings about package incompatibility with certain packages. This does not affect the functionality of this notebook but you may need to upgrade the packages producing the warnings to a more recent version. # + import sys import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) MIN_REQ_PYTHON = (3,6) if sys.version_info < MIN_REQ_PYTHON: print('Check the Kernel->Change Kernel menu and ensure that Python 3.6') print('or later is selected as the active kernel.') sys.exit("Python %s.%s or later is required.\n" % MIN_REQ_PYTHON) # Package Installs - try to avoid if they are already installed try: import msticpy.sectools as sectools import Kqlmagic from dns import reversename, resolver from ipwhois import IPWhois import folium print('If you answer "n" this cell will exit with an error in order to avoid the pip install calls,') print('This error can safely be ignored.') resp = input('msticpy and Kqlmagic packages are already loaded. Do you want to re-install? (y/n)') if resp.strip().lower() != 'y': sys.exit('pip install aborted - you may skip this error and continue.') except ImportError: pass print('\nPlease wait. Installing required packages. This may take a few minutes...') # !pip install git+https://github.com/microsoft/msticpy --upgrade --user # !pip install Kqlmagic --no-cache-dir --upgrade --user # Additional packages used in this notebook. # !pip install dnspython --upgrade # !pip install ipwhois --upgrade # !pip install folium --upgrade # Uncomment to refresh the maxminddb database # # !pip install maxminddb-geolite2 --upgrade print('To ensure that the latest versions of the installed libraries ' 'are used, please restart the current kernel and run ' 'the notebook again skipping this cell.') # + # Imports import sys import warnings MIN_REQ_PYTHON = (3,6) if sys.version_info < MIN_REQ_PYTHON: print('Check the Kernel->Change Kernel menu and ensure that Python 3.6') print('or later is selected as the active kernel.') sys.exit("Python %s.%s or later is required.\n" % MIN_REQ_PYTHON) import numpy as np from IPython import get_ipython from IPython.display import display, HTML, Markdown import ipywidgets as widgets from ipywidgets import interactive import matplotlib.pyplot as plt import seaborn as sns sns.set() import networkx as nx import pandas as pd pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 50) pd.set_option('display.max_colwidth', 100) import msticpy.sectools as sectools import msticpy.nbtools as mas import msticpy.nbtools.kql as qry import msticpy.nbtools.nbdisplay as nbdisp from msticpy.sectools.geoip import GeoLiteLookup import platform from datetime import datetime, timedelta from dns import reversename, resolver from ipwhois import IPWhois # Some of our dependencies (networkx) still use deprecated Matplotlib # APIs - we can't do anything about it so suppress them from view from matplotlib import MatplotlibDeprecationWarning warnings.simplefilter("ignore", category=MatplotlibDeprecationWarning) WIDGET_DEFAULTS = {'layout': widgets.Layout(width='95%'), 'style': {'description_width': 'initial'}} display(HTML(mas.util._TOGGLE_CODE_PREPARE_STR)) # - # ### Copy Last Query to Clipboard # This section adds an IPython magic command 'la'. The magic is used as follows: # # ```%la [pythonvar|string]``` # # If used with no arguments it will copy the last KQL query to clipboard and display a link to take you to the Sentinel/Log Analytics portal. If the argument is a variable the value of the variable is copied, otherwise the string is copied. # # When using the **%%la** cell magic form the entire cell is copied to the clipboard. # # The URL uses the current config settings for workspace and subscription. # # + from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic) from collections import OrderedDict def copy_to_clipboard(copy_text): pd.DataFrame([copy_text]).to_clipboard(index=False,header=False) LA_URL=('https://ms.portal.azure.com/' '?feature.showassettypes=Microsoft_Azure_Security_Insights_SecurityInsightsDashboard' '#blade/Microsoft_Azure_Security_Insights/MainMenuBlade/7' '/subscriptionId/{sub_id}' '/resourceGroup/{res_group}' '/workspaceName/{ws_name}') LA_URL_BARE=('https://ms.portal.azure.com/' '?feature.showassettypes=Microsoft_Azure_Security_Insights_SecurityInsightsDashboard' '#blade/Microsoft_Azure_Security_Insights/MainMenuBlade/') @register_line_cell_magic def la(line, cell=None): KQL_MAGIC_RESULT = '_kql_raw_result_' #import pdb; pdb.set_trace() if not cell and not line or line.strip() == KQL_MAGIC_RESULT: if KQL_MAGIC_RESULT in globals(): copy_to_clipboard(globals()[KQL_MAGIC_RESULT].query) print('Last kql query copied to clipboard.') elif line and cell is None: if line in globals(): copy_to_clipboard(globals()[line]) print(f'Value of {line} copied to clipboard.') elif line in locals(): copy_to_clipboard(locals()[line]) print(f'Value of {line} copied to clipboard.') else: copy_to_clipboard(line) print(f'Copied to clipboard.') else: copy_to_clipboard(cell) print(f'Copied to clipboard.') try: ws_config = WorkspaceConfig(ws_config_file) url = LA_URL.format(sub_id=ws_config['subscription_id'], res_group=ws_config['resource_group'], ws_name=ws_config['workspace_name']) except: url = LA_URL_BARE return HTML(f'<a target="_new" href="{url}">Open Log Analytics</a>') del la # Create an observation collector list from collections import namedtuple Observation = namedtuple('Observation', ['caption', 'description', 'item', 'link']) observation_list = OrderedDict() def display_observation(observation): display(Markdown(f'### {observation.caption}')) display(Markdown(observation.description)) display(Markdown(f'[Go to details](#{observation.link})')) display(observation.item) def add_observation(observation): observation_list[observation.caption] = observation # + [markdown] tags=["remove"] # ### Get WorkspaceId # To find your Workspace Id go to [Log Analytics](https://ms.portal.azure.com/#blade/HubsExtension/Resources/resourceType/Microsoft.OperationalInsights%2Fworkspaces). Look at the workspace properties to find the ID. # + tags=["todo"] import os from msticpy.nbtools.wsconfig import WorkspaceConfig ws_config_file = 'config.json' WORKSPACE_ID = None TENANT_ID = None try: ws_config = WorkspaceConfig(ws_config_file) display(Markdown(f'Read Workspace configuration from local config.json for workspace **{ws_config["workspace_name"]}**')) for cf_item in ['tenant_id', 'subscription_id', 'resource_group', 'workspace_id', 'workspace_name']: display(Markdown(f'**{cf_item.upper()}**: {ws_config[cf_item]}')) if ('cookiecutter' not in ws_config['workspace_id'] or 'cookiecutter' not in ws_config['tenant_id']): WORKSPACE_ID = ws_config['workspace_id'] TENANT_ID = ws_config['tenant_id'] except: pass if not WORKSPACE_ID or not TENANT_ID: display(Markdown('**Workspace configuration not found.**\n\n' 'Please go to your Log Analytics workspace, copy the workspace ID' ' and/or tenant Id and paste here.<br> ' 'Or read the workspace_id from the config.json in your Azure Notebooks project.')) ws_config = None ws_id = mas.GetEnvironmentKey(env_var='WORKSPACE_ID', prompt='Please enter your Log Analytics Workspace Id:', auto_display=True) ten_id = mas.GetEnvironmentKey(env_var='TENANT_ID', prompt='Please enter your Log Analytics Tenant Id:', auto_display=True) # - # ### Authenticate to Log Analytics # If you are using user/device authentication, run the following cell. # - Click the 'Copy code to clipboard and authenticate' button. # - This will pop up an Azure Active Directory authentication dialog (in a new tab or browser window). The device code will have been copied to the clipboard. # - Select the text box and paste (Ctrl-V/Cmd-V) the copied value. # - You should then be redirected to a user authentication page where you should authenticate with a user account that has permission to query your Log Analytics workspace. # # Use the following syntax if you are authenticating using an Azure Active Directory AppId and Secret: # ``` # # %kql loganalytics://tenant(aad_tenant).workspace(WORKSPACE_ID).clientid(client_id).clientsecret(client_secret) # ``` # instead of # ``` # # %kql loganalytics://code().workspace(WORKSPACE_ID) # ``` # # Note: you may occasionally see a JavaScript error displayed at the end of the authentication - you can safely ignore this.<br> # On successful authentication you should see a ```popup schema``` button. # + tags=["todo"] if not WORKSPACE_ID or not TENANT_ID: try: WORKSPACE_ID = ws_id.value TENANT_ID = ten_id.value except NameError: raise ValueError('No workspace or Tenant Id.') mas.kql.load_kql_magic() # %kql loganalytics://code().tenant(TENANT_ID).workspace(WORKSPACE_ID) # - # %kql search * | summarize RowCount=count() by Type | project-rename Table=Type la_table_set = _kql_raw_result_.to_dataframe() table_index = la_table_set.set_index('Table')['RowCount'].to_dict() display(Markdown('Current data in workspace')) display(la_table_set.T) # <a id='enteralertid'></a>[Contents](#toc) # # Choose Alert to Investigate # Pick an alert from a list of retrieved alerts. # # This section extracts the alert information and entities into a SecurityAlert object allowing us to query the properties more reliably. # # In particular, we use the alert to automatically provide parameters for queries and UI elements. # Subsequent queries will use properties like the host name and derived properties such as the OS family (Linux or Windows) to adapt the query. Query time selectors like the one above will also default to an origin time that matches the alert selected. # # The alert view below shows all of the main properties of the alert plus the extended property dictionary (if any) and JSON representations of the Entity. # + [markdown] tags=["todo"] # ### Choose Timespan to look for alerts # # Specify a time range to search for alerts. One this is set run the following cell to retrieve any alerts in that time window.<br> # You can change the time range and re-run the queries until you find the alerts that you want. # - alert_q_times = mas.QueryTime(units='day', max_before=20, before=2, max_after=1) alert_q_times.display() # ### Select alert from list # As you select an alert, the main properties will be shown below the list.<br> # Use the filter box to narrow down your search to any substring in the AlertName. # + # Query for alerts alert_counts = qry.list_alerts_counts(provs=[alert_q_times]) alert_list = qry.list_alerts(provs=[alert_q_times]) print(len(alert_counts), ' distinct alert types') print(len(alert_list), ' distinct alerts') from msticpy.nbtools.entityschema import GeoLocation from msticpy.sectools.geoip import GeoLiteLookup iplocation = GeoLiteLookup() security_alert = None alert_ip_entities = [] def show_full_alert(selected_alert): global security_alert, alert_ip_entities security_alert = mas.SecurityAlert(alert_select.selected_alert) alert_ip_entities = get_alert_ips(security_alert) mas.disp.display_alert(security_alert, show_entities=True) def get_alert_ips(alert): alert_ip_entities = [e for e in alert.entities if isinstance(e, mas.IpAddress)] # Extract any additional IP addresses from text in the alert ioc_extractor = sectools.IoCExtract() alert_iocs = ioc_extractor.extract(src=str(alert)) addl_ip_addrs = alert_iocs.get('ipv4', []) if addl_ip_addrs: _, ip_entities = iplocation.lookup_ip(ip_addr_list=addl_ip_addrs) current_ips = [e.Address for e in alert_ip_entities] for new_ip_entity in ip_entities: if new_ip_entity.Address not in current_ips: alert_ip_entities.append(new_ip_entity) return alert_ip_entities # Display the alert list alert_select = mas.AlertSelector(alerts=alert_list, action=show_full_alert) alert_select.display() # - # # See what is happening on the host in this Alert # print(security_alert.primary_host) print(security_alert.TimeGenerated) # ### Observations # - We can see that it's a Linux host and can view the alert time. # - Set the time boundaries to be a hour or two either side of the alert # %config Kqlmagic.auto_dataframe=False host1_q_times = mas.QueryTime(label='Set time bounds for alert host - at least 1hr either side of the alert', units='hour', max_before=48, before=2, after=1, max_after=24, origin_time=security_alert.StartTimeUtc) host1_q_times.display() # #### Data is in Raw Auditd format so we need to unpack and re-assemble it # + import pickle from os import path # Retrieve Linux auditd events linux_events = r''' AuditLog_CL | where Computer has '{hostname}' | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | extend mssg_parts = extract_all(@"type=(?P<type>[^\s]+)\s+msg=audit\((?P<mssg_id>[^)]+)\):\s+(?P<mssg>[^\r]+)\r?", dynamic(['type', 'mssg_id', 'mssg']), RawData) | extend mssg_type = tostring(mssg_parts[0][0]), mssg_id = tostring(mssg_parts[0][1]) | project TenantId, TimeGenerated, Computer, mssg_type, mssg_id, mssg_parts | extend mssg_content = split(mssg_parts[0][2],' ') | extend typed_mssg = pack(mssg_type, mssg_content) | summarize AuditdMessage = makelist(typed_mssg) by TenantId, TimeGenerated, Computer, mssg_id '''.format(start=host1_q_times.start, end=host1_q_times.end, hostname=security_alert.hostname) _PICKLE_FILE = 'lx_auditd.cache' linux_events_all = None if path.exists(_PICKLE_FILE): with open(_PICKLE_FILE, 'rb') as cache_file: linux_events_all = pickle.load(cache_file) if linux_events_all is None: print('getting data...') # %kql -query linux_events linux_events_df = _kql_raw_result_.to_dataframe() print(f'{len(linux_events_df)} raw auditd mssgs downloaded') import codecs from datetime import datetime encoded_params = {'EXECVE': {'a0', 'a1', 'a2', 'a3', 'arch'}, 'PROCTITLE': {'proctitle'}, 'USER_CMD': {'cmd'}} def unpack_auditd(audit_str): event_dict = {} for record in audit_str: for rec_key, rec_val in record.items(): rec_dict = {} encoded_fields_map = encoded_params.get(rec_key, None) for rec_item in rec_val: rec_split = rec_item.split('=', maxsplit=1) if len(rec_split) == 1: rec_dict[rec_split[0]] = None continue if (not encoded_fields_map or rec_split[1].startswith('"') or rec_split[0] not in encoded_fields_map): field_value = rec_split[1].strip('\"') else: try: field_value = codecs.decode(rec_split[1], 'hex').decode('utf-8') except: field_value = rec_split[1] print(rec_val) print('ERR:', rec_key, rec_split[0], rec_split[1], type(rec_split[1])) rec_dict[rec_split[0]] = field_value event_dict[rec_key] = rec_dict return event_dict USER_START = {'pid': 'int', 'uid': 'int', 'auid': 'int', 'ses': 'int', 'msg': None, 'acct': None, 'exe': None, 'hostname': None, 'addr': None, 'terminal': None, 'res': None} FIELD_DEFS = {'SYSCALL': {'success': None, 'ppid': 'int', 'pid': 'int', 'auid': 'int', 'uid': 'int', 'gid': 'int', 'euid': 'int', 'egid': 'int', 'ses': 'int', 'exe': None, 'com': None}, 'CWD': {'cwd': None}, 'PROCTITLE': {'proctitle': None}, 'LOGIN': {'pid': 'int', 'uid': 'int', 'tty': None, 'old-ses': 'int', 'ses': 'int', 'res': None}, 'EXECVE': {'argc': 'int', 'a0': None, 'a1': None, 'a2': None}, 'USER_START': USER_START, 'USER_END': USER_START, 'CRED_DISP': USER_START, 'USER_ACCT': USER_START, 'CRED_ACQ': USER_START, 'USER_CMD': {'pid': 'int', 'uid': 'int', 'auid': 'int', 'ses': 'int', 'msg': None, 'cmd': None, 'terminal': None, 'res': None}, } def extract_event(message_dict): if 'SYSCALL' in message_dict: proc_create_dict = {} for mssg_type in ['SYSCALL', 'CWD', 'EXECVE', 'PROCTITLE']: if (not mssg_type in message_dict or not mssg_type in FIELD_DEFS) : continue for fieldname, conv in FIELD_DEFS[mssg_type].items(): value = message_dict[mssg_type].get(fieldname, None) if not value: continue if conv: if conv == 'int': value = int(value) if value == 4294967295: value = -1 proc_create_dict[fieldname] = value if mssg_type == 'EXECVE': args = int(proc_create_dict.get('argc', 1)) arg_strs = [] for arg_idx in range(0, args): arg_strs.append(proc_create_dict.get(f'a{arg_idx}', '')) proc_create_dict['cmdline'] = ' '.join(arg_strs) return 'SYSCALL', proc_create_dict else: event_dict = {} for mssg_type, mssg in message_dict.items(): if mssg_type in FIELD_DEFS: for fieldname, conv in FIELD_DEFS[mssg_type].items(): value = message_dict[mssg_type].get(fieldname, None) if conv: if conv == 'int': value = int(value) if value == 4294967295: value = -1 event_dict[fieldname] = value else: event_dict.update(message_dict[mssg_type]) return list(message_dict.keys())[0], event_dict def move_cols_to_front(df, column_count): """Reorder columms to put the last column count cols to front.""" return df[list(df.columns[-column_count:]) + list(df.columns[:-column_count])] def extract_events_to_df(data, event_type=None, verbose=False): if verbose: start_time = datetime.utcnow() print(f'Unpacking auditd messages for {len(data)} events...') tmp_df = (data.apply(lambda x: extract_event(unpack_auditd(x.AuditdMessage)), axis=1, result_type='expand') .rename(columns={0: 'EventType', 1: 'EventData'}) ) # if only one type of event is requested if event_type: tmp_df = tmp_df[tmp_df['EventType'] == event_type] if verbose: print(f'Event subset = ', event_type, ' (events: {len(tmp_df)})') if verbose: print('Building output dataframe...') tmp_df = (tmp_df.apply(lambda x: pd.Series(x.EventData), axis=1) .merge(tmp_df[['EventType']], left_index=True, right_index=True) .merge(data.drop(['AuditdMessage'], axis=1), how='inner', left_index=True, right_index=True) .dropna(axis=1, how='all')) if verbose: print('Fixing timestamps...') # extract real timestamp from mssg_id tmp_df['TimeStamp'] = (tmp_df.apply(lambda x: datetime.utcfromtimestamp(float(x.mssg_id.split(':')[0])), axis=1)) tmp_df = (tmp_df.drop(['TimeGenerated'], axis=1) .rename(columns={'TimeStamp': 'TimeGenerated'}) .pipe(move_cols_to_front, column_count=5)) if verbose: print(f'Complete. {len(tmp_df)} output rows', end=' ') delta = datetime.utcnow() - start_time print(f'time: {delta.seconds + delta.microseconds/1_000_000} sec') return tmp_df def get_event_subset(data, event_type): return (data[data['EventType'] == event_type] .dropna(axis=1, how='all') .infer_objects()) if linux_events_all is None: linux_events_all = extract_events_to_df(linux_events_df, verbose=True) with open(_PICKLE_FILE, 'ab') as cache_file: print('Writing cache file') pickle.dump(linux_events_all, cache_file) print(f'{len(linux_events_all)} events read.') # - # <a id='linux_login_ips'></a>[Contents](#toc) # ## Get Any External Logins (that have an IP Address Recorded) # + lx_proc_create = get_event_subset(linux_events_all,'SYSCALL') print(f'{len(lx_proc_create)} Process Create Events') lx_login = (get_event_subset(linux_events_all, 'LOGIN') .merge(get_event_subset(linux_events_all, 'CRED_ACQ'), how='inner', left_on=['old-ses', 'pid', 'uid'], right_on=['ses', 'pid', 'uid'], suffixes=('', '_cred')).drop(['old-ses','TenantId_cred', 'Computer_cred'], axis=1) .dropna(axis=1, how='all')) print(f'{len(lx_login)} Login Events') logins_with_ips = (lx_login[lx_login['addr'] != '?'] [['Computer', 'TimeGenerated','pid', 'ses', 'acct', 'addr', 'exe', 'hostname', 'msg', 'res_cred', 'ses_cred', 'terminal']]) if len(logins_with_ips) > 0: display(logins_with_ips) # add the source IPs if not alert new_ips = logins_with_ips['addr'].drop_duplicates().tolist() current_ips = [e.Address for e in alert_ip_entities] for new_ip in new_ips: if new_ip not in current_ips: ip_entity = mas.IpAddress(Address=new_ip) iplocation.lookup_ip(ip_entity=ip_entity) alert_ip_entities.append(ip_entity) display(Markdown('### What is happening in these sessions?')) # Mapping to Windows-like event to work more easily with clustering lx_to_proc_create = {'acct': 'SubjectUserName', 'uid': 'SubjectUserSid', 'user': 'SubjectUserName', 'ses': 'SubjectLogonId', 'pid': 'NewProcessId', 'exe': 'NewProcessName', 'ppid': 'ProcessId', 'cmdline': 'CommandLine',} proc_create_to_lx = {'SubjectUserName': 'acct', 'SubjectUserSid': 'uid', 'SubjectUserName': 'user', 'SubjectLogonId': 'ses', 'NewProcessId': 'pid', 'NewProcessName': 'exe', 'ProcessId': 'ppid', 'CommandLine': 'cmdline',} lx_to_logon = {'acct': 'SubjectUserName', 'auid': 'SubjectUserSid', 'user': 'TargetUserName', 'uid': 'TargetUserSid', 'ses': 'TargetLogonId', 'exe': 'LogonProcessName', 'terminal': 'LogonType', 'msg': 'AuthenticationPackageName', 'res': 'Status', 'addr': 'IpAddress', 'hostname': 'WorkstationName',} logon_to_lx = {'SubjectUserName': 'acct', 'SubjectUserSid': 'auid', 'TargetUserName': 'user', 'TargetUserSid': 'uid', 'TargetLogonId': 'ses', 'LogonProcessName': 'exe', 'LogonType': 'terminal', 'AuthenticationPackageName': 'msg', 'Status': 'res', 'IpAddress': 'addr', 'WorkstationName': 'hostname',} lx_proc_create_trans = lx_proc_create.rename(columns=lx_to_proc_create) lx_login_trans = lx_login.rename(columns=lx_to_logon) print('analyzing data...') from msticpy.sectools.eventcluster import dbcluster_events, add_process_features feature_procs_h1 = add_process_features(input_frame=lx_proc_create_trans, path_separator=security_alert.path_separator) # you might need to play around with the max_cluster_distance parameter. # decreasing this gives more clusters. (clus_events, dbcluster, x_data) = dbcluster_events(data=feature_procs_h1, cluster_columns=['commandlineTokensFull', 'pathScore', 'SubjectUserSid'], time_column='TimeGenerated', max_cluster_distance=0.0001) print('Number of input events:', len(feature_procs_h1)) print('Number of clustered events:', len(clus_events)) (clus_events.sort_values('TimeGenerated')[['TimeGenerated', 'LastEventTime', 'NewProcessName', 'CommandLine', 'ClusterSize', 'commandlineTokensFull', 'SubjectLogonId', 'SubjectUserSid', 'pathScore', 'isSystemSession']] .sort_values('ClusterSize', ascending=True)); def view(x=''): procs = (clus_events[clus_events['SubjectLogonId']==x] [['TimeGenerated', 'NewProcessName','CommandLine', 'NewProcessId', 'SubjectUserSid', 'cwd', 'ClusterSize', 'SubjectLogonId']]) display(Markdown(f'{len(procs)} process events')) display(procs.query('SubjectUserSid != 0')) items = logins_with_ips['ses'].unique().tolist() w = widgets.Select(options=items, description='Select Session to view', **WIDGET_DEFAULTS) interactive(view, x=w) # - # ### Observations # - We can see that the attacker is retrieve host information including contents of /etc/passwd. # - Looks like a shell script is being downloaded and set as executable. # - Finally, looks like something is happening with the cron scheduler - this is just listing crontab but likely this is a precursor to installing a persistent presence on the machine. # <a id='alert_host_net'></a>[Contents](#toc) # # Host Network Data # + from datetime import timedelta import folium from folium.plugins import MarkerCluster from numbers import Number import warnings host_entities = [e for e in security_alert.entities if isinstance(e, mas.Host)] if len(host_entities) == 1: alert_host_entity = host_entities[0] host_name = alert_host_entity.HostName resource = alert_host_entity.AzureID else: host_name = None alert_host_entity = None print('Error: Could not determine host entity from alert.') def create_ip_map(): folium_map = folium.Map(zoom_start=7, tiles=None, width='100%', height='100%') folium_map.add_tile_layer(name='IPEvents') return folium_map def add_ip_cluster(folium_map, ip_entities, alert=None, **icon_props): if not folium_map: folium_map = create_ip_map() for ip_entity in ip_entities: if not (isinstance(ip_entity.Location.Latitude, Number) and isinstance(ip_entity.Location.Longitude, Number)): warnings.warn("Invalid location information for IP: " + ip_entity.Address, RuntimeWarning) continue loc_props = ', '.join([f'{key}={val}' for key, val in ip_entity.Location.properties.items() if val]) popup_text = "{loc_props}<br>{IP}".format(IP=ip_entity.Address, loc_props=loc_props) tooltip_text = '{City}, {CountryName}'.format(**ip_entity.Location.properties) if alert: popup_text = f'{popup_text}<br>{alert.AlertName}' if ip_entity.AdditionalData: addl_props = ', '.join([f'{key}={val}' for key, val in ip_entity.AdditionalData.items() if val]) popup_text = f'{popup_text}<br>{addl_props}' tooltip_text = f'{tooltip_text}, {addl_props}' marker = folium.Marker( location = [ip_entity.Location.Latitude, ip_entity.Location.Longitude], popup=popup_text, tooltip=tooltip_text, icon=folium.Icon(**icon_props) ) marker.add_to(folium_map) return folium_map print('Looking for IP addresses of ', host_name) aznet_query = ''' AzureNetworkAnalytics_CL | where VirtualMachine_s has \'{host}\' | where ResourceType == 'NetworkInterface' | top 1 by TimeGenerated desc | project PrivateIPAddresses = PrivateIPAddresses_s, PublicIPAddresses = PublicIPAddresses_s '''.format(host=host_name) # %kql -query aznet_query az_net_df = _kql_raw_result_.to_dataframe() oms_heartbeat_query = ''' Heartbeat | where Computer has \'{host}\' | top 1 by TimeGenerated desc nulls last | project ComputerIP, OSType, OSMajorVersion, OSMinorVersion, ResourceId, RemoteIPCountry, RemoteIPLatitude, RemoteIPLongitude, SourceComputerId '''.format(host=host_name) # %kql -query oms_heartbeat_query oms_heartbeat_df = _kql_raw_result_.to_dataframe() #display(oms_heartbeat_df[['ComputerIP']]) #display(az_net_df) print('getting data...') # Get the host entity and add this IP and system info to the try: if not inv_host_entity: inv_host_entity = mas.Host() inv_host_entity.HostName = host_name except NameError: inv_host_entity = mas.Host() inv_host_entity.HostName = host_name def convert_to_ip_entities(ip_str): ip_entities = [] if ip_str: if ',' in ip_str: addrs = ip_str.split(',') elif ' ' in ip_str: addrs = ip_str.split(' ') else: addrs = [ip_str] for addr in addrs: ip_entity = mas.IpAddress() ip_entity.Address = addr.strip() iplocation.lookup_ip(ip_entity=ip_entity) ip_entities.append(ip_entity) print(addr) return ip_entities # Add this information to our inv_host_entity if len(az_net_df) == 1: priv_addr_str = az_net_df['PrivateIPAddresses'].loc[0] inv_host_entity.properties['private_ips'] = convert_to_ip_entities(priv_addr_str) pub_addr_str = az_net_df['PublicIPAddresses'].loc[0] inv_host_entity.properties['public_ips'] = convert_to_ip_entities(pub_addr_str) retrieved_address = [ip.Address for ip in inv_host_entity.properties['public_ips']] if len(oms_heartbeat_df) == 1: if oms_heartbeat_df['ComputerIP'].loc[0]: oms_address = oms_heartbeat_df['ComputerIP'].loc[0] if oms_address not in retrieved_address: ip_entity = mas.IpAddress() ip_entity.Address = oms_address iplocation.lookup_ip(ip_entity=ip_entity) inv_host_entity.properties['public_ips'].append(ip_entity) inv_host_entity.OSFamily = oms_heartbeat_df['OSType'].loc[0] inv_host_entity.AdditionalData['OSMajorVersion'] = oms_heartbeat_df['OSMajorVersion'].loc[0] inv_host_entity.AdditionalData['OSMinorVersion'] = oms_heartbeat_df['OSMinorVersion'].loc[0] inv_host_entity.AdditionalData['SourceComputerId'] = oms_heartbeat_df['SourceComputerId'].loc[0] # print('Updated Host Entity\n') # print(inv_host_entity) display(Markdown('### Flow Time and Protocol Distribution')) # Azure Network Analytics Base Query az_net_analytics_query =r''' AzureNetworkAnalytics_CL | where SubType_s == 'FlowLog' | where FlowStartTime_t >= datetime({start}) | where FlowEndTime_t <= datetime({end}) | project TenantId, TimeGenerated, FlowStartTime = FlowStartTime_t, FlowEndTime = FlowEndTime_t, FlowIntervalEndTime = FlowIntervalEndTime_t, FlowType = FlowType_s, ResourceGroup = split(VM_s, '/')[0], VMName = split(VM_s, '/')[1], VMIPAddress = VMIP_s, PublicIPs = extractall(@"([\d\.]+)[|\d]+", dynamic([1]), PublicIPs_s), SrcIP = SrcIP_s, DestIP = DestIP_s, ExtIP = iif(FlowDirection_s == 'I', SrcIP_s, DestIP_s), L4Protocol = L4Protocol_s, L7Protocol = L7Protocol_s, DestPort = DestPort_d, FlowDirection = FlowDirection_s, AllowedOutFlows = AllowedOutFlows_d, AllowedInFlows = AllowedInFlows_d, DeniedInFlows = DeniedInFlows_d, DeniedOutFlows = DeniedOutFlows_d, RemoteRegion = AzureRegion_s, VMRegion = Region_s | extend AllExtIPs = iif(isempty(PublicIPs), pack_array(ExtIP), iif(isempty(ExtIP), PublicIPs, array_concat(PublicIPs, pack_array(ExtIP))) ) | project-away ExtIP | mvexpand AllExtIPs {where_clause} ''' start = security_alert.StartTimeUtc - timedelta(seconds=(10 * 60 * 60)) end = security_alert.StartTimeUtc + timedelta(seconds=(5 * 60 * 60)) ### Flow Time and Protocol Distribution all_alert_host_ips = inv_host_entity.private_ips + inv_host_entity.public_ips host_ips = {'\'{}\''.format(i.Address) for i in all_alert_host_ips} alert_host_ip_list = ','.join(host_ips) az_ip_where = f''' | where (VMIPAddress in ({alert_host_ip_list}) or SrcIP in ({alert_host_ip_list}) or DestIP in ({alert_host_ip_list}) ) and (AllowedOutFlows > 0 or AllowedInFlows > 0)''' print('getting data...', end=' ') az_net_query_byip = az_net_analytics_query.format(where_clause=az_ip_where, start=start, end=end) net_default_cols = ['FlowStartTime', 'FlowEndTime', 'VMName', 'VMIPAddress', 'PublicIPs', 'SrcIP', 'DestIP', 'L4Protocol', 'L7Protocol', 'DestPort', 'FlowDirection', 'AllowedOutFlows', 'AllowedInFlows'] # %kql -query az_net_query_byip az_net_comms_df = _kql_raw_result_.to_dataframe() print('done') import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") az_net_comms_df['TotalAllowedFlows'] = az_net_comms_df['AllowedOutFlows'] + az_net_comms_df['AllowedInFlows'] sns.catplot(x="L7Protocol", y="TotalAllowedFlows", col="FlowDirection", data=az_net_comms_df) sns.relplot(x="FlowStartTime", y="TotalAllowedFlows", col="FlowDirection", kind="line", hue="L7Protocol", data=az_net_comms_df).set_xticklabels(rotation=50) nbdisp.display_timeline(data=az_net_comms_df.query('AllowedOutFlows > 0'), overlay_data=az_net_comms_df.query('AllowedInFlows > 0'), alert=security_alert, title='Network Flows (out=blue, in=green)', time_column='FlowStartTime', source_columns=['FlowType', 'AllExtIPs', 'L7Protocol', 'FlowDirection'], height=300) display(Markdown('### GeoLocation Mapping for external IPs')) ip_locs_in = set() ip_locs_out = set() for _, row in az_net_comms_df.iterrows(): ip = row.AllExtIPs if ip in ip_locs_in or ip in ip_locs_out or not ip: continue ip_entity = mas.IpAddress(Address=ip) iplocation.lookup_ip(ip_entity=ip_entity) if not ip_entity.Location: continue ip_entity.AdditionalData['protocol'] = row.L7Protocol if row.FlowDirection == 'I': ip_locs_in.add(ip_entity) else: ip_locs_out.add(ip_entity) flow_map = create_ip_map() display(HTML('<h3>External IP Addresses communicating with host</h3>')) display(HTML('Numbered circles indicate multiple items - click to expand')) display(HTML('Location markers: Blue = outbound, Purple = inbound, Green = Host')) icon_props = {'color': 'green'} flow_map = add_ip_cluster(folium_map=flow_map, ip_entities=inv_host_entity.public_ips, **icon_props) icon_props = {'color': 'blue'} flow_map = add_ip_cluster(folium_map=flow_map, ip_entities=ip_locs_out, **icon_props) icon_props = {'color': 'purple'} flow_map = add_ip_cluster(folium_map=flow_map, ip_entities=ip_locs_in, **icon_props) display(flow_map) display(Markdown('<p style="color:red">Warning: the folium mapping library ' 'does not display correctly in some browsers.</p><br>' 'If you see a blank image please retry with a different browser.')) # - # ### Observations # - We can the relatively rare ssh inbound traffic and view the connections on a timeline. # - We can also see the originating location of the source IP Address (in purple). # <a id='other_hosts_to_ips'></a>[Contents](#toc) # ## Have any other hosts been communicating with this address(es)? # + from datetime import timedelta alert_ips = {'\'{}\''.format(i.Address) for i in alert_ip_entities} alert_host_ip_list = ','.join(alert_ips) az_ip_where = f'| where AllExtIPs in ({alert_host_ip_list})' az_net_query_by_pub_ip = az_net_analytics_query.format(where_clause=az_ip_where, start = security_alert.StartTimeUtc - timedelta(3), end = security_alert.StartTimeUtc + timedelta(1)) print('getting data...') # %kql -query az_net_query_by_pub_ip az_net_ext_comms_df = _kql_raw_result_.to_dataframe() #az_net_ext_comms_df[net_default_cols] # az_net_ext_comms_df.groupby(['VMName', 'L7Protocol'])['AllowedOutFlows','AllowedInFlows','DeniedInFlows','DeniedOutFlows'].sum() inv_host_ips = [ent.Address for ent in inv_host_entity.private_ips] inv_host_ips += [ent.Address for ent in inv_host_entity.public_ips] alert_ips = [ip.Address for ip in alert_ip_entities] known_ips = inv_host_ips + alert_ips # Ips can be in one of 4 columns! def find_new_ips(known_ips, row): new_ips = set() if row.VMIPAddress and row.VMIPAddress not in known_ips: new_ips.add(row.VMIPAddress) if row.SrcIP and row.SrcIP not in known_ips: new_ips.add(row.SrcIP) if row.DestIP and row.DestIP not in known_ips: new_ips.add(row.DestIP) if row.PublicIPs: for pub_ip in row.PublicIPs: if pub_ip not in known_ips: new_ips.add(pub_ip) if new_ips: return list(new_ips) new_ips_all = az_net_ext_comms_df.apply(lambda x: find_new_ips(known_ips, x), axis=1).dropna() new_ips = set() for ip in [ip for item in new_ips_all for ip in item]: new_ips.add(ip) display(Markdown(f'#### {len(new_ips)} unseen IP Address found in this data: {list(new_ips)}')) vm_ip = new_ips.pop() aznet_query = ''' AzureNetworkAnalytics_CL | where PrivateIPAddresses_s has \'{vm_ip}\' | where ResourceType == 'NetworkInterface' | top 1 by TimeGenerated desc | project PrivateIPAddresses = PrivateIPAddresses_s, PublicIPAddresses = PublicIPAddresses_s, VirtualMachine = VirtualMachine_s | extend Host = split(VirtualMachine, '/')[-1] '''.format(vm_ip=vm_ip) # %kql -query aznet_query az_net_df = _kql_raw_result_.to_dataframe() if len(az_net_df) > 0: host_name = az_net_df['Host'].at[0] oms_heartbeat_query = ''' Heartbeat | where ComputerIP == \'{vm_ip}\' | top 1 by TimeGenerated desc nulls last | project Computer, ComputerIP, OSType, OSMajorVersion, OSMinorVersion, ResourceId, RemoteIPCountry, RemoteIPLatitude, RemoteIPLongitude, SourceComputerId '''.format(vm_ip=vm_ip) # %kql -query oms_heartbeat_query oms_heartbeat_df = _kql_raw_result_.to_dataframe() if len(oms_heartbeat_df) > 0: host_name = oms_heartbeat_df['Computer'].at[0] # Get the host entity and add this IP and system info to the try: if not victim_host_entity: victim_host_entity = mas.Host() victim_host_entity.HostName = host_name except NameError: victim_host_entity = mas.Host() victim_host_entity.HostName = host_name def convert_to_ip_entities(ip_str): ip_entities = [] if ip_str: if ',' in ip_str: addrs = ip_str.split(',') elif ' ' in ip_str: addrs = ip_str.split(' ') else: addrs = [ip_str] for addr in addrs: ip_entity = mas.IpAddress() ip_entity.Address = addr.strip() iplocation.lookup_ip(ip_entity=ip_entity) ip_entities.append(ip_entity) return ip_entities # Add this information to our inv_host_entity retrieved_pub_addresses = [] if len(az_net_df) == 1: priv_addr_str = az_net_df['PrivateIPAddresses'].loc[0] victim_host_entity.properties['private_ips'] = convert_to_ip_entities(priv_addr_str) pub_addr_str = az_net_df['PublicIPAddresses'].loc[0] victim_host_entity.properties['public_ips'] = convert_to_ip_entities(pub_addr_str) retrieved_pub_addresses = [ip.Address for ip in victim_host_entity.properties['public_ips']] if len(oms_heartbeat_df) == 1: if oms_heartbeat_df['ComputerIP'].loc[0]: oms_address = oms_heartbeat_df['ComputerIP'].loc[0] if oms_address not in retrieved_address: ip_entity = mas.IpAddress() ip_entity.Address = oms_address iplocation.lookup_ip(ip_entity=ip_entity) inv_host_entity.properties['public_ips'].append(ip_entity) victim_host_entity.OSFamily = oms_heartbeat_df['OSType'].loc[0] victim_host_entity.AdditionalData['OSMajorVersion'] = oms_heartbeat_df['OSMajorVersion'].loc[0] victim_host_entity.AdditionalData['OSMinorVersion'] = oms_heartbeat_df['OSMinorVersion'].loc[0] victim_host_entity.AdditionalData['SourceComputerId'] = oms_heartbeat_df['SourceComputerId'].loc[0] print(f'Found New Host Entity {victim_host_entity.HostName}\n') print(victim_host_entity) add_observation(Observation(caption=f'Second victim host identified {victim_host_entity.HostName}', description='Description of host entity shown in attachment.', item=victim_host_entity, link='other_hosts_to_ips')) sns.set() from matplotlib import MatplotlibDeprecationWarning warnings.simplefilter("ignore", category=MatplotlibDeprecationWarning) ip_graph = nx.DiGraph(id='IPGraph') def add_vm_node(graph, host_entity): vm_name = host_entity.HostName vm_ip = host_entity.private_ips[0].Address vm_desc = f'{host_entity.HostName}' ip_graph.add_node(vm_ip, name=vm_name, description=vm_desc, node_type='host') for ip_entity in alert_ip_entities: if 'Location' in ip_entity: ip_desc = f'{ip_entity.Address}\n{ip_entity.Location.City}, {ip_entity.Location.CountryName}' else: ip_desc = 'unknown location' ip_graph.add_node(ip_entity.Address, name=ip_entity.Address, description=ip_desc, node_type='ip') add_vm_node(ip_graph, inv_host_entity) add_vm_node(ip_graph, victim_host_entity) def add_edges(graph, row): dest_ip = row.DestIP if row.DestIP else row.VMIPAddress if row.SrcIP: src_ip = row.SrcIP ip_graph.add_edge(src_ip, dest_ip) else: for ip in row.PublicIPs: src_ip = ip ip_graph.add_edge(src_ip, dest_ip) # Add edges from network data az_net_ext_comms_df.apply(lambda x: add_edges(ip_graph, x),axis=1) src_node = [n for (n, node_type) in nx.get_node_attributes(ip_graph, 'node_type').items() if node_type == 'ip'] vm_nodes = [n for (n, node_type) in nx.get_node_attributes(ip_graph, 'node_type').items() if node_type == 'host'] # now draw them in subsets using the `nodelist` arg plt.rcParams['figure.figsize'] = (10, 10) plt.margins(x=0.3, y=0.3) plt.title('Comms between hosts and suspect IPs') pos = nx.circular_layout(ip_graph) nx.draw_networkx_nodes(ip_graph, pos, nodelist=src_node, node_color='red', alpha=0.5, node_shape='o') nx.draw_networkx_nodes(ip_graph, pos, nodelist=vm_nodes, node_color='green', alpha=0.5, node_shape='s', s=400) nlabels = nx.get_node_attributes(ip_graph, 'description') nx.relabel_nodes(ip_graph, nlabels) nx.draw_networkx_labels(ip_graph, pos, nlabels, font_size=15) nx.draw_networkx_edges(ip_graph, pos, alpha=0.5, arrows=True, arrowsize=20); # - # ### Observations # - We have found a new IP address that our attacker has also been communicating with. We should investigate that machine. # - From the name looks like a Windows host # - There is also another public IP involved that has been taking to both hosts. We should look at that. # <a id='other_host_investigate'></a>[Contents](#toc) # # Other Hosts Communicating with IP # Investigating the second host in the attack graph. # <a id='host_logons'></a>[Contents](#toc) # ## Check Host Logons # + hidden=true from msticpy.nbtools.query_defns import DataFamily, DataEnvironment params_dict = {} params_dict.update(security_alert.query_params) params_dict['host_filter_eq'] = f'Computer has \'{victim_host_entity.HostName}\'' params_dict['host_filter_neq'] = f'Computer !has \'{victim_host_entity.HostName}\'' params_dict['host_name'] = victim_host_entity.HostName params_dict['start'] = security_alert.origin_time - timedelta(days=5) params_dict['end'] = security_alert.origin_time + timedelta(days=1) if victim_host_entity.OSFamily == 'Linux': params_dict['data_family'] = DataFamily.LinuxSecurity params_dict['path_separator'] = '/' else: params_dict['data_family'] = DataFamily.WindowsSecurity params_dict['path_separator'] = '\\' # # set the origin time to the time of our alert # logon_query_times = mas.QueryTime(units='day', origin_time=security_alert.origin_time, # before=5, after=1, max_before=20, max_after=20) # logon_query_times.display() from msticpy.sectools.eventcluster import dbcluster_events, add_process_features, _string_score print('getting data...') host_logons = qry.list_host_logons(**params_dict) if len(host_logons) > 0: logon_features = host_logons.copy() logon_features['AccountNum'] = host_logons.apply(lambda x: _string_score(x.Account), axis=1) logon_features['LogonIdNum'] = host_logons.apply(lambda x: _string_score(x.TargetLogonId), axis=1) logon_features['LogonHour'] = host_logons.apply(lambda x: x.TimeGenerated.hour, axis=1) # you might need to play around with the max_cluster_distance parameter. # decreasing this gives more clusters. (clus_logons, _, _) = dbcluster_events(data=logon_features, time_column='TimeGenerated', cluster_columns=['AccountNum', 'LogonType'], max_cluster_distance=0.0001) # %matplotlib inline # plt.rcParams['figure.figsize'] = (12, 4) # clus_logons.plot.barh(x="Account", y="ClusterSize") # display(Markdown(f'Number of input events: {len(host_logons)}')) # display(Markdown(f'Number of clustered events: {len(clus_logons)}')) # display(Markdown('#### Distinct host logon patterns')) # clus_logons.sort_values('TimeGenerated') # nbdisp.display_logon_data(clus_logons) # else: # display(Markdown('No logon events found for host.')) display(Markdown('### Classification of Logon Types by Account')) display(Markdown('### Counts of logon events by logon type.')) display(Markdown('Min counts for each logon type highlighted.')) logon_by_type = (host_logons[['Account', 'LogonType', 'EventID']] .groupby(['Account','LogonType']).count().unstack() .fillna(0) .style .background_gradient(cmap='viridis', low=.5, high=0) .format("{0:0>3.0f}")) display(logon_by_type) key = 'logon type key = {}'.format('; '.join([f'{k}:{v}' for k,v in mas.nbdisplay._WIN_LOGON_TYPE_MAP.items()])) display(Markdown(key)) display(Markdown('### Logon Timeline')) nbdisp.display_timeline(data=host_logons, overlay_data=host_logons.query('LogonType == 10'), alert=security_alert, source_columns=['Account', 'LogonType', 'TimeGenerated'], title='All Host Logons (RDP Logons in green)') add_observation(Observation(caption='RDP Logons seen for victim #2', description='Logons by logon type.', item=logon_by_type, link='victim2_logon_types')) display(Markdown('### Failed Logons')) failedLogons = qry.list_host_logon_failures(**params_dict) if failedLogons.shape[0] == 0: display(print('No logon failures recorded for this host between {security_alert.start} and {security_alert.start}')) else: display(failedLogons) add_observation(Observation(caption='Logon failures seen for victim #2', description=f'{len(failedLogons)} Logons seen.', item=failedLogons, link='failed_logons')) # - # ### Observations # - We see some Network and RemoteInteractive logons - some occuring around the time leading up to the original alert. # - From the failed logons it looks like a few attempts were made to logon to the account name "ian". # - Once the logon succeeded our attacker logged in using remote desktop. # <a id='examine_win_logon_sess'></a>[Contents](#toc) # ## Examine a Logon Session # ### Select a Logon ID To Examine # + import re dist_logons = clus_logons.sort_values('TimeGenerated')[['TargetUserName', 'TimeGenerated', 'LastEventTime', 'LogonType', 'ClusterSize']] items = dist_logons.apply(lambda x: (f'{x.TargetUserName}: ' f'(logontype={x.LogonType}) ' f'timerange={x.TimeGenerated} - {x.LastEventTime} ' f'count={x.ClusterSize}'), axis=1).values.tolist() def get_selected_logon_cluster(selected_item): acct_match = re.search(r'(?P<acct>[^:]+):\s+\(logontype=(?P<l_type>[^)]+)', selected_item) if acct_match: acct = acct_match['acct'] l_type = int(acct_match['l_type']) return host_logons.query('TargetUserName == @acct and LogonType == @l_type') def get_selected_logon(selected_item): logon_list_regex = r''' (?P<acct>[^:]+):\s+ \(logontype=(?P<logon_type>[^)]+)\)\s+ \(timestamp=(?P<time>[^)]+)\)\s+ logonid=(?P<logonid>[0-9a-fx)]+) ''' acct_match = re.search(logon_list_regex, selected_item, re.VERBOSE) if acct_match: acct = acct_match['acct'] logon_type = int(acct_match['logon_type']) time_stamp = pd.to_datetime(acct_match['time']) logon_id = acct_match['logonid'] return host_logons.query('TargetUserName == @acct and LogonType == @logon_type' ' and TargetLogonId == @logon_id') logon_wgt = mas.SelectString(description='Select logon cluster to examine', item_list=items, height='200px', width='100%', auto_display=True) # - # ### Observations # - Select the logon account and type that we're interested in # <a id='process_clustering'></a>[Contents](#toc) # ## Unusual Processes on Host - Clustering # Sometimes you don't have a source process to work with. Other times it's just useful to see what else is going on on the host. This section retrieves all processes on the host within the time bounds # set in the query times widget. # # You can display the raw output of this by looking at the *processes_on_host* dataframe. Just copy this into a new cell and hit Ctrl-Enter. # # Usually though, the results return a lot of very repetitive and unintersting system processes so we attempt to cluster these to make the view easier to negotiate. # To do this we process the raw event list output to extract a few features that render strings (such as commandline)into numerical values. The default below uses the following features: # - commandLineTokensFull - this is a count of common delimiters in the commandline # (given by this regex r'[\s\-\\/\.,"\'|&:;%$()]'). The aim of this is to capture the commandline structure while ignoring variations on what is essentially the same pattern (e.g. temporary path GUIDs, target IP or host names, etc.) # - pathScore - this sums the ordinal (character) value of each character in the path (so /bin/bash and /bin/bosh would have similar scores). # - isSystemSession - 1 if this is a root/system session, 0 if anything else. # # Then we run a clustering algorithm (DBScan in this case) on the process list. The result groups similar (noisy) processes together and leaves unique process patterns as single-member clusters. # + selected_logon_cluster = get_selected_logon_cluster(logon_wgt.value) # Calculate time range based on the logons from previous section logon_time = selected_logon_cluster['TimeGenerated'].min() last_logon_time = selected_logon_cluster['TimeGenerated'].max() time_diff_delta = (last_logon_time - logon_time) # set the origin time to the time of our alert params_dict['start'] = logon_time - timedelta(seconds=(1 * 60 * 60)) params_dict['end'] = logon_time + time_diff_delta + timedelta(seconds=(2 * 60 * 60)) from msticpy.sectools.eventcluster import dbcluster_events, add_process_features print('Getting process events...', end='') processes_on_host = qry.list_processes(**params_dict) print('done') print('Clustering...', end='') feature_procs = add_process_features(input_frame=processes_on_host, path_separator=params_dict['path_separator']) feature_procs['accountNum'] = feature_procs.apply(lambda x: _string_score(x.Account), axis=1) # you might need to play around with the max_cluster_distance parameter. # decreasing this gives more clusters. (clus_events, dbcluster, x_data) = dbcluster_events(data=feature_procs, cluster_columns=['commandlineTokensFull', 'pathScore', 'accountNum', 'isSystemSession'], max_cluster_distance=0.0001) print('done') print('Number of input events:', len(feature_procs)) print('Number of clustered events:', len(clus_events)) (clus_events.sort_values('TimeGenerated')[['TimeGenerated', 'LastEventTime', 'NewProcessName', 'CommandLine', 'ClusterSize', 'commandlineTokensFull', 'pathScore', 'isSystemSession']] .sort_values('ClusterSize', ascending=False)) print('done') display(Markdown('### View processes used in login session')) selected_logon_cluster = get_selected_logon_cluster(logon_wgt.value) def view_logon_sess(x=''): global selected_logon selected_logon = get_selected_logon(x) display(selected_logon) logonId = selected_logon['TargetLogonId'].iloc[0] sess_procs = (processes_on_host.query('TargetLogonId == @logonId | SubjectLogonId == @logonId') [['NewProcessName', 'CommandLine', 'TargetLogonId']] .drop_duplicates()) display(sess_procs) items = selected_logon_cluster.sort_values('TimeGenerated').apply(lambda x: (f'{x.TargetUserName}: ' f'(logontype={x.LogonType}) ' f'(timestamp={x.TimeGenerated}) ' f'logonid={x.TargetLogonId}'), axis=1).values.tolist() sess_w = widgets.Select(options=items, description='Select logon instance to examine', **WIDGET_DEFAULTS) interactive(view_logon_sess, x=sess_w) # - # ### Observations # - First session listed doesn't look interesting # - but the second shows: # - Accounts being added # - Accounts added to local Administrators group # - Permissions removed on RPD/Terminal services logon # - Scheduled task being installed as a means of persistence # + display(Markdown('### EventTypes login session in select time interval')) all_events_base_qry = ''' SecurityEvent | where Computer =~ '{host}' | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | where {where_filter} ''' all_events_qry = all_events_base_qry.format(host=params_dict['host_name'], start=params_dict['start'], end=params_dict['end'], where_filter='EventID != 4688 and EventID != 4624') # %kql -query all_events_qry all_events_df = _kql_raw_result_.to_dataframe() display(all_events_df[['Account', 'Activity', 'TimeGenerated']] .groupby(['Account', 'Activity']).count()) add_observation(Observation(caption='System account modifications during attack.', description='Count of event types seen on system', item=all_events_df[['Account', 'Activity', 'TimeGenerated']].groupby(['Account', 'Activity']).count(), link='other_win_events')) # - # ### Observations # Some unusual events associated with our compromised account session: # - Logon failure # - Account creation # - Password reset # - Security group changes # <a id='o365'></a>[Contents](#toc) # # Office 365 Activity # ### Check our Office Subscription for anything suspicious # + o365_start = security_alert.origin_time - timedelta(seconds=(60 * 60)) o365_end = security_alert.origin_time + timedelta(seconds=(10 * 60 * 60)) print('Running queries...', end=' ') # Queries ad_changes_query = ''' OfficeActivity | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | where RecordType == 'AzureActiveDirectory' | where Operation in ('Add service principal.', 'Change user password.', 'Add user.', 'Add member to role.') | where UserType == 'Regular' | project OfficeId, TimeGenerated, Operation, OrganizationId, OfficeWorkload, ResultStatus, OfficeObjectId, UserId = tolower(UserId), ClientIP, ExtendedProperties '''.format(start = o365_start, end=o365_end) # %kql -query ad_changes_query ad_changes_df = _kql_raw_result_.to_dataframe() office_ops_query = ''' OfficeActivity | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | where RecordType in ("AzureActiveDirectoryAccountLogon", "AzureActiveDirectoryStsLogon") | extend UserAgent = extractjson("$[0].Value", ExtendedProperties, typeof(string)) | union ( OfficeActivity | where TimeGenerated >= datetime({start}) | where TimeGenerated <= datetime({end}) | where RecordType !in ("AzureActiveDirectoryAccountLogon", "AzureActiveDirectoryStsLogon") ) | where UserType == 'Regular' '''.format(start = o365_start, end=o365_end) # %kql -query office_ops_query office_ops_df = _kql_raw_result_.to_dataframe() office_ops_summary_query = ''' let timeRange=ago(30d); let officeAuthentications = OfficeActivity | where TimeGenerated >= timeRange | where RecordType in ("AzureActiveDirectoryAccountLogon", "AzureActiveDirectoryStsLogon") | extend UserAgent = extractjson("$[0].Value", ExtendedProperties, typeof(string)) | where Operation == "UserLoggedIn"; officeAuthentications | union ( OfficeActivity | where TimeGenerated >= timeRange | where RecordType !in ("AzureActiveDirectoryAccountLogon", "AzureActiveDirectoryStsLogon") ) | where UserType == 'Regular' | extend RecordOp = strcat(RecordType, '-', Operation) | summarize OpCount=count() by RecordType, Operation, UserId, UserAgent, ClientIP, bin(TimeGenerated, 1h) // render timeline '''.format(start = o365_start, end=o365_end) # %kql -query office_ops_summary_query office_ops_summary_df = _kql_raw_result_.to_dataframe() # # %kql -query office_ops_query # office_ops_df = _kql_raw_result_.to_dataframe() # office_logons_query = ''' # let timeRange=ago(30d); # let officeAuthentications = OfficeActivity # | where TimeGenerated >= timeRange # | where RecordType in ("AzureActiveDirectoryAccountLogon", "AzureActiveDirectoryStsLogon") # | extend UserAgent = extractjson("$[0].Value", ExtendedProperties, typeof(string)) # | where Operation == "UserLoggedIn"; # let lookupWindow = 1d; # let lookupBin = lookupWindow / 2.0; # officeAuthentications | project-rename Start=TimeGenerated # | extend TimeKey = bin(Start, lookupBin) # | join kind = inner ( # officeAuthentications # | project-rename End=TimeGenerated # | extend TimeKey = range(bin(End - lookupWindow, lookupBin), bin(End, lookupBin), lookupBin) # | mvexpand TimeKey to typeof(datetime) # ) on UserAgent, TimeKey # | project timeSpan = End - Start, UserId, ClientIP , UserAgent , Start, End # | summarize dcount(ClientIP) by UserAgent # | where dcount_ClientIP > 1 # | join kind=inner ( # officeAuthentications # | summarize minTime=min(TimeGenerated), maxTime=max(TimeGenerated) by UserId, UserAgent, ClientIP # ) on UserAgent # ''' # # %kql -query office_logons_query # office_logons_df = _kql_raw_result_.to_dataframe() print('done.') # Any IP Addresses in our alert IPs that match? display(Markdown('### Any IP Addresses in our alert IPs that match Office Activity?')) for ip in alert_ip_entities: susp_o365_activities = office_ops_df[office_ops_df['ClientIP'] == ip.Address] susp_o365_summ = (office_ops_df[office_ops_df['ClientIP'] == ip.Address] [['OfficeId', 'UserId', 'RecordType', 'Operation']] .groupby(['UserId', 'RecordType', 'Operation']).count() .rename(columns={'OfficeId': 'OperationCount'})) display(Markdown(f'### Activity for {ip.Address}')) if len(susp_o365_summ) > 0: display(susp_o365_summ) add_observation(Observation(caption=f'O365 activity from suspected attacker IP {ip.Address}', description=f'Summarized operation count for each user/service/operation type', item=susp_o365_summ, link='o365_match_ip')) else: display(Markdown('No activity detected')) for susp_ip in [ip.Address for ip in alert_ip_entities]: suspect_ip_ops = office_ops_df[office_ops_df['ClientIP'] == susp_ip] display(Markdown(f'### Timeline of operations originating from suspect IP Address: {susp_ip}')) display(Markdown(f'**{susp_ip}**')) if len(suspect_ip_ops) == 0: display(Markdown('No activity detected')) continue sel_op_type='FileDownloaded' nbdisp.display_timeline(data=suspect_ip_ops, title=f'Operations from {susp_ip} (all=blue, {sel_op_type}=green)', overlay_data=suspect_ip_ops.query('Operation == @sel_op_type'), height=200, source_columns=['UserId', 'RecordType', 'Operation']) # Uncomment line below to see all activity # display(suspect_ip_ops.sort_values('TimeGenerated', ascending=True).head()) display(Markdown('### Evidence of automated or bulk uploads/downloads')) timed_slice_ops = office_ops_df[['RecordType', 'TimeGenerated', 'Operation', 'OrganizationId', 'UserType', 'OfficeWorkload', 'ResultStatus', 'OfficeObjectId', 'UserId', 'ClientIP', 'Start_Time']] timed_slice_ops2 = timed_slice_ops.set_index('TimeGenerated') hi_freq_ops = (timed_slice_ops2[['UserId', 'ClientIP', 'Operation', 'RecordType']] .groupby(['UserId', 'ClientIP', 'RecordType', 'Operation']).resample('10S').count() .query('RecordType > 10') .drop(['ClientIP', 'UserId', 'RecordType'], axis=1) .assign(OpsPerSec = lambda x: x.Operation / 10) .rename(columns={'Operation': 'Operation Count'})) if len(hi_freq_ops) > 0: display(hi_freq_ops) add_observation(Observation(caption=f'O365 bulk/high freq operations seen', description=f'Summarized operation count bulk actions', item=hi_freq_ops, link='o356_high_freq')) # - # ### Observations # - Logon failures and success originating from our attacker IP Address # - File download activity # - We also confirm what looks like data exfiltration with another check that looks for high frequency operations for a given user/IP # + [markdown] hidden=true # <a id='appendices'></a>[Contents](#toc) # # Appendices # - # ## Available DataFrames print('List of current DataFrames in Notebook') print('-' * 50) current_vars = list(locals().keys()) for var_name in current_vars: if isinstance(locals()[var_name], pd.DataFrame) and not var_name.startswith('_'): print(var_name) # + [markdown] heading_collapsed=true tags=["todo"] # ## Saving Data to Excel # To save the contents of a pandas DataFrame to an Excel spreadsheet # use the following syntax # ``` # writer = pd.ExcelWriter('myWorksheet.xlsx') # my_data_frame.to_excel(writer,'Sheet1') # writer.save() # ```
Notebooks/Guided Hunting - Linux-Windows-Office.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [anaconda] # language: python # name: Python [anaconda] # --- ''' Standard things to import... ''' # %matplotlib inline import numpy as np import matplotlib.pyplot as plt from astropy.io import fits # + ''' Lets import some other new things! ''' import matplotlib # going to use this to change some settings (next cell) from matplotlib.colors import LogNorm # this lets us scale color outputs using Log instead of Linear import matplotlib.cm as cm # this gives access to the standard colormaps (besides rainbow) # - ''' this is how you can change the default properties of plot text Search Goolge for more examples of changing rcParams to get other fonts, styles, etc ''' matplotlib.rcParams.update({'font.size':11}) matplotlib.rcParams.update({'font.family':'serif'}) # + # remember how to open FITS tables from last week (or go back and review) dfile = 'data.fit' # our data comes from the HIPPARCOS mission: http://adsabs.harvard.edu/abs/1997ESASP1200.....E # I used Vizier to make a smaller version of the table for ease of reading hdulist2 = fits.open(dfile) hdulist2.info() # print the extensions # - tbl = hdulist2[1].data # get the data from the 2nd extension hdulist2.close() # close the file tbl.columns # print the columns available (can be called by name!) # you can make plots by calling columns by name! plt.plot(tbl['col1'], tbl['col2'], alpha=0.2) # You'll need to compute the absolute magnitude of the stars. Recall the formula: # # $M_v = -5 \log_{10}(1/\pi) + 5 + m_V$ # # Where $\pi$ is the parallax in arcseconds, $m_V$ is the apparent magnitude in the V-band # + ''' Find stars with "good" data I required errors for B-V greater than 0 and less than or equal to 0.05mag I required errors on parallax to be greater than 0 and less than or equal to 5 Finally, I required the absolute magnitudes to be real numbers (no Nulls, NaN's, Infs, etc) ''' # here is most of what you need. Finish it! ok = np.where((tbl['e_B-V'] <= 0.05) & (tbl['e_Plx'] > 0) & np.isfinite(Mv)) # + plt.figure( figsize=(7,5) ) # here's a freebie: I used a 10x8 figsize plt.hist2d(x, y, bins=(10,20), # set the number of bins in the X and Y direction. You'll have to guess what I used norm=LogNorm(), # scale the colors using log, not linear (default) cmap = cm.Spectral) # change the colormap # the B-V color of the Sun is 0.635 mag # use plt.annotate to put words on the plot, set their colors, fontsizes, and rotation plt.ylabel('$m_{V}$') # you can put (some) LaTeX math in matplotlib titles/labels cb = plt.colorbar() # make a colorbar magically appear # more freebies: this is the exact resolution and padding I used to make the figure file plt.savefig('FILENAME.png', dpi=300, # set the resolution bbox_inches='tight', # make the figure fill the window size pad_inches=0.5) # give a buffer so text doesnt spill off side of plot # -
lab5/example_plots.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 os import path import numpy as np name_basics_path='../../data/imbd_data/name_basics.tsv' name_basics_processed_path='../../data/imbd_data/name_basics_processed.csv' # Reading TSV files # TSV files are csv files with "\t" as the delimeter df = pd.read_csv(name_basics_path,delimiter="\t") print(df.head(1)) def write_to_csv(df,filepath): ''' input: df - a pandas DataFrame filepath - an output filepath as a string writes to a csv file in same diretory as this script returns: nothing ''' # if no csv exists if not path.exists(filepath): df.to_csv(filepath,index=False) else: df.to_csv(filepath, mode='a', header=False,index=False) print(df.head(1)) print(len(df)) print(df.primaryProfession.unique()) # make na string to na df = df.replace('\\N', np.nan) # only include rows with valid birthYear df = df[df['birthYear'].notna()] df = df[['nconst', 'primaryName', 'birthYear', 'deathYear']] write_to_csv(df,name_basics_processed_path) print(df.columns)
code/clean_imbd_data_scripts/clean_name_basics.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 # --- # # Exploitation vs Exploration # + # %matplotlib inline import numpy as np import matplotlib.pyplot as plt from bayes_opt import BayesianOptimization # use sklearn's default parameters for theta and random_start gp_params = {"corr": "cubic", "theta0": 0.1, "thetaL": None, "thetaU": None, "random_start": 1} # - # # Target function # + np.random.seed(42) xs = np.linspace(-2, 10, 10000) f = np.exp(-(xs - 2)**2) + np.exp(-(xs - 6)**2/10) + 1/ (xs**2 + 1) plt.plot(f) plt.show() # - # # Utility function for plotting def plot_bo(f, bo): xs = [x["x"] for x in bo.res["all"]["params"]] ys = bo.res["all"]["values"] mean, var = bo.gp.predict(np.arange(len(f)).reshape(-1, 1), eval_MSE=True) plt.figure(figsize=(16, 9)) plt.plot(f) plt.plot(np.arange(len(f)), mean) plt.fill_between(np.arange(len(f)), mean+var, mean-var, alpha=0.1) plt.scatter(bo.X.flatten(), bo.Y, c="red", s=50, zorder=10) plt.xlim(0, len(f)) plt.ylim(f.min()-0.1*(f.max()-f.min()), f.max()+0.1*(f.max()-f.min())) plt.show() # # Acquisition Function "Expected Improvement" # ## Prefer exploitation (xi=0.0) # # Note that most points are around the peak(s). # + bo = BayesianOptimization(f=lambda x: f[int(x)], pbounds={"x": (0, len(f)-1)}, verbose=0) bo.maximize(init_points=2, n_iter=25, acq="ei", xi=0.0, **gp_params) plot_bo(f, bo) # - # ## Prefer exploration (xi=0.1) # # Note that the points are more spread out across the whole range. # + bo = BayesianOptimization(f=lambda x: f[int(x)], pbounds={"x": (0, len(f)-1)}, verbose=0) bo.maximize(init_points=2, n_iter=25, acq="ei", xi=0.1, **gp_params) plot_bo(f, bo) # - # # Acquisition Function "Probability of Improvement" # ## Prefer exploitation (xi=0.0) # # Note that most points are around the peak(s). # + bo = BayesianOptimization(f=lambda x: f[int(x)], pbounds={"x": (0, len(f)-1)}, verbose=0) bo.maximize(init_points=2, n_iter=25, acq="poi", xi=0.0, **gp_params) plot_bo(f, bo) # - # ## Prefer exploration (xi=0.1) # # Note that the points are more spread out across the whole range. # + bo = BayesianOptimization(f=lambda x: f[int(x)], pbounds={"x": (0, len(f)-1)}, verbose=0) bo.maximize(init_points=2, n_iter=25, acq="poi", xi=0.1, **gp_params) plot_bo(f, bo) # -
examples/exploitation vs 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 # name: python3 # --- # + id="wDlWLbfkJtvu" cellView="form" #@title Copyright 2020 Google LLC. Double-click here for license information. # 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="TL5y5fY9Jy_x" # # Simple Linear Regression with Synthetic Data # # In this first Colab, you'll explore linear regression with a simple database. # + [markdown] id="DZz29MwGgE2Y" # ## Learning objectives: # # After doing this exercise, you'll know how to do the following: # # * Run Colabs. # * Tune the following [hyperparameters](https://developers.google.com/machine-learning/glossary/#hyperparameter): # * [learning rate](https://developers.google.com/machine-learning/glossary/#learning_rate) # * number of [epochs](https://developers.google.com/machine-learning/glossary/#epoch) # * [batch size](https://developers.google.com/machine-learning/glossary/#batch_size) # * Interpret different kinds of [loss curves](https://developers.google.com/machine-learning/glossary/#loss_curve). # + [markdown] id="wm3K3dHlf_1n" # ## About Colabs # # Machine Learning Crash Course uses Colaboratories (**Colabs**) for all programming exercises. Colab is Google's implementation of [Jupyter Notebook](https://jupyter.org/). Like all Jupyter Notebooks, a Colab consists of two kinds of components: # # * **Text cells**, which contain explanations. You are currently reading a text cell. # * **Code cells**, which contain Python code for you to run. Code cells have a light gray background. # # You *read* the text cells and *run* the code cells. # + [markdown] id="qc3e5Jbbf5aA" # ### Running code cells # # You must run code cells in order. In other words, you may only run a code cell once all the code cells preceding it have already been run. # # To run a code cell: # # 1. Place the cursor anywhere inside the [ ] area at the top left of a code cell. The area inside the [ ] will display an arrow. # 2. Click the arrow. # # Alternatively, you may invoke **Runtime->Run all**. Note, though, that some of the code cells will fail because not all the coding is complete. (You'll complete the coding as part of the exercise.) # + [markdown] id="Sa35idJHf0__" # ### Understanding hidden code cells # # We've **hidden** the code in code cells that don't advance the learning objectives. For example, we've hidden the code that plots graphs. However, **you must still run code cells containing hidden code**. You'll know that the code is hidden because you'll see a title (for example, "Load the functions that build and train a model") without seeing the code. # # To view the hidden code, just double click the header. # + [markdown] id="8H508dWUfvY1" # ### Why did you see an error? # # If a code cell returns an error when you run it, consider two common problems: # # * You didn't run *all* of the code cells preceding the current code cell. # * If the code cell is labeled as a **Task**, then you haven't written the necessary code. # + [markdown] id="bMr7MPVmoiHf" # ## Use the right version of TensorFlow # # The following hidden code cell ensures that the Colab will run on TensorFlow 2.X, which is the most recent version of TensorFlow: # + id="Z1pOWL7eevO8" #@title Run this Colab on TensorFlow 2.x # %tensorflow_version 2.x # + [markdown] id="xchnxAsaKKqO" # ## Import relevant modules # # The following cell imports the packages that the program requires: # + id="9n9_cTveKmse" import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt # + [markdown] id="SIpsyJITPcbG" # ## Define functions that build and train a model # # The following code defines two functions: # # * `build_model(my_learning_rate)`, which builds an empty model. # * `train_model(model, feature, label, epochs)`, which trains the model from the examples (feature and label) you pass. # # Since you don't need to understand model building code right now, we've hidden this code cell. You may optionally double-click the headline to explore this code. # + id="xvO_beKVP1Ke" #@title Define the functions that build and train a model def build_model(my_learning_rate): """Create and compile a simple linear regression model.""" # Most simple tf.keras models are sequential. # A sequential model contains one or more layers. model = tf.keras.models.Sequential() # Describe the topography of the model. # The topography of a simple linear regression model # is a single node in a single layer. model.add(tf.keras.layers.Dense(units=1, input_shape=(1,))) # Compile the model topography into code that # TensorFlow can efficiently execute. Configure # training to minimize the model's mean squared error. model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate), loss="mean_squared_error", metrics=[tf.keras.metrics.RootMeanSquaredError()]) return model def train_model(model, feature, label, epochs, batch_size): """Train the model by feeding it data.""" # Feed the feature values and the label values to the # model. The model will train for the specified number # of epochs, gradually learning how the feature values # relate to the label values. history = model.fit(x=feature, y=label, batch_size=batch_size, epochs=epochs) # Gather the trained model's weight and bias. trained_weight = model.get_weights()[0] trained_bias = model.get_weights()[1] # The list of epochs is stored separately from the # rest of history. epochs = history.epoch # Gather the history (a snapshot) of each epoch. hist = pd.DataFrame(history.history) # Specifically gather the model's root mean #squared error at each epoch. rmse = hist["root_mean_squared_error"] return trained_weight, trained_bias, epochs, rmse print("Defined create_model and train_model") # + [markdown] id="Ak_TMAzGOIFq" # ## Define plotting functions # # We're using a popular Python library called [Matplotlib](https://developers.google.com/machine-learning/glossary/#matplotlib) to create the following two plots: # # * a plot of the feature values vs. the label values, and a line showing the output of the trained model. # * a [loss curve](https://developers.google.com/machine-learning/glossary/#loss_curve). # # We hid the following code cell because learning Matplotlib is not relevant to the learning objectives. Regardless, you must still run all hidden code cells. # + id="QF0BFRXTOeR3" #@title Define the plotting functions def plot_the_model(trained_weight, trained_bias, feature, label): """Plot the trained model against the training feature and label.""" # Label the axes. plt.xlabel("feature") plt.ylabel("label") # Plot the feature values vs. label values. plt.scatter(feature, label) # Create a red line representing the model. The red line starts # at coordinates (x0, y0) and ends at coordinates (x1, y1). x0 = 0 y0 = trained_bias x1 = my_feature[-1] y1 = trained_bias + (trained_weight * x1) plt.plot([x0, x1], [y0, y1], c='r') # Render the scatter plot and the red line. plt.show() def plot_the_loss_curve(epochs, rmse): """Plot the loss curve, which shows loss vs. epoch.""" plt.figure() plt.xlabel("Epoch") plt.ylabel("Root Mean Squared Error") plt.plot(epochs, rmse, label="Loss") plt.legend() plt.ylim([rmse.min()*0.97, rmse.max()]) plt.show() print("Defined the plot_the_model and plot_the_loss_curve functions.") # + [markdown] id="LVSDPusELEZ5" # ## Define the dataset # # The dataset consists of 12 [examples](https://developers.google.com/machine-learning/glossary/#example). Each example consists of one [feature](https://developers.google.com/machine-learning/glossary/#feature) and one [label](https://developers.google.com/machine-learning/glossary/#label). # # + id="rnUSYKw4LUuh" my_feature = ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) my_label = ([5.0, 8.8, 9.6, 14.2, 18.8, 19.5, 21.4, 26.8, 28.9, 32.0, 33.8, 38.2]) # + [markdown] id="K24afla-4s2x" # ## Specify the hyperparameters # # The hyperparameters in this Colab are as follows: # # * [learning rate](https://developers.google.com/machine-learning/glossary/#learning_rate) # * [epochs](https://developers.google.com/machine-learning/glossary/#epoch) # * [batch_size](https://developers.google.com/machine-learning/glossary/#batch_size) # # The following code cell initializes these hyperparameters and then invokes the functions that build and train the model. # + id="Ye730h13CQ97" learning_rate=0.01 epochs=10 my_batch_size=12 my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + [markdown] id="QwSm60H6pQjJ" # ## Task 1: Examine the graphs # # Examine the top graph. The blue dots identify the actual data; the red line identifies the output of the trained model. Ideally, the red line should align nicely with the blue dots. Does it? Probably not. # # A certain amount of randomness plays into training a model, so you'll get somewhat different results every time you train. That said, unless you are an extremely lucky person, the red line probably *doesn't* align nicely with the blue dots. # # Examine the bottom graph, which shows the loss curve. Notice that the loss curve decreases but doesn't flatten out, which is a sign that the model hasn't trained sufficiently. # + [markdown] id="lLXPvqCRvgI4" # ## Task 2: Increase the number of epochs # # Training loss should steadily decrease, steeply at first, and then more slowly. Eventually, training loss should eventually stay steady (zero slope or nearly zero slope), which indicates that training has [converged](http://developers.google.com/machine-learning/glossary/#convergence). # # In Task 1, the training loss did not converge. One possible solution is to train for more epochs. Your task is to increase the number of epochs sufficiently to get the model to converge. However, it is inefficient to train past convergence, so don't just set the number of epochs to an arbitrarily high value. # # Examine the loss curve. Does the model converge? # + id="uXuJH3h6t5qs" learning_rate=0.2 epochs= 30 # Replace ? with an integer. my_batch_size=12 my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + id="1tWrzP4Ww7sD" #@title Double-click to view a possible solution learning_rate=0.01 epochs=450 my_batch_size=12 my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # The loss curve suggests that the model does converge. # + [markdown] id="0KmzfFB5zwvd" # ## Task 3: Increase the learning rate # # In Task 2, you increased the number of epochs to get the model to converge. Sometimes, you can get the model to converge more quickly by increasing the learning rate. However, setting the learning rate too high often makes it impossible for a model to converge. In Task 3, we've intentionally set the learning rate too high. Run the following code cell and see what happens. # + id="eD1hTmdd0uCo" # Increase the learning rate and decrease the number of epochs. learning_rate=100 epochs=500 my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + [markdown] id="c96ITm021NEV" # The resulting model is terrible; the red line doesn't align with the blue dots. Furthermore, the loss curve oscillates like a [roller coaster](https://www.wikipedia.org/wiki/Roller_coaster). An oscillating loss curve strongly suggests that the learning rate is too high. # + [markdown] id="r63YkMx82WVr" # ## Task 4: Find the ideal combination of epochs and learning rate # # Assign values to the following two hyperparameters to make training converge as efficiently as possible: # # * learning_rate # * epochs # + id="ZYC8eR5x5n4m" # Set the learning rate and number of epochs learning_rate= 0.2 # Replace ? with a floating-point number epochs= 55 # Replace ? with an integer my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + id="_GMGgR6O54IN" #@title Double-click to view a possible solution learning_rate=0.14 epochs=70 my_batch_size=12 my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + [markdown] id="0NDET9e6AAbA" # ## Task 5: Adjust the batch size # # The system recalculates the model's loss value and adjusts the model's weights and bias after each **iteration**. Each iteration is the span in which the system processes one batch. For example, if the **batch size** is 6, then the system recalculates the model's loss value and adjusts the model's weights and bias after processing every 6 examples. # # One **epoch** spans sufficient iterations to process every example in the dataset. For example, if the batch size is 12, then each epoch lasts one iteration. However, if the batch size is 6, then each epoch consumes two iterations. # # It is tempting to simply set the batch size to the number of examples in the dataset (12, in this case). However, the model might actually train faster on smaller batches. Conversely, very small batches might not contain enough information to help the model converge. # # Experiment with `batch_size` in the following code cell. What's the smallest integer you can set for `batch_size` and still have the model converge in a hundred epochs? # + id="_vGx0lOodQrT" learning_rate=0.05 epochs=100 my_batch_size= 15 # Replace ? with an integer. my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + id="-mtVpoBrANAm" #@title Double-click to view a possible solution learning_rate=0.05 epochs=125 my_batch_size=1 # Wow, a batch size of 1 works! my_model = build_model(learning_rate) trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, my_label, epochs, my_batch_size) plot_the_model(trained_weight, trained_bias, my_feature, my_label) plot_the_loss_curve(epochs, rmse) # + [markdown] id="aS3q7TIF9SFL" # ## Summary of hyperparameter tuning # # Most machine learning problems require a lot of hyperparameter tuning. Unfortunately, we can't provide concrete tuning rules for every model. Lowering the learning rate can help one model converge efficiently but make another model converge much too slowly. You must experiment to find the best set of hyperparameters for your dataset. That said, here are a few rules of thumb: # # * Training loss should steadily decrease, steeply at first, and then more slowly until the slope of the curve reaches or approaches zero. # * If the training loss does not converge, train for more epochs. # * If the training loss decreases too slowly, increase the learning rate. Note that setting the learning rate too high may also prevent training loss from converging. # * If the training loss varies wildly (that is, the training loss jumps around), decrease the learning rate. # * Lowering the learning rate while increasing the number of epochs or the batch size is often a good combination. # * Setting the batch size to a *very* small batch number can also cause instability. First, try large batch size values. Then, decrease the batch size until you see degradation. # * For real-world datasets consisting of a very large number of examples, the entire dataset might not fit into memory. In such cases, you'll need to reduce the batch size to enable a batch to fit into memory. # # Remember: the ideal combination of hyperparameters is data dependent, so you must always experiment and verify.
ml/cc/exercises/linear_regression_with_synthetic_data.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/sanikamal/tensorflow-AtoZ/blob/master/flowers_with_transfer_learning.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] colab_type="text" id="NxjpzKTvg_dd" # # TensorFlow Hub # + [markdown] colab_type="text" id="crU-iluJIEzw" # [TensorFlow Hub](http://tensorflow.org/hub) is an online repository of already trained TensorFlow models that you can use. # These models can either be used as is, or they can be used for Transfer Learning. # # Transfer learning is a process where you take an existing trained model, and extend it to do additional work. This involves leaving the bulk of the model unchanged, while adding and retraining the final layers, in order to get a different set of possible outputs. # # Here, you can see all the models available in [TensorFlow Module Hub](https://tfhub.dev/). # # Before starting this Colab, you should reset the Colab environment by selecting `Runtime -> Reset all runtimes...` from menu above. # + [markdown] colab_type="text" id="7RVsYZLEpEWs" # # Imports # # # + [markdown] colab_type="text" id="fL7DqCwbmfwi" # This Colab will require us to use some things which are not yet in official releases of TensorFlow. So below, we're first installing a nightly version of TensorFlow as well as TensorFlow Hub. # # This will switch your installation of TensorFlow in Colab to this TensorFlow version. Once you are finished with this Colab, you should switch batch to the latest stable release of TensorFlow by doing selecting `Runtime -> Reset all runtimes...` in the menus above. This will reset the Colab environment to its original state. # + colab_type="code" id="e3BXzUGabcI9" colab={} # !pip install tf-nightly-gpu # !pip install "tensorflow_hub==0.4.0" # !pip install -U tensorflow_datasets # + [markdown] colab_type="text" id="ZUCEcRdhnyWn" # Some normal imports we've seen before. The new one is importing tensorflow_hub which was installed above, and which this Colab will make heavy use of. # + colab_type="code" id="OGNpmn43C0O6" colab={} from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import matplotlib.pyplot as plt import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) tf.enable_eager_execution() import tensorflow_hub as hub import tensorflow_datasets as tfds from tensorflow.keras import layers # + [markdown] colab_type="text" id="amfzqn1Oo7Om" # # Download the Flowers Dataset using TensorFlow Datasets # + [markdown] colab_type="text" id="Z93vvAdGxDMD" # In the cell below you will download the Flowers dataset using TensorFlow Datasets. If you look at the [TensorFlow Datasets documentation](https://www.tensorflow.org/datasets/datasets#tf_flowers) you will see that the name of the Flowers dataset is `tf_flowers`. You can also see that this dataset is only split into a TRAINING set. You will therefore have to use `tfds.splits` to split this training set into to a `training_set` and a `validation_set`. Do a `[70, 30]` split such that 70 corresponds to the `training_set` and 30 to the `validation_set`. Then load the `tf_flowers` dataset using `tfds.load`. Make sure the `tfds.load` function uses the all the parameters you need, and also make sure it returns the dataset info, so we can retrieve information about the datasets. # # # # + colab_type="code" id="oXiJjX0jfx1o" colab={} splits = tfds.Split.TRAIN.subsplit([70, 30]) (training_set, validation_set), dataset_info = tfds.load('tf_flowers', with_info=True, as_supervised=True, split=splits) # + [markdown] colab_type="text" id="X0p1sOEHf0JF" # # Print Information about the Flowers Dataset # # Now that you have downloaded the dataset, use the dataset info to print the number of classes in the dataset, and also write some code that counts how many images we have in the training and validation sets. # + colab_type="code" id="DrIUV3V0xDL_" colab={} num_classes = dataset_info.features['label'].num_classes num_training_examples = 0 num_validation_examples = 0 for example in training_set: num_training_examples += 1 for example in validation_set: num_validation_examples += 1 print('Total Number of Classes: {}'.format(num_classes)) print('Total Number of Training Images: {}'.format(num_training_examples)) print('Total Number of Validation Images: {} \n'.format(num_validation_examples)) # + [markdown] colab_type="text" id="UlFZ_hwjCLgS" # The images in the Flowers dataset are not all the same size. # + colab_type="code" id="W4lDPkn2cpWZ" colab={} for i, example in enumerate(training_set.take(5)): print('Image {} shape: {} label: {}'.format(i+1, example[0].shape, example[1])) # + [markdown] colab_type="text" id="mbgpD3E6gM2P" # # Reformat Images and Create Batches # # In the cell below create a function that reformats all images to the resolution expected by MobileNet v2 (224, 224) and normalizes them. The function should take in an `image` and a `label` as arguments and should return the new `image` and corresponding `label`. Then create create training and validation batches of size `32`. # + colab_type="code" id="we_ftzQxNf7e" colab={} IMAGE_RES = 224 def format_image(image, label): image = tf.image.resize(image, (IMAGE_RES, IMAGE_RES))/255.0 return image, label BATCH_SIZE = 32 train_batches = training_set.shuffle(num_training_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1) validation_batches = validation_set.map(format_image).batch(BATCH_SIZE).prefetch(1) # + [markdown] colab_type="text" id="JzV457OXreQP" # # Do Simple Transfer Learning with TensorFlow Hub # # Let's now use TensorFlow Hub to do Transfer Learning. Remember, in transfer learning we reuse parts of an already trained model and change the final layer, or several layers, of the model, and then retrain those layers on our own dataset. # # ### Create a Feature Extractor # In the cell below create a `feature_extractor` using MobileNet v2. Remember that the partial model from TensorFlow Hub (without the final classification layer) is called a feature vector. Go to the [TensorFlow Hub documentation](https://tfhub.dev/s?module-type=image-feature-vector&q=tf2) to see a list of available feature vectors. Click on the `tf2-preview/mobilenet_v2/feature_vector`. Read the docuemntation and get the corresponding `URL` to get the MobileNet v2 feature vector. Finally, ceate a `feature_extractor` by using `hub.KerasLayer` with the correct `input_shape` parameter. # + colab_type="code" id="5wB030nezBwI" colab={} URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2" feature_extractor = hub.KerasLayer(URL, input_shape=(IMAGE_RES, IMAGE_RES,3)) # + [markdown] colab_type="text" id="CtFmF7A5E4tk" # ### Freeze the Pre-Trained Model # # In the cell below freeze the variables in the feature extractor layer, so that the training only modifies the final classifier layer. # + colab_type="code" id="Jg5ar6rcE4H-" colab={} feature_extractor.trainable = False # + [markdown] colab_type="text" id="RPVeouTksO9q" # ### Attach a classification head # # In the cell below create a `tf.keras.Sequential` model, and add the pre-trained model and the new classification layer. Remember that the classification layer must have the same number of classes as our Flowers dataset. Finally print a sumary of the Sequential model. # + colab_type="code" id="mGcY27fY1q3Q" colab={} model = tf.keras.Sequential([ feature_extractor, layers.Dense(num_classes, activation='softmax') ]) model.summary() # + [markdown] colab_type="text" id="OHbXQqIquFxQ" # ### Train the model # # In the cell bellow train this model like any other, by first calling `compile` and then followed by `fit`. Make sure you use the proper parameters when applying both methods. Train the model for only 6 epochs. # + colab_type="code" id="3n0Wb9ylKd8R" colab={} model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) EPOCHS = 6 history = model.fit(train_batches, epochs=EPOCHS, validation_data=validation_batches) # + [markdown] colab_type="text" id="76as-K8-vFQJ" # You can see we get ~88% validation accuracy with only 6 epochs of training, which is absolutely awesome. This is a huge improvement over the model we created in the previous lesson, where we were able to get ~76% accuracy with 80 epochs of training. The reason for this difference is that MobileNet v2 was carefully designed over a long time by experts, then trained on a massive dataset (ImageNet). # + [markdown] colab_type="text" id="SLxTcprUqJaq" # # Plot Training and Validation Graphs. # # In the cell below, plot the training and validation accuracy/loss graphs. # + colab_type="code" id="d28dhbFpr98b" colab={} acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(EPOCHS) plt.figure(figsize=(8, 8)) 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] colab_type="text" id="5zmoDisGvNye" # What is a bit curious here is that validation performance is better than training performance, right from the start to the end of execution. # # One reason for this is that validation performance is measured at the end of the epoch, but training performance is the average values across the epoch. # # The bigger reason though is that we're reusing a large part of MobileNet which is already trained on Flower images. # + [markdown] colab_type="text" id="kb__ZN8uFn-D" # # Check Predictions # # In the cell below get the label names from the dataset info and convert them into a NumPy array. Print the array to make sure you have the correct label names. # + colab_type="code" id="W_Zvg2i0fzJu" colab={} class_names = np.array(dataset_info.features['label'].names) print(class_names) # + [markdown] colab_type="text" id="4Olg6MsNGJTL" # ### Create an Image Batch and Make Predictions # # In the cell below, use the `next()` fucntion to create an `image_batch` and its corresponding `label_batch`. Convert both the `image_batch` and `label_batch` to numpy arrays using the `.numpy()` method. Then use the `.predict()` method to run the image batch through your model and make predictions. Then use the `np.argmax()` function to get the indices of the best prediction for each image. Finally convert the indices of the best predcitions to class names. # + colab_type="code" id="fCLVCpEjJ_VP" colab={} image_batch, label_batch = next(iter(train_batches)) image_batch = image_batch.numpy() label_batch = label_batch.numpy() predicted_batch = model.predict(image_batch) predicted_batch = tf.squeeze(predicted_batch).numpy() predicted_ids = np.argmax(predicted_batch, axis=-1) predicted_class_names = class_names[predicted_ids] print(predicted_class_names) # + [markdown] colab_type="text" id="CkGbZxl9GZs-" # ### Print True Labels and Predicted Indices # # In the cell below, print the the true labels and the indices of predicted labels. # + colab_type="code" id="nL9IhOmGI5dJ" colab={} print("Labels: ", label_batch) print("Predicted labels: ", predicted_ids) # + [markdown] colab_type="text" id="gJDyzEfYuFcW" # # Plot Model Predictions # + colab_type="code" id="wC_AYRJU9NQe" colab={} plt.figure(figsize=(10,9)) for n in range(30): plt.subplot(6,5,n+1) plt.imshow(image_batch[n]) color = "blue" if predicted_ids[n] == label_batch[n] else "red" plt.title(predicted_class_names[n].title(), color=color) plt.axis('off') _ = plt.suptitle("Model predictions (blue: correct, red: incorrect)")
flowers_with_transfer_learning.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 nltk.classify.util from nltk.classify import NaiveBayesClassifier from nltk.corpus import movie_reviews # A function that extracts which words exist in a text based on a list of words to which we compare. def word_feats(words): return dict([(word, True) for word in words]) # - votes= pd.read_csv("usa-2016-presidential-election-by-county.csv", error_bad_lines=False, sep=";") votes.head() votes_state= votes.groupby(by=['State'], as_index=False)[["Votes", "Votes16 Trumpd", "Votes16 Clintonh"]].sum() votes["State"] votes_state votes_state["Trump %"]= (votes_state["Votes16 Trumpd"]/votes_state["Votes"])*100 votes_state votes_state["Clinton %"]= (votes_state["Votes16 Clintonh"]/votes_state["Votes"])*100 votes_state["T or H"]= for i in votes_state: if votes_state["Trump %"] > votes_state["Clinton %"]: votes_state["T or H"] =="T" else: votes_state["T or H"] =="H" votes_state['T or H'] = np.where(votes_state["Trump %"] > votes_state["Clinton %"], "Trump", "Hillary") votes_state= votes_state.drop([1]) votes_state votes_state.to_csv('US_2016_winners.csv', index=False)
Tweets with Votes.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 # --- # ### Imports # + # Standard imports import numpy as np import pandas as pd from collections import Counter, OrderedDict import re import string from numpy import inf # NLTK imports from nltk.tokenize import WordPunctTokenizer from nltk.stem.snowball import SnowballStemmer from nltk.corpus import stopwords # SKLearn related imports import sklearn from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.base import TransformerMixin from sklearn import preprocessing from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn.metrics.pairwise import cosine_similarity # - # # Let's look at some Movie Reviews # After learning all about tokenization and regexes, let's start doing some cool stuff and apply it in a true dataset! # # In Part II of this BLU, we're going to look into how to transform text into something that is meaningful to a machine. As you may have noticed, text is a bit different from other datasets you might have seen - it's just a bunch of words stringed together! Where are the features in a tightly organized table of examples? Unlike other data you might have worked with in previous BLU's, text is unstructured and thus needs some additional work on our end to make it structured and ready to be handled by a machine learning algorithm. # # <img src="../media/xkcd_language_nerd.png" width="300"> # # Language can be messy. One thing is clear - we need features. To get features from a string of text, or a **document**, is to **vectorize** it. Normally, this means that our feature space is the **vocabulary** of the examples present in our dataset, that is, the set of unique words we can find in all of the training examples. # # But enough talk - let's get our hands dirty! # # In this BLU, we're going to work with some movie reviews from IMDB. Let's load the dataset into pandas... df = pd.read_csv('../data/imdb_sentiment.csv') df.head() # As you can see there are two columns in this dataset - one for the labels and another for the text of the movie review. Each example is labeled as a positive or negative review. Our goal is to retrieve meaningful features from the text so a machine can predict if a given unlabeled review is positive or negative. # # Let's see a positive and a negative example. pos_example = df.text[4835] print(df.sentiment[4835]) print(pos_example) # Nice! So here's a review about *The Lion King 1 and a 1/2* (a.k.a. *The Lion King 3* in some countries). It seems the reviewer liked it. neg_example = df.text[4] print(df.sentiment[4]) print(neg_example) # Yikes. I guess that's a pass for this one, right? # # Let's get the first 200 documents of this dataset to run experiments faster. docs = df.text[:200] # As we learned in Part I, we can tokenize and stem our text to be able to extract better features. Let's initialize our favorite tokenizer and stemmer. tokenizer = WordPunctTokenizer() stemmer = SnowballStemmer("english", ignore_stopwords=True) # We can also use a regex to clean our sentences. We can see from the examples above that our corpus has some html substrings `<br />` that are only polluting the sentences. We can remove them with `re.sub()` by substituting every substring that matches the regex `<[^>]*>` with an empty string. # # We will define a `clean()` method that removes these unnecessary html tags, tokenizes and stems our corpus' sentences. def clean(doc): # remove html tags doc = re.sub("<[^>]*>", "", doc) # lowercase doc = doc.lower() # tokenize words = tokenizer.tokenize(doc) # remove punctuation words = list(filter(lambda x: x not in string.punctuation, words)) # stem stems = list(map(stemmer.stem, words)) new_doc = " ".join(stems) return new_doc docs = docs.apply(clean) # Let's see one of the above examples again, after we cleaned the corpus. docs[4] # Well, we may not understand it as well now, but we actually just made the text much easier for a machine to read. # As we said, our feature space in text will be the vocabulary of our data. In our example, this is the set of unique words and symbols present in our documents. # # To create our vocabulary, we will use a `Counter()`. `Counter()` is a dictionary that counts the number of ocurrences of different tokens in a list and can be updated with each sentence of our corpus. # # After getting all counts for each unique token, we sort our dictionary by counts using `Counter()`'s built-in method `.most_common()`, and store everything in an `OrderedDict()`. This makes sure our vectorized representations of the documents will be ordered according to the most common words in the whole corpus (this is not required, but makes data visualization much nicer!). # + def build_vocabulary(): vocabulary = Counter() for doc in docs: words = doc.split() vocabulary.update(words) return OrderedDict(vocabulary.most_common()) # turn into a list of tuples and get the first 20 items list(build_vocabulary().items())[:20] # - # # Representing Text through a Bag of Words # Now that we have our vocabulary, we can vectorize our documents. The value of our features will be the most simple vectorization of a document there is - the word counts. # # By doing this, each column value is the number of times that word of the vocabulary appeared in the document. This is what is called a **Bag of Words** (BoW) representation. # # Note that this type of vectorization of the document loses all the syntactic information of it. That is, you could shuffle the words in document and get the same vector (that's why it's called a bag of words). Of course, since we are trying to understand if a movie review is positive or negative, one could argue that what really matters as features is what kind of words appear in the documents and not their order. def vectorize(): vocabulary = build_vocabulary() vectors = [] for doc in docs: words = doc.split() vector = np.array([doc.count(word) for word in vocabulary]) vectors.append(vector) return vectors # We can visualize this better if we use a pandas DataFrame. # + def build_df(): return pd.DataFrame(vectorize(), columns=build_vocabulary()) build_df().head() # - # # Stopwords # We're looking for the most meaningful features in our vocabulary to tell us in what category our document falls into. Text is filled with words that are unimportant to the meaning of a particular sentence like "the" or "and". This is in contrast with words like "love" or "hate" that have a very clear semantic meaning. The former example of words are called **stopwords** - words that _usually_ don't introduce any meaning to a piece of text and are often just in the document for syntactic reasons. # # It's important to emphasize that we used "usually" in our previous statement. You should be aware that sometimes stopwords can be useful features, especially when we use more than just unigrams as features (ex.: bigrams, trigrams, ...) and word order and word combination starts to be relevant. # # You can easily find lists of stopwords for several languages in the internet. You can find one for english in the `data` folder. # + stopwords = [line.strip("\n") for line in open("../data/english_stopwords.txt", "r")] stopwords[:20] # - # Let's update our build_vocabulary() and vectorize() functions and remove these words from the text. This way we will reduce our vocabulary - and thus our feature space - making our representations more lightweight. # + def build_vocabulary(): vocabulary = Counter() for doc in docs: words = [word for word in doc.split() if word not in stopwords] vocabulary.update(words) return OrderedDict(vocabulary.most_common()) def vectorize(): vocabulary = build_vocabulary() vectors = [] for doc in docs: words = doc.split() vector = np.array([doc.count(word) for word in vocabulary if word not in stopwords]) vectors.append(vector) return vectors BoW = build_df() BoW.head() # - # Another thing that we could do is to normalize our counts. As you can see, different documents have different number of words: BoW.sum(axis=1).head() # This can introduce bias in our features, so we should normalize each document by its number of words. This way, instead of having word counts as features of our model, we will have **term frequencies**. This way, the features in any document of the dataset sum to 1: tf = BoW.div(BoW.sum(axis=1), axis=0) tf.sum(axis=1).head() # # Kicking it up a notch with TF-IDF # It should be clear by now that not all words have the same importance to find out in what category a document falls into. # # In our dataset, if we want to classify a review as positive, for instance, the word "_good_" is much more informative than "_house_", and we should give it more weight as a feature. # # In general, words that are very common in the corpus are less informative than rare words. # # That is the rational behind **Term Frequency - Inverse Document Frequency (TF-IDF)**: # # $$ tfidf _{t, d} =(log_2{(1 + tf_{t,d})})*(log_2{(1 + \frac{N}{df_{t}})}) $$ # # where $t$ and $d$ are the term and document for which we are computing a feature, $tf_{t,d}$ is the term frequency of term $t$ in document $d$, $N$ is the total number of documents we have, while $df_{t}$ is the number of documents that contain $t$. # # We are using the word frequencies we were using before, but now we are weighting each by the inverse of the number of times they occur in all the documents. The more a word appears in a document and the less it appears in other documents, the higher is the TF-IDF of that word in that document. # # In short, we measure *the term frequency, weighted by its rarity in the entire corpus*. # # **Note**: TF-IDF can vary in formulation - the idea is always the same but computation might change slightly. In our case, we are choosing to log-normalize our frequencies. # + def idf(column): return np.log2(1 + len(column) / sum(column > 0)) tf_idf = (np.log2(1 + tf)).multiply(tf.apply(idf)) tf_idf.head() # - # An interesting thing we can do with our feature representations is to check similarities between words. To do this, instead of seeing the vocabulary as the features of a given document, we see each document as a feature of a given term in the vocabulary. By doing this, we get a vectorized representation of a word! # # A very popular way of computing similarities between vectors is to compute the cosine similarity. # # Let's check the similarity between the word _movi_ (which is the stem of _movie_) and the word _film_ in our Bag of Words representation. cosine_similarity(BoW['movi'].values.reshape(1,-1), BoW['film'].values.reshape(1,-1)) # Now, let's compute it for _movi_ and _shoe_. We should get a lower similarity score. cosine_similarity(BoW['movi'].__array__().reshape(1,-1), BoW['shoe'].__array__().reshape(1,-1)) # Let's check the same similarity scores but in the tf-idf representation: cosine_similarity(tf_idf['movi'].__array__().reshape(1,-1), tf_idf['film'].__array__().reshape(1,-1)) cosine_similarity(tf_idf['movi'].__array__().reshape(1,-1), tf_idf['shoe'].__array__().reshape(1,-1)) # Nice! The gap between the similarities of these pair of words increased with our tf-idf representation. This means that our tf-idf model is computing better and more meaningful features than our BoW model. This will surely help when we feed these feature matrices to a classifier.
Natural-Language-Processing/Feature-Extraction/BLU 7 Part II.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 # --- # # OOI Equipment mapping # - 6/22: tweaked and tested by Emilio # - by <NAME> # - 6/14/2016 # - This notebook is for retrieving information from google sheets and then mapping to a JSON file, each instrument has its own JSON file configuration # - The required libraries for this manipulation is *gspread*, *oauth2client*, and *pycrypto* # ### TO-DO: # - 6/22: CHANGE depth_m TO BE A STRING? eg, '-1m' # - Handle "measurements" sheet, too import os import json import numpy as np import pandas as pd def get_googlesheet_doc(gdocjson_pth, doc_name): import oauth2client import gspread # Get Google docs json token and scope for google sheets gdocstoken_json = os.path.join(gdocjson_pth, '.gdocs_Nanoos-fcdeeb760f83.json') scope = ['https://spreadsheets.google.com/feeds'] # Retrieve credentials from JSON key of service account # oauth_ver = oauth2client.__version__ try: from oauth2client.service_account import ServiceAccountCredentials credentials = ServiceAccountCredentials.from_json_keyfile_name(gdocstoken_json, scope) except: from oauth2client.client import SignedJwtAssertionCredentials with open(gdocstoken_json) as f: json_key = json.load(f) credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope) gc = gspread.authorize(credentials) sheetgdoc = gc.open(doc_name) return sheetgdoc # ## Testing with vizer google credentials # + import vizer.tsharvest.util as vhutil vizer = vhutil.Vizer('nvs', False) # - gdoc = get_googlesheet_doc(vizer.vizerspath, "sensor_configurations_mappings") sheet = gdoc.worksheet('instruments') # ## Parsing data to a pandas dataframe # Now that connection has been established, data is parsed to be viewed sheetvalues = sheet.get_all_values() # Convert data into pandas dataframe df = pd.DataFrame(sheetvalues[1:], columns=sheetvalues[0]) df = df.convert_objects(convert_numeric=True) df.head() # Get Platforms json_data = df[['platform', 'instrument', 'depth_m', 'mfn', 'deployment', 'data_logger', 'subtype', 'magnetic_declin_correction']].reset_index(drop=True) platforms = json_data['platform'].unique() # Create platform dictionary. Eliminate instruments with blank instrument strings, # and platforms containing only such instruments. platforms_dct = {} for platform in platforms: instruments_df = json_data.loc[json_data['platform'] == platform] instruments_tmp_dct = {} for idx, instruments_df_row in instruments_df.iterrows(): row_dct = instruments_df_row.to_dict() instrument = row_dct['instrument'] row_dct['mfn'] = True if row_dct['mfn'] == 'x' else False if row_dct['subtype'] != '': row_dct['subtype'] = int(row_dct['subtype'].split('::')[1]) else: row_dct['subtype'] = None if np.isnan(row_dct['magnetic_declin_correction']): row_dct['magnetic_declin_correction'] = None row_dct.pop('platform', None) row_dct.pop('instrument', None) if len(instrument) > 1: instruments_tmp_dct[instrument] = row_dct if instruments_tmp_dct: platforms_dct[platform] = instruments_tmp_dct platforms_dct.keys() platforms_dct['CE09OSSM'].keys() # prints the JSON structured dictionary jsont_str = json.dumps(platforms_dct, sort_keys=True, indent=4) print(jsont_str) # ## Output to JSON fpth = os.path.join(vizer.vizerspath, 'nvs', 'siso_ooi_harvest.json') with open(fpth, 'w') as fojson: fojson.write(jsont_str)
OOI/OOI_equipment_mapping_Emilio.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 # --- # <p style="font-size:32px;text-align:center"> <b>Social network Graph Link Prediction - Facebook Challenge</b> </p> # + #Importing Libraries # please do go through this python notebook: import warnings warnings.filterwarnings("ignore") import csv import pandas as pd import datetime import time import numpy as np import matplotlib import matplotlib.pylab as plt import seaborn as sns from matplotlib import rcParams from sklearn.cluster import MiniBatchKMeans, KMeans import math import pickle import os import xgboost as xgb import warnings import networkx as nx import pdb import pickle from pandas import HDFStore,DataFrame from pandas import read_hdf from scipy.sparse.linalg import svds, eigs import gc from tqdm import tqdm # - # # 1. Reading Data if os.path.isfile('data/after_eda/train_pos_after_eda.csv'): train_graph=nx.read_edgelist('data/after_eda/train_pos_after_eda.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) print(nx.info(train_graph)) else: print("please run the FB_EDA.ipynb or download the files from drive") # # 2. Similarity measures # ## 2.1 Jaccard Distance: # http://www.statisticshowto.com/jaccard-index/ #for followees # code copied from StackOverflow def jaccard_for_followees(a,b): if len(set(train_graph.successors(a))) == 0 | len(set(train_graph.successors(b))) == 0: return 0 sim = (len(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))))/\ (len(set(train_graph.successors(a)).union(set(train_graph.successors(b))))) return sim #one test case print(jaccard_for_followees(273084,1505602)) #node 1635354 not in graph print(jaccard_for_followees(273084,1505602)) #for followers # code copied from StackOverflow def jaccard_for_followers(a,b): try: if len(set(train_graph.predecessors(a))) == 0 | len(set(g.predecessors(b))) == 0: return 0 sim = (len(set(train_graph.predecessors(a)).intersection(set(train_graph.predecessors(b)))))/\ (len(set(train_graph.predecessors(a)).union(set(train_graph.predecessors(b))))) return sim except: return 0 print(jaccard_for_followers(273084,470294)) #node 1635354 not in graph print(jaccard_for_followees(669354,1635354)) # ## 2.2 Cosine distance (Otsuka-Ochiai coefficient) #for followees def cosine_for_followees(a,b): try: if len(set(train_graph.successors(a))) == 0 | len(set(train_graph.successors(b))) == 0: return 0 sim = (len(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))))/\ (math.sqrt(len(set(train_graph.successors(a)))*len((set(train_graph.successors(b)))))) return sim except: return 0 print(cosine_for_followees(273084,1505602)) print(cosine_for_followees(273084,1635354)) def cosine_for_followers(a,b): try: if len(set(train_graph.predecessors(a))) == 0 | len(set(train_graph.predecessors(b))) == 0: return 0 sim = (len(set(train_graph.predecessors(a)).intersection(set(train_graph.predecessors(b)))))/\ (math.sqrt(len(set(train_graph.predecessors(a))))*(len(set(train_graph.predecessors(b))))) return sim except: return 0 print(cosine_for_followers(2,470294)) print(cosine_for_followers(669354,1635354)) # # Page Rank # # # # PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. if not os.path.isfile('data/fea_sample/page_rank.p'): pr = nx.pagerank(train_graph, alpha=0.85) # alpha is some hyperparameter pickle.dump(pr,open('data/fea_sample/page_rank.p','wb')) else: pr = pickle.load(open('data/fea_sample/page_rank.p','rb')) print('min',pr[min(pr, key=pr.get)]) print('max',pr[max(pr, key=pr.get)]) print('mean',float(sum(pr.values())) / len(pr)) #for imputing to nodes which are not there in Train data mean_pr = float(sum(pr.values())) / len(pr) print(mean_pr) # # Shortest path: # Getting Shortest path between two nodes, # if has direct edge then deleting that edge and calculating shortest path # https://stackoverflow.com/questions/9430027/networkx-shortest-path-length def compute_shortest_path_length(a,b): p=-1 try: p = nx.shortest_path_length(train_graph,source=a,target=b) return p except: return -1 #testing compute_shortest_path_length(77697, 826021) #testing compute_shortest_path_length(669354,1635354) # # Checking for same weakly conected component (Community) #getting weekly connected edges from graph wcc=list(nx.weakly_connected_components(train_graph)) def belongs_to_same_wcc(a,b): index = [] if train_graph.has_edge(b,a) or train_graph.has_edge(a,b): return 1 else: for i in wcc: if a in i: index= i break if(b in index): return 1 else: return 0 belongs_to_same_wcc(861, 1659750) belongs_to_same_wcc(669354,1635354) # # Adamic/Adar Index: # Adamic/Adar measures is defined as inverted sum of degrees of common neighbours for given two vertices. # $$A(x,y)=\sum_{u \in N(x) \cap N(y)}\frac{1}{log(|N(u)|)}$$ #adar index def calc_adar_in(a,b): sum=0 try: n=list(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))) if len(n)!=0: for i in n: sum=sum+(1/np.log10(len(list(train_graph.predecessors(i))))) return sum else: return 0 except: return 0 calc_adar_in(1,189226) calc_adar_in(669354,1635354) # # Does the person follow back? def follows_back(a,b): if train_graph.has_edge(b,a): return 1 else: return 0 follows_back(1,189226) follows_back(669354,1635354) # # Katz Centrality: # https://en.wikipedia.org/wiki/Katz_centrality # # https://www.geeksforgeeks.org/katz-centrality-centrality-measure/ # if not os.path.isfile('data/fea_sample/katz.p'): katz = nx.katz.katz_centrality(train_graph,alpha=0.005,beta=1) pickle.dump(katz,open('data/fea_sample/katz.p','wb')) else: katz = pickle.load(open('data/fea_sample/katz.p','rb')) print('min',katz[min(katz, key=katz.get)]) print('max',katz[max(katz, key=katz.get)]) print('mean',float(sum(katz.values())) / len(katz)) mean_katz = float(sum(katz.values())) / len(katz) print(mean_katz) # # HITS Score # The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. # # https://en.wikipedia.org/wiki/HITS_algorithm import pickle if not os.path.isfile('data/fea_sample/hits.p'): # returns tuple of 2 dictionary,(hubs,authorities) hits = nx.hits(train_graph, max_iter=100, tol=1e-08, nstart=None, normalized=True) pickle.dump(hits,open('data/fea_sample/hits.p','wb')) else: hits = pickle.load(open('data/fea_sample/hits.p','rb')) type(hits), type(hits[0]), type(hits[1]) # tuple of 2, hub dict, auth dict # + import math inf = math.inf Min=inf Max = -1 for key, item in hits[0].items(): Min = min(Min, item) Max = max(Max, item) print('min',Min) print('max',Max) print('mean',float(sum(hits[0].values())) / len(hits[0])) # - # # Featurization # # Reading a sample of Data from both train and test import random if os.path.isfile('data/after_eda/train_after_eda.csv'): filename = "data/after_eda/train_after_eda.csv" # you uncomment this line, if you dont know the lentgh of the file name # here we have hardcoded the number of lines as 15100030 # n_train = sum(1 for line in open(filename)) #number of records in file (excludes header) n_train = 15100028 s = 100000 #desired sample size skip_train = sorted(random.sample(range(1,n_train+1),n_train-s)) #https://stackoverflow.com/a/22259008/4084039 if os.path.isfile('data/after_eda/train_after_eda.csv'): filename = "data/after_eda/test_after_eda.csv" # you uncomment this line, if you dont know the lentgh of the file name # here we have hardcoded the number of lines as 3775008 # n_test = sum(1 for line in open(filename)) #number of records in file (excludes header) n_test = 3775006 s = 50000 #desired sample size skip_test = sorted(random.sample(range(1,n_test+1),n_test-s)) #https://stackoverflow.com/a/22259008/4084039 print("Number of rows in the train data file:", n_train) print("Number of rows we are going to elimiate in train data are",len(skip_train)) print("Number of rows in the test data file:", n_test) print("Number of rows we are going to elimiate in test data are",len(skip_test)) df_final_train = pd.read_csv('data/after_eda/train_after_eda.csv', skiprows=skip_train, names=['source_node', 'destination_node']) df_final_train['indicator_link'] = pd.read_csv('data/train_y.csv', skiprows=skip_train, names=['indicator_link']) print("Our train matrix size ",df_final_train.shape) df_final_train.head(2) df_final_test = pd.read_csv('data/after_eda/test_after_eda.csv', skiprows=skip_test, names=['source_node', 'destination_node']) df_final_test['indicator_link'] = pd.read_csv('data/test_y.csv', skiprows=skip_test, names=['indicator_link']) print("Our test matrix size ",df_final_test.shape) df_final_test.head(2) # ## 5.2 Adding a set of features # # __we will create these each of these features for both train and test data points__ # <ol> # <li>jaccard_followers</li> # <li>jaccard_followees</li> # <li>cosine_followers</li> # <li>cosine_followees</li> # <li>num_followers_s</li> # <li>num_followees_s</li> # <li>num_followers_d</li> # <li>num_followees_d</li> # <li>inter_followers</li> # <li>inter_followees</li> # </ol> if not os.path.isfile('data/fea_sample/storage_sample_stage1.h5'): #mapping jaccrd followers to train and test data df_final_train['jaccard_followers'] = df_final_train.apply(lambda row: jaccard_for_followers(row['source_node'],row['destination_node']),axis=1) df_final_test['jaccard_followers'] = df_final_test.apply(lambda row: jaccard_for_followers(row['source_node'],row['destination_node']),axis=1) #mapping jaccrd followees to train and test data df_final_train['jaccard_followees'] = df_final_train.apply(lambda row: jaccard_for_followees(row['source_node'],row['destination_node']),axis=1) df_final_test['jaccard_followees'] = df_final_test.apply(lambda row: jaccard_for_followees(row['source_node'],row['destination_node']),axis=1) #mapping jaccrd followers to train and test data df_final_train['cosine_followers'] = df_final_train.apply(lambda row: cosine_for_followers(row['source_node'],row['destination_node']),axis=1) df_final_test['cosine_followers'] = df_final_test.apply(lambda row: cosine_for_followers(row['source_node'],row['destination_node']),axis=1) #mapping jaccrd followees to train and test data df_final_train['cosine_followees'] = df_final_train.apply(lambda row: cosine_for_followees(row['source_node'],row['destination_node']),axis=1) df_final_test['cosine_followees'] = df_final_test.apply(lambda row: cosine_for_followees(row['source_node'],row['destination_node']),axis=1) def compute_features_stage1(df_final): #calculating no of followers followees for source and destination #calculating intersection of followers and followees for source and destination num_followers_s=[] num_followees_s=[] num_followers_d=[] num_followees_d=[] inter_followers=[] inter_followees=[] for i,row in df_final.iterrows(): s1=set(train_graph.predecessors(row['source_node'])) s2=set(train_graph.successors(row['source_node'])) d1=set(train_graph.predecessors(row['destination_node'])) d2=set(train_graph.successors(row['destination_node'])) num_followers_s.append(len(s1)) num_followees_s.append(len(s2)) num_followers_d.append(len(d1)) num_followees_d.append(len(d2)) inter_followers.append(len(s1.intersection(d1))) inter_followees.append(len(s2.intersection(d2))) return num_followers_s, num_followers_d, num_followees_s, num_followees_d, inter_followers, inter_followees if not os.path.isfile('data/fea_sample/storage_sample_stage1.h5'): df_final_train['num_followers_s'], df_final_train['num_followers_d'], \ df_final_train['num_followees_s'], df_final_train['num_followees_d'], \ df_final_train['inter_followers'], df_final_train['inter_followeed']= compute_features_stage1(df_final_train) df_final_test['num_followers_s'], df_final_test['num_followers_d'], \ df_final_test['num_followees_s'], df_final_test['num_followees_d'], \ df_final_test['inter_followers'], df_final_test['inter_followeed']= compute_features_stage1(df_final_test) hdf = HDFStore('data/fea_sample/storage_sample_stage1.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage1.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage1.h5', 'test_df',mode='r') # ## 5.3 Adding new set of features # # __we will create these each of these features for both train and test data points__ # <ol> # <li>adar index</li> # <li>is following back</li> # <li>belongs to same weakly connect components</li> # <li>shortest path between source and destination</li> # </ol> networkxif not os.path.isfile('data/fea_sample/storage_sample_stage2.h5'): #mapping adar index on train df_final_train['adar_index'] = df_final_train.apply(lambda row: calc_adar_in(row['source_node'],row['destination_node']),axis=1) #mapping adar index on test df_final_test['adar_index'] = df_final_test.apply(lambda row: calc_adar_in(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping followback or not on train df_final_train['follows_back'] = df_final_train.apply(lambda row: follows_back(row['source_node'],row['destination_node']),axis=1) #mapping followback or not on test df_final_test['follows_back'] = df_final_test.apply(lambda row: follows_back(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping same component of wcc or not on train df_final_train['same_comp'] = df_final_train.apply(lambda row: belongs_to_same_wcc(row['source_node'],row['destination_node']),axis=1) ##mapping same component of wcc or not on train df_final_test['same_comp'] = df_final_test.apply(lambda row: belongs_to_same_wcc(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping shortest path on train df_final_train['shortest_path'] = df_final_train.apply(lambda row: compute_shortest_path_length(row['source_node'],row['destination_node']),axis=1) #mapping shortest path on test df_final_test['shortest_path'] = df_final_test.apply(lambda row: compute_shortest_path_length(row['source_node'],row['destination_node']),axis=1) hdf = HDFStore('data/fea_sample/storage_sample_stage2.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage2.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage2.h5', 'test_df',mode='r') # ## 5.4 Adding new set of features # # __we will create these each of these features for both train and test data points__ # <ol> # <li>Weight Features # <ul> # <li>weight of incoming edges</li> # <li>weight of outgoing edges</li> # <li>weight of incoming edges + weight of outgoing edges</li> # <li>weight of incoming edges * weight of outgoing edges</li> # <li>2*weight of incoming edges + weight of outgoing edges</li> # <li>weight of incoming edges + 2*weight of outgoing edges</li> # </ul> # </li> # <li>Page Ranking of source</li> # <li>Page Ranking of dest</li> # <li>katz of source</li> # <li>katz of dest</li> # <li>hubs of source</li> # <li>hubs of dest</li> # <li>authorities_s of source</li> # <li>authorities_s of dest</li> # </ol> # #### Weight Features # \begin{equation} # W = \frac{1}{\sqrt{1+|X|}} # \end{equation} # it is directed graph so calculated Weighted in and Weighted out differently # + #weight for source and destination of each link Weight_in = {} Weight_out = {} for i in tqdm(train_graph.nodes()): s1=set(train_graph.predecessors(i)) w_in = 1.0/(np.sqrt(1+len(s1))) Weight_in[i]=w_in s2=set(train_graph.successors(i)) w_out = 1.0/(np.sqrt(1+len(s2))) Weight_out[i]=w_out #for imputing with mean mean_weight_in = np.mean(list(Weight_in.values())) mean_weight_out = np.mean(list(Weight_out.values())) # - if not os.path.isfile('data/fea_sample/storage_sample_stage3.h5'): #mapping to pandas train, weight_in for destination node, and weight_out for source node df_final_train['weight_in'] = df_final_train.destination_node.apply(lambda x: Weight_in.get(x,mean_weight_in)) df_final_train['weight_out'] = df_final_train.source_node.apply(lambda x: Weight_out.get(x,mean_weight_out)) #mapping to pandas test, weight_in for destination node, and weight_out for source node df_final_test['weight_in'] = df_final_test.destination_node.apply(lambda x: Weight_in.get(x,mean_weight_in)) df_final_test['weight_out'] = df_final_test.source_node.apply(lambda x: Weight_out.get(x,mean_weight_out)) #some features engineerings on the in and out weights for Train Data df_final_train['weight_f1'] = df_final_train.weight_in + df_final_train.weight_out df_final_train['weight_f2'] = df_final_train.weight_in * df_final_train.weight_out df_final_train['weight_f3'] = (2*df_final_train.weight_in + 1*df_final_train.weight_out) df_final_train['weight_f4'] = (1*df_final_train.weight_in + 2*df_final_train.weight_out) #some features engineerings on the in and out weights for Test Data df_final_test['weight_f1'] = df_final_test.weight_in + df_final_test.weight_out df_final_test['weight_f2'] = df_final_test.weight_in * df_final_test.weight_out df_final_test['weight_f3'] = (2*df_final_test.weight_in + 1*df_final_test.weight_out) df_final_test['weight_f4'] = (1*df_final_test.weight_in + 2*df_final_test.weight_out) if not os.path.isfile('data/fea_sample/storage_sample_stage3.h5'): #page rank for source and destination in Train and Test #if anything not there in train graph then adding mean page rank df_final_train['page_rank_s'] = df_final_train.source_node.apply(lambda x:pr.get(x,mean_pr)) df_final_train['page_rank_d'] = df_final_train.destination_node.apply(lambda x:pr.get(x,mean_pr)) df_final_test['page_rank_s'] = df_final_test.source_node.apply(lambda x:pr.get(x,mean_pr)) df_final_test['page_rank_d'] = df_final_test.destination_node.apply(lambda x:pr.get(x,mean_pr)) #================================================================================ #Katz centrality score for source and destination in Train and test #if anything not there in train graph then adding mean katz score df_final_train['katz_s'] = df_final_train.source_node.apply(lambda x: katz.get(x,mean_katz)) df_final_train['katz_d'] = df_final_train.destination_node.apply(lambda x: katz.get(x,mean_katz)) df_final_test['katz_s'] = df_final_test.source_node.apply(lambda x: katz.get(x,mean_katz)) df_final_test['katz_d'] = df_final_test.destination_node.apply(lambda x: katz.get(x,mean_katz)) #================================================================================ #Hits algorithm score for source and destination in Train and test #if anything not there in train graph then adding 0 df_final_train['hubs_s'] = df_final_train.source_node.apply(lambda x: hits[0].get(x,0)) df_final_train['hubs_d'] = df_final_train.destination_node.apply(lambda x: hits[0].get(x,0)) df_final_test['hubs_s'] = df_final_test.source_node.apply(lambda x: hits[0].get(x,0)) df_final_test['hubs_d'] = df_final_test.destination_node.apply(lambda x: hits[0].get(x,0)) #================================================================================ #Hits algorithm score for source and destination in Train and Test #if anything not there in train graph then adding 0 df_final_train['authorities_s'] = df_final_train.source_node.apply(lambda x: hits[1].get(x,0)) df_final_train['authorities_d'] = df_final_train.destination_node.apply(lambda x: hits[1].get(x,0)) df_final_test['authorities_s'] = df_final_test.source_node.apply(lambda x: hits[1].get(x,0)) df_final_test['authorities_d'] = df_final_test.destination_node.apply(lambda x: hits[1].get(x,0)) #================================================================================ hdf = HDFStore('data/fea_sample/storage_sample_stage3.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage3.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage3.h5', 'test_df',mode='r')
FB_featurization.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 # --- # # Retrieval and Preparation of San Francisco Traffic Data # %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import wget from datetime import datetime matplotlib.rcParams['figure.figsize'] = [16, 9] pd.options.display.max_columns = 999 # ## Load Data # # Road occupancy rates (between 0 and 1) from 861 traffic sensors in San Francisco. # # Source: https://github.com/laiguokun/multivariate-time-series-data/tree/master/traffic url = 'https://github.com/laiguokun/multivariate-time-series-data/blob/master/traffic/traffic.txt.gz?raw=true' wget.download(url) # !gzip -d traffic.txt.gz df = pd.read_csv('traffic.txt', header=None) df.columns = ['ts%s' % str(col+1) for col in df.columns] df.head() # Add in datetime index (data source says data corresponds to 48 months over 2015-2016). df.index = pd.DatetimeIndex(freq='H', start=datetime(2015, 1, 1), periods=len(df)) df.index.name = 'DateTime' df.head() # No missing values df.isnull().any().all() == False for col in df.columns[:5]: df[col][:500].plot() plt.legend() plt.title("First Five Time Series") plt.ylabel("Road Occupancy"); # # Save Data # !rm traffic.txt df.to_csv('san-francisco-traffic.csv')
_datasets/san-francisco-traffic.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="5d780ueIzzTk" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1620606503760, "user_tz": -540, "elapsed": 10808, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="fceb25e0-1138-48f6-b7d4-d18690ae731a" # -*- coding: utf-8 -*- # ์ฝ”๋“œ ๋‚ด๋ถ€์— ํ•œ๊ธ€์„ ์‚ฌ์šฉ๊ฐ€๋Šฅ ํ•˜๊ฒŒ ํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค. # ๋”ฅ๋Ÿฌ๋‹์„ ๊ตฌ๋™ํ•˜๋Š” ๋ฐ ํ•„์š”ํ•œ ์ผ€๋ผ์Šค ํ•จ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค. from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค. import numpy as np import tensorflow as tf # ์‹คํ–‰ํ•  ๋•Œ๋งˆ๋‹ค ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ์„ค์ •ํ•˜๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค. np.random.seed(3) tf.random.set_seed(3) # ์ค€๋น„๋œ ์ˆ˜์ˆ  ํ™˜์ž ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ๋“ค์ž…๋‹ˆ๋‹ค. Data_set = np.loadtxt("/content/drive/MyDrive/ThoraricSurgery.csv", delimiter=",") # ํ™˜์ž์˜ ๊ธฐ๋ก๊ณผ ์ˆ˜์ˆ  ๊ฒฐ๊ณผ๋ฅผ X์™€ Y๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. X = Data_set[:,0:17] Y = Data_set[:,17] # ๋”ฅ๋Ÿฌ๋‹ ๊ตฌ์กฐ๋ฅผ ๊ฒฐ์ •ํ•ฉ๋‹ˆ๋‹ค(๋ชจ๋ธ์„ ์„ค์ •ํ•˜๊ณ  ์‹คํ–‰ํ•˜๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค). model = Sequential() model.add(Dense(30, input_dim=17, activation='relu')) model.add(Dense(1, activation='sigmoid')) # ๋”ฅ๋Ÿฌ๋‹์„ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X, Y, epochs=100, batch_size=10) # + id="iT-slNJBunDD" # + colab={"base_uri": "https://localhost:8080/"} id="dyb8u2_NvaDa" executionInfo={"status": "ok", "timestamp": 1620606396006, "user_tz": -540, "elapsed": 25769, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="7b31359f-96a3-4579-d5f5-54b855d94912" from google.colab import drive drive.mount('/content/drive') # + [markdown] id="o4OMVLJ95vge" # # ์ƒˆ ์„น์…˜ # + [markdown] id="MXlqsGUZ0LCC" # # ์ƒˆ ์„น์…˜ # + [markdown] id="NEnnBPr61S5X" # # ์ƒˆ ์„น์…˜ # + id="WiRO48hMzzTm" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1620015292043, "user_tz": -540, "elapsed": 613, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="75be1d89-c558-4d04-93c9-e2f63859e5d2" import numpy as np x = [2, 4, 6, 8] y = [81, 93, 91, 97] mx = np.mean(x) my = np.mean(y) print("x์˜ ํ‰๊ท  :", mx) print("y์˜ ํ‰๊ท  :", my) divisor = sum([(mx - i) **2 for i in x]) def top(x, mx, y, my): d = 0 for i in range(len(x)): d += (x[i] - mx) * (y[i] - my) return d devidend = top(x, mx, y, my) print("๋ถ„๋ชจ :", divisor) print("๋ถ„์ž :", devidend) a = devidend / divisor b = my - (mx*a) print("๊ธฐ์šธ๊ธฐ :", a) print("y ์ ˆํŽธ b:", b) # + colab={"base_uri": "https://localhost:8080/"} id="mrzfuKeNcA2i" executionInfo={"status": "ok", "timestamp": 1620016238218, "user_tz": -540, "elapsed": 604, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="c7f43cab-a1d4-42b2-f960-66a9fed25a76" fake_a_b = [3, 76] data = [[2,81], [4, 93], [6,91], [8, 97]] x=[i[0] for i in data] y=[i[1] for i in data] def predict(x): return fake_a_b[0]*x + fake_a_b[1] def mse(y, y_hat): return ((y-y_hat) **2).mean() def mse_val(y, predict_result): return mse(np.array(y), np.array(predict_result)) predict_result = [] for i in range(len(x)): predict_result.append(predict(x[i])) print("๊ณต๋ถ€ํ•œ ์‹œ๊ฐ„=%.f, ์‹ค์ œ ์ ์ˆ˜=%.f, ์˜ˆ์ธก ์ ์ˆ˜=%.f" % (x[i], y[i], predict(x[i]))) print("mse ์ตœ์ข…๊ฐ’=" + str(mse_val(predict_result, y))) # + colab={"base_uri": "https://localhost:8080/", "height": 320} id="mGRcfL_Buo6J" executionInfo={"status": "ok", "timestamp": 1620020281015, "user_tz": -540, "elapsed": 745, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="e8393254-0a10-46d0-a922-d49d4dd7316a" import numpy as np import pandas as pd import matplotlib.pyplot as plt #๊ณต๋ถ€์‹œ๊ฐ„ X์™€ ์„ฑ์  Y์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. data = [[2, 81], [4, 93], [6, 91], [8, 97]] x = [i[0] for i in data] y = [i[1] for i in data] #๊ทธ๋ž˜ํ”„๋กœ ๋‚˜ํƒ€๋‚ด ๋ด…๋‹ˆ๋‹ค. plt.figure(figsize=(8,5)) plt.scatter(x, y) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="fRGSYMXYu7uf" executionInfo={"status": "ok", "timestamp": 1620020635078, "user_tz": -540, "elapsed": 574, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="63f76051-8a21-4e1c-fde8-066576858f06" x_data = np.array(x) y_data = np.array(y) a = 0 b = 0 lr = 0.03 epochs = 2001 for i in range(epochs): y_hat = a * x_data + b error = y_hat - y_data a_diff = (2/len(x_data)) * sum(x_data * (error)) b_diff = (2/len(x_data)) * sum(error) a = a - lr * a_diff b = b - lr * b_diff if i % 100 == 0: print("epoch=%.f, ๊ธฐ์šธ๊ธฐ=%.04f, ์ ˆํŽธ=%.04f" % (i, a, b)) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="RFfMVcV2u81O" executionInfo={"status": "ok", "timestamp": 1620020700542, "user_tz": -540, "elapsed": 590, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="e721574b-7171-447b-8b67-d5a60dbcf66c" y_pred = a * x_data + b plt.scatter(x, y) plt.plot([min(x_data), max(x_data)], [min(y_pred), max(y_pred)]) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 248} id="0-eH_i1bwiMB" executionInfo={"status": "ok", "timestamp": 1620025884385, "user_tz": -540, "elapsed": 879, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="f9cd4d9f-eba2-449d-8d42-7224fdb499d1" import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits import mplot3d #๊ณต๋ถ€์‹œ๊ฐ„ X์™€ ์„ฑ์  Y์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. data = [[2, 0, 81], [4, 4, 93], [6, 2, 91], [8, 3, 97]] x1 = [i[0] for i in data] x2 = [i[1] for i in data] y = [i[2] for i in data] #๊ทธ๋ž˜ํ”„๋กœ ํ™•์ธํ•ด ๋ด…๋‹ˆ๋‹ค. ax = plt.axes(projection='3d') ax.set_xlabel('study_hours') ax.set_ylabel('private_class') ax.set_zlabel('Score') ax.dist = 11 ax.scatter(x1, x2, y) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="E0txi511ETsq" executionInfo={"status": "ok", "timestamp": 1620025906487, "user_tz": -540, "elapsed": 607, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="b6b3cfca-e895-4d0b-f5b6-7fba6d279898" x1_data = np.array(x1) x2_data = np.array(x2) y_data = np.array(y) # ๊ธฐ์šธ๊ธฐ a์™€ ์ ˆํŽธ b์˜ ๊ฐ’์„ ์ดˆ๊ธฐํ™” ํ•ฉ๋‹ˆ๋‹ค. a1 = 0 a2 = 0 b = 0 #ํ•™์Šต๋ฅ ์„ ์ •ํ•ฉ๋‹ˆ๋‹ค. lr = 0.02 #๋ช‡ ๋ฒˆ ๋ฐ˜๋ณต๋ ์ง€๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.(0๋ถ€ํ„ฐ ์„ธ๋ฏ€๋กœ ์›ํ•˜๋Š” ๋ฐ˜๋ณต ํšŸ์ˆ˜์— +1์„ ํ•ด ์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.) epochs = 3001 #๊ฒฝ์‚ฌ ํ•˜๊ฐ•๋ฒ•์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. for i in range(epochs): # epoch ์ˆ˜ ๋งŒํผ ๋ฐ˜๋ณต y_pred = a1 * x1_data + a2 * x2_data + b #y๋ฅผ ๊ตฌํ•˜๋Š” ์‹์„ ์„ธ์›๋‹ˆ๋‹ค error = y_data - y_pred #์˜ค์ฐจ๋ฅผ ๊ตฌํ•˜๋Š” ์‹์ž…๋‹ˆ๋‹ค. a1_diff = -(2/len(x1_data)) * sum(x1_data * (error)) # ์˜ค์ฐจํ•จ์ˆ˜๋ฅผ a1๋กœ ๋ฏธ๋ถ„ํ•œ ๊ฐ’์ž…๋‹ˆ๋‹ค. a2_diff = -(2/len(x2_data)) * sum(x2_data * (error)) # ์˜ค์ฐจํ•จ์ˆ˜๋ฅผ a2๋กœ ๋ฏธ๋ถ„ํ•œ ๊ฐ’์ž…๋‹ˆ๋‹ค. b_new = -(2/len(x1_data)) * sum(y_data - y_pred) # ์˜ค์ฐจํ•จ์ˆ˜๋ฅผ b๋กœ ๋ฏธ๋ถ„ํ•œ ๊ฐ’์ž…๋‹ˆ๋‹ค. a1 = a1 - lr * a1_diff # ํ•™์Šต๋ฅ ์„ ๊ณฑํ•ด ๊ธฐ์กด์˜ a1๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค. a2 = a2 - lr * a2_diff # ํ•™์Šต๋ฅ ์„ ๊ณฑํ•ด ๊ธฐ์กด์˜ a2๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค. b = b - lr * b_new # ํ•™์Šต๋ฅ ์„ ๊ณฑํ•ด ๊ธฐ์กด์˜ b๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค. if i % 100 == 0: # 100๋ฒˆ ๋ฐ˜๋ณต๋  ๋•Œ๋งˆ๋‹ค ํ˜„์žฌ์˜ a1, a2, b๊ฐ’์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. print("epoch=%.f, ๊ธฐ์šธ๊ธฐ1=%.04f, ๊ธฐ์šธ๊ธฐ2=%.04f, ์ ˆํŽธ=%.04f" % (i, a1, a2, b)) # + id="HbE2o6h5EZKx" import statsmodels.api as statm import statsmodels.formula.api as statfa #from matplotlib.pyplot import figure X = [i[0:2] for i in data] y = [i[2] for i in data] X_1=statm.add_constant(X) results=statm.OLS(y,X_1).fit() hour_class=pd.DataFrame(X,columns=['study_hours','private_class']) hour_class['Score']=pd.Series(y) model = statfa.ols(formula='Score ~ study_hours + private_class', data=hour_class) results_formula = model.fit() a, b = np.meshgrid(np.linspace(hour_class.study_hours.min(),hour_class.study_hours.max(),100), np.linspace(hour_class.private_class.min(),hour_class.private_class.max(),100)) X_ax = pd.DataFrame({'study_hours': a.ravel(), 'private_class': b.ravel()}) fittedY=results_formula.predict(exog=X_ax) fig = plt.figure() graph = fig.add_subplot(111, projection='3d') graph.scatter(hour_class['study_hours'],hour_class['private_class'],hour_class['Score'], c='blue',marker='o', alpha=1) graph.plot_surface(a,b,fittedY.values.reshape(a.shape), rstride=1, cstride=1, color='none', alpha=0.4) graph.set_xlabel('study hours') graph.set_ylabel('private class') graph.set_zlabel('Score') graph.dist = 11 plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="R_TFZck4EmTg" executionInfo={"status": "ok", "timestamp": 1620026196815, "user_tz": -540, "elapsed": 620, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="69e2e465-8d4d-4e7a-d411-f3bd42e73f8e" import numpy as np import pandas as pd import matplotlib.pyplot as plt #๊ณต๋ถ€์‹œ๊ฐ„ X์™€ ์„ฑ์  Y์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. data = [[2, 0], [4, 0], [6, 0], [8, 1], [10, 1], [12, 1], [14, 1]] x_data = [i[0] for i in data] y_data = [i[1] for i in data] #๊ทธ๋ž˜ํ”„๋กœ ๋‚˜ํƒ€๋‚ด ๋ด…๋‹ˆ๋‹ค. plt.scatter(x_data, y_data) plt.xlim(0, 15) plt.ylim(-.1, 1.1) # + id="59bA0i91FnYt" a = 0 b = 0 #ํ•™์Šต๋ฅ ์„ ์ •ํ•ฉ๋‹ˆ๋‹ค. lr = 0.05 #์‹œ๊ทธ๋ชจ์ด๋“œ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. def sigmoid(x): return 1 / (1 + np.e ** (-x)) # + colab={"base_uri": "https://localhost:8080/"} id="KrekafceFp_L" executionInfo={"status": "ok", "timestamp": 1620026519524, "user_tz": -540, "elapsed": 548, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="21721d7d-01c4-4381-85b4-36e069c50342" for i in range(3001): for x_data, y_data in data: a_diff = x_data*(sigmoid(a*x_data + b) - y_data) b_diff = sigmoid(a*x_data + b) - y_data a = a - lr * a_diff b = b - lr * b_diff if i % 100 == 0: print("epoch=%.f, ๊ธฐ์šธ๊ธฐ=%.04f, ์ ˆํŽธ=%.04f" % (i, a, b)) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="7XXkIMrnGu2O" executionInfo={"status": "ok", "timestamp": 1620026558233, "user_tz": -540, "elapsed": 582, "user": {"displayName": "\ubc15\ud76c\uc6a9", "photoUrl": "", "userId": "04667452191491854015"}} outputId="3a02ece2-7797-4eb8-e954-b40674e37fa7" plt.scatter(x_data, y_data) plt.xlim(0, 15) plt.ylim(-.1, 1.1) x_range = (np.arange(0, 15, 0.1)) #๊ทธ๋ž˜ํ”„๋กœ ๋‚˜ํƒ€๋‚ผ x๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ์ •ํ•ฉ๋‹ˆ๋‹ค. plt.plot(np.arange(0, 15, 0.1), np.array([sigmoid(a*x + b) for x in x_range])) plt.show() # + id="dRroqrXoG4Ss"
01_My_First_Deeplearning.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="zX4Kg8DUTKWO" #@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. # + id="s6eq-RBcQ_Zr" try: # # %tensorflow_version only exists in Colab. # %tensorflow_version 2.x except Exception: pass # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="BOjujz601HcS" outputId="7b7940f7-fcb2-4b94-c890-2032c6f512a3" import tensorflow as tf import numpy as np import matplotlib.pyplot as plt print(tf.__version__) # + colab={"base_uri": "https://localhost:8080/", "height": 199} id="asEdslR_05O_" outputId="81efffa7-44af-4725-d004-60e3e1db5385" dataset = tf.data.Dataset.range(10) for val in dataset: print(val.numpy()) # + colab={"base_uri": "https://localhost:8080/", "height": 199} id="Lrv_ghSt1lgQ" outputId="0946edc3-e2c8-4ee0-99f8-aff8f67a7450" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1) for window_dataset in dataset: for val in window_dataset: print(val.numpy(), end=" ") print() # + colab={"base_uri": "https://localhost:8080/", "height": 126} id="QLEq6MG-2DN2" outputId="cca1057a-dc98-4b3a-bf92-dde4ee61b1ef" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1, drop_remainder=True) for window_dataset in dataset: for val in window_dataset: print(val.numpy(), end=" ") print() # + colab={"base_uri": "https://localhost:8080/", "height": 126} id="PJ9CAHlJ2ODe" outputId="a1383f54-9ee2-4a33-cbf5-fb9143c64014" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(5)) for window in dataset: print(window.numpy()) # + colab={"base_uri": "https://localhost:8080/", "height": 126} id="DryEZ2Mz2nNV" outputId="cd301fcb-781e-441f-9495-4b709878dfc6" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(5)) dataset = dataset.map(lambda window: (window[:-1], window[-1:])) for x,y in dataset: print(x.numpy(), y.numpy()) # + colab={"base_uri": "https://localhost:8080/", "height": 126} id="1tl-0BOKkEtk" outputId="082d2e6e-2237-4da0-b8a7-656213d17c7c" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(5)) dataset = dataset.map(lambda window: (window[:-1], window[-1:])) dataset = dataset.shuffle(buffer_size=10) for x,y in dataset: print(x.numpy(), y.numpy()) # + colab={"base_uri": "https://localhost:8080/", "height": 235} id="Wa0PNwxMGapy" outputId="32b7c5e3-4d53-4f88-89cc-9baf84cf7861" dataset = tf.data.Dataset.range(10) dataset = dataset.window(5, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(5)) dataset = dataset.map(lambda window: (window[:-1], window[-1:])) dataset = dataset.shuffle(buffer_size=10) dataset = dataset.batch(2).prefetch(1) for x,y in dataset: print("x = ", x.numpy()) print("y = ", y.numpy())
Curso Tensorflow/Curso4-TimeSeries/semana2/S+P_Week_2_Lesson_1.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 # --- # # MISSION TO MARS - SCRAPING # ### Import Dependencies # + tags=[] from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup as bs import requests import pymongo import time import pandas as pd import numpy as np # - # Setup splinter executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable_path, headless=False) # + [markdown] tags=[] # ## NASA Mars News # - url = 'https://redplanetscience.com/' browser.visit(url) html = browser.html soup = bs(html, 'html.parser') list_text = soup.find_all('div', class_='list_text') # + tags=[] list_text # - content_title = list_text[0].find('div', class_ = 'content_title') news_title = content_title.text.strip() news_title article_teaser_body = list_text[0].find('div', class_ = 'article_teaser_body') news_p = article_teaser_body.text.strip() news_p # + [markdown] tags=[] # ## JPL Mars Space Images # - url = 'https://spaceimages-mars.com/' browser.visit(url) html = browser.html soup = bs(html, 'html.parser') # + tags=[] header = soup.find_all('div', class_='header') header # - featured_image_url = url + soup.find('img', class_='headerimage fade-in')['src'] featured_image_url # + [markdown] tags=[] # ## Mars Facts # + tags=[] url = 'https://galaxyfacts-mars.com/' browser.visit(url) # + # html = browser.html # soup = bs(html, 'html.parser') # facepalmed when I went back to review Pandas scraping and realized I didnt need BSoup # + tags=[] mars_facts = pd.read_html(url) # - mars_facts mars_facts = mars_facts[0] mars_facts.columns = ['Comparison', 'Mars', 'Earth'] mars_facts = mars_facts.drop(index=0) mars_facts.set_index('Comparison', inplace=True) mars_facts mars_facts.to_html() # ## <NAME> url = 'https://marshemispheres.com/' browser.visit(url) html = browser.html soup = bs(html, 'html.parser') # + sidebar = soup.find('div', class_='collapsible') categories = sidebar.find_all('h3') # - categories # + hemisphere_img_urls = [] for item in range(len(categories)): hemisphere = {} browser.find_by_css("a.product-item h3")[item].click() sample_img = browser.links.find_by_text("Sample").first hemisphere["title"] = browser.find_by_css("h2.title").text hemisphere["img_url"] = sample_img["href"] hemisphere_img_urls.append(hemisphere) browser.back() # + tags=[] hemisphere_img_urls # - browser.quit()
Mission_to_Mars/mission_to_mars.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/annissatessffaaye/QA-Data-Engineering-Bootcamp-Azure-Python-SQL/blob/main/Normalization.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="uHSbkkeH-DVZ" # Statistical Formulae # Problem: # In any dataset-> values can be on different scales and units # Name. Age. MoneyEarned BankBalance Married Happy # ABC. number. number. number. boolean. boolean # ML-> to either classify-> Married, Happy #. regression -> Age, Money, BankBal.... # Let's assume-> Happiness (T/F) # Happiness = f(Name, Age, MoneyEarned, BankBal, Married) # how to find whether it should a function or not-> Independence, Correlation # Name-> string # Age-> 0 to 200 # Money-> 0 to GBP 1 Trillion # BankBal-> - 1 Trillion to 1 Trillion # Happiness = w1*Name + w2*Age + w3*ME + w4*BB + w5*married + bias # all w and b-> variables, everything else (Name...Age..-> Constants) # ML-> graph-> we will try to fit these equations -> weights and bias are components # along my x,y,z.... axis # deep learning-> Integration -> we assume values for W,b; differentiation-> reduce values # by a very tiny fraction # + id="gZaByVGAATI2" # d/f b/w the ranges of Age, Money and BankBal will ensure # that Money and BankBal will always dominate the equation! # why-> because they are very large numbers! # wx*billion_dollars + wy*millions_bank + wz*42 # we want to avoid EXTREMELY LARGE or EXTREMELY SMALL VARIABLES! # everything-> in the same scale! # + id="b4SxhPLGBJ8V" # NORMALIZATION-> bringing your data to same scale (No large or no TINY values) # our options: # Type Scale # MinMax from 0 to 1 # we assume smallest value to be 0, largest to be 1, and all values are scaled b/w #. example-> wherever negative numbers may not make sense-> Pixels, # colors, images, videos # tanh-> -1 to 1 # TanH (sine=P/H, cosine=B/H)-> tangent -> sine and 90 degree delay-> cosine # tangent-> wave-> tangent-> Direction of the wave-> (y2-y1)/(x2-x1)-> slope # slope-> is calculate on small data (linear or homogeneous) # tangent is calulcated on big shapes (heterogeneous) # Z-Score (Standard Scaler) -inf to +inf # Make the average 0, and scale everything else as a RATIO instead of original #. number #. from -inf to +inf -> we remove everything that is more than 3 times of #. STANDARD DEVIATION!! #. Since Z-Score gives you ratios-> outliers can be removed by just removing #. all values > +3, < -3 # + id="1sJpv56yCulU" # Strings: use them for filtering-> One-Hot Encoding # : use them as input variables-> Label Encoding (convert strings to numbers) # + id="QLAexn36C5aF" # Sales. ItemsSold. Location. If_to_fund_company #. 100. 10. London. False #. 1000. 900. London. False # 100. 5. York True #. 90 1 MiddleEarth. True # 1st situation where i want to build 1 ML model representing all cities: # London-> 0, York-> 1 and ME-> 2 # w1*Sales + w2*IS + w3*Location # does this mean-> w3*0 for London, w3 for ME is twice as large # as York? # + id="U5k-UnZgDsaP" # One-Hot ENcoding #String Data (few elements- discrete values) # we convert these discrete values into independent columns # Sales. ItemsSold. loc_london. loc_york. loc_ME If_to_fund_company #. 100. 10. 1 0 0 False #. 1000. 900. 1 0 0 False # 100. 5. 0 1 0 True #. 90 1 0 0 1 True # Filter-> 3 ML models for this-> 1 for London, York and ME each # + colab={"base_uri": "https://localhost:8080/", "height": 301} id="tDmHQr4yHevl" outputId="259cb81e-9b08-45cd-eaff-86c79c8d0772" # Sigmoid-> to scale b/w 0 to 1 (Probability) # tanh-> to scale b/w -1 to 1 (Outlier managing, profit/loss) import cv2 from google.colab.patches import cv2_imshow img = cv2.imread('sigmoid tanh.jpeg') cv2_imshow(img) # + id="ynYIBTa8HuLq" # Z-Score # Making the average as 0, and scaling everything as a ratio of STANDARD_DEVIATIOn # we assume a circle with radius as Standard Deviation, and the centre as Mean # formulae: dataset_x -> z-score = (x-mean) / std # z-score = (distance from centre)/radius # anything 3 times larger than radius is assumed to be outlier! # + id="TGyRZ7MOIYn5" import pandas as pd data = pd.read_csv('https://raw.githubusercontent.com/a-forty-two/DFE3/main/data.csv', header=0) # + colab={"base_uri": "https://localhost:8080/", "height": 243} id="BhHiCELPItkl" outputId="90ff4886-f959-4855-d20e-9ccb7a6ff7e3" data.head() # + colab={"base_uri": "https://localhost:8080/", "height": 337} id="BB_yz36YIvNM" outputId="465e6a92-6966-4897-b2b4-5034ef127988" # statistics of dataset data.describe() # STD and MEAN can be easily extracted from this dataset! # + id="PUM99vlJI0J4" stats = data.describe().T mu = stats['mean'] sigma = stats['std'] # calculated mean and standard_deviation for every column # + id="NkICs7MTJIMn" # Z-score--> x-mean/std dataset_norm = (data-mu)/sigma # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="ocgjNmdKJJBo" outputId="3e883e90-20d2-4831-b951-e7730169925e" dataset_norm.head(10) # + id="j_if9AFFJYd7" import numpy as np mydataset = np.array([1,4,6,42,1042,99,24, 101]) minv = mydataset.min() maxv = mydataset.max() norm_dataset = (mydataset - minv)/(maxv-minv) # formulae-> dataset x -> minmax -> (x-min)/(max-min) # + colab={"base_uri": "https://localhost:8080/"} id="0zvibLtKKSGP" outputId="e67e96d6-9803-4f32-d5c1-cd26708ef658" norm_dataset # + id="jmbm4_a2KVQJ" # Label Encoding # converting words to numbers # dictionary mydictionary = { 'M': 1, 'B': 0} mytfx = lambda val: mydictionary[val] # + id="hUEG9bDtLisE" data['encoded_diagnosis'] = data['diagnosis'].map(mytfx) # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="m9SfFi-FLJ4i" outputId="99522ef5-116c-42a5-d008-d8dc5acad588" data.tail(10) # + colab={"base_uri": "https://localhost:8080/"} id="DYz2CgUqLKpJ" outputId="ba3d7cf0-7220-46f1-9fb1-26a737093daf" data2 # + id="AKl1rtX0Lr3U" # one hot encoding mydictionary1 = { 'M': 1, 'B': 0} mytfx1 = lambda val: mydictionary1[val] mydictionary2 = { 'M': 0, 'B': 1} mytfx2 = lambda val: mydictionary2[val] # + id="QBCg7XtFMyV2" data['diagnosis_M'] = data['diagnosis'].map(mytfx1) data['diagnosis_B'] = data['diagnosis'].map(mytfx2) # + colab={"base_uri": "https://localhost:8080/", "height": 400} id="yYnz0xgPM8JO" outputId="acb4562f-faa4-424c-c212-681153c87a4c" data.tail(10) #One-Hot Encoding-> you now have 2 new columns in the end! # + colab={"base_uri": "https://localhost:8080/", "height": 417} id="v3sp9jCOM9f2" outputId="03cb7725-38ca-4f92-fdb3-d5006de75370" # One-hot encoding is used as a filter-> to select only Malignant rows! data_m = data[data['diagnosis_M'] == 1] print(len(data_m)) data_m.tail(10) # + id="I72vAdKMNZ9k"
Normalization.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 from IPython.display import display # getting functions from helper file import sim_frbs import path_help # - # ### Query # # wget --http-user=vravi --http-passwd=<PASSWORD> --cookies=on --keep-session-cookies --save-cookies=cookie.txt --load-cookies=cookie.txt -O BC03_001_short.csv "http://gavo.mpa-garching.mpg.de/MyMillennium?action=doQuery&SQL= select c.ra, c.dec, c.Rc, c.diskSize, c.ang_dist, g.redshift, g.cosInclination, g.sfr, g.stellarMass, g.diskMass, g.stellarDiskRadius from Henriques2015a.cones.MRscPlanck1_BC03_001 c, Henriques2015a..MRscPlanck1 g where g.galaxyId = c.galaxyId and c.Rc < 40 " # ## Importing and checking catalog # Bruzual&Charlot2003 stellar populations 001 cat = pd.read_csv('BC03_001_short.csv', skiprows=17, skipfooter=1, engine='python') # making the central ra to 1 cat.loc[cat[cat['ra']<2].index, 'ra'] += 1 cat.loc[cat[cat['ra']>350].index, 'ra'] -= 359 # adjusting stellar mass units cat.stellarMass = cat.stellarMass / 10**10 * 69 # cat # plotting sample of 1000 galaxies and their magnitudes ra = cat.ra.sample(n=1000, random_state=122).values dec = cat.dec.sample(n=1000, random_state=122).values plt.figure(figsize=(6, 5)) plt.scatter(ra, dec, c=cat.Rc.sample(n=1000, random_state=122)) plt.set_cmap(plt.cm.Blues) plt.colorbar() plt.xlabel('ra') plt.ylabel('dec'); #plt.scatter(frbs.ra, frbs.dec, c='tab:orange', s=5); # x vs y plot for different catalog variables xarr = 'sfr' yarr = 'diskSize' x = cat[xarr].sample(n=10000, random_state=122).values y = cat[yarr].sample(n=10000, random_state=122).values plt.scatter(x, y*(1+y)**2, s=2) plt.yscale('log') plt.xscale('log') plt.xlabel(xarr) plt.ylabel(yarr); # + # plotting histograms for different catalog variables plt.subplots(2, 2, figsize=(10, 10)) plt.subplot(2,2,1) plt.hist(cat.Rc, 100) plt.xlabel('$m_r\:(AB)$') plt.ylabel('Count') plt.subplot(2,2,2) plt.hist(cat.diskSize, np.linspace(0, 2, 100)) plt.xlabel('$\phi\:(arcsec)$') plt.ylabel('Count') plt.subplot(2,2,3) plt.hist(cat.redshift, 50) plt.xlabel('Redshift') plt.ylabel('Count') plt.subplot(2,2,4) plt.hist(cat.sfr, 100)#, np.linspace(0, 2, 100)) plt.xlabel('SFR ($M_{sun}/yr$)') plt.ylabel('Count'); # - # ## Simulating FRBs # + # %%time # can set conditions on catalog to search through here #galaxies = cat[np.logical_and(cat.Rc < 23, cat.Rc>20)] frbs = sim_frbs.sim_frbs(cat, 1000, 1, ('sfr'), (5., None)) frb_gals = cat.loc[frbs.gal_Index.values] frbs # - # ## Running PATH + analysis # %%time stats = path_help.multiple_path(frbs, (0.0, 'sfr'), (6., 'exp'), search_rad=7, gal_cat=cat, save=None) stats #stats = import_stats('new_dists_10000') path_help.analyze(stats); stats = path_help.single_path(frbs.iloc[0], (0., 'sfr'), (6., 'exp'), search_rad=7, plot=True, gal_cat=cat)
path_sims_example.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 # --- # # Image classification using MLP # # 1. Imports the Keras library # 2. Imports a Flatten layer to convert the image matrix into a vector # 3. Defines the neural network architecture # 4. Adds the Flatten layer # 5. Adds 2 hidden layers with 512 nodes each. Using the ReLU activation function is recommended in hidden layers. # 6. Adds 1 output Dense layer with nodes. Using the softmax activation function is recommended in the output layer for multiclass classification problems. from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense # + model = Sequential() model.add(Flatten(input_shape = (28,28))) model.add(Dense(512, activation = 'relu')) model.add(Dense(512, activation = 'relu')) model.add(Dense(10, activation = 'softmax')) model.summary() # -
ComputerVision/03_convolutional_nerual_networks.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 # --- # # Lecture 3.1: Clustering # # [**Lecture Slides**](https://docs.google.com/presentation/d/19huVbcPfj-okCOjXIMG34cuQdZZP1ktswuMFjbT66ZA/edit?usp=sharing) # # This lecture, we are going to cluster a geospatial dataset using k-Means. # # **Learning goals:** # # - Explore data using clustering # - Implement k-means # - Visualize geospatial data # - Create a ridgeline graph # # # We are tasked with gathering insights into to a volcano dataset ๐ŸŒ‹, but we know nothing about geology ๐Ÿ™ˆ. No need to panic! We know machine learning algorithms that can help us explore the patterns in this data. # # # ## 1. Geospatial Data # # Let's start our volcanic exploration by loading the dataset into pandas: # # + import pandas as pd volcanos = pd.read_csv('volcanos.csv') volcanos.head() # - # There are a lot of columns, but the most interesting are `Latitude` and `Longitude`. These are geospatial coordinates, which means it's our first opportunity to visualize some awesome maps! There are many geospatial data visualization libraries in python, but for this notebook we'll use [folium](https://python-visualization.github.io/folium/). # # Let's focus on the coordinates by selecting the two geospatial columns from our `DataFrame`: coords = volcanos[['Latitude', 'Longitude']] # We now have to initialize a [`folium.Map`](https://python-visualization.github.io/folium/modules.html#folium.folium.Map). This is done with one central location. Since our coordinates span the entire globe, this doesn't matter, and we can pick our first volcano as center: import folium m = folium.Map(location=coords.iloc[0], tiles='Stamen Toner', zoom_start=1) type(m) m # We have a map! ๐Ÿ—บ Notice how you can move and zoom interactively. Let's populate this map with our volcanos! We'll iterate through the `DataFrame` rows using [`.iterrows()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html). Then, we can create a [`Circle`](https://python-visualization.github.io/folium/modules.html#folium.vector_layers.Circle) for each volcano location. These have to be explicitly added to the map with `.add_to(m)`: # + for index, row in coords.iterrows(): folium.Circle( radius=10, location=row, color='crimson', fill=True, ).add_to(m) m # - # This is already much easier to understand than our tabular format! Notice how volcanos aren't spread around the globe, but instead form "clumps" and "lines". We'd like to investigate this further, but we don't have a column which categorizes the data into these groups... # # ## 2. K-Means # # So we're going to have to make them ourselves! This is a clustering task, for which we will use the k-Means implementation from the [sklearn](https://scikit-learn.org/) library. Remember that k-Means is a _learning_ algorithm, so there will be two steps: fitting the data, then applying the model on the data. # # First let's train our k-Means model. It looks like there is a dozen "clumps" on the map, so we'll pick a somewhat arbitrary $k=10$. Then, we'll convert our `DataFrame` to a NumPy `ndarray` using the [`.to_numpy()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html) method, and fit the model to the data: # + from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=10) kmeans.fit(coords.to_numpy()) # - # Our model is trained, and ready to be used! Next, we "predict" the cluster allocation of points by feeding our `DataFrame` back into the `kmeans` model. # # โ„น๏ธ This step might sound redundant, but it is important to differentiate between _training data_ and _prediction data_. In our case, they are the same, but they don't have to be! For example, if we were aliens and our dataset contained _billions_ of volcanoes, it could be more efficient to choose a random subset of the data to train the k-Means model. y_kmeans = kmeans.predict(coords) y_kmeans # The [`.predict()`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans.predict) method returned a vector of integers. These are the _cluster allocations_ of our volcanos. Each cluster is labeled by an integer , and each volcano is assigned a cluster. This vector stores these assignments. # # This allows us to visualize the clusters on our map! We use a trick to iterate through the `coords.iterrows()` and the `y_kmeans` at the same time: the python builtin function, [`zip()`](https://docs.python.org/3.3/library/functions.html#zip): # + import seaborn as sns colors = sns.color_palette('husl', n_colors=10).as_hex() m = folium.Map(location=coords.iloc[0], tiles='Stamen Toner', zoom_start=1) for (index, row), y in zip(coords.iterrows(), y_kmeans): folium.Circle( radius=10, location=row, color=colors[y], fill=True, ).add_to(m) m # - # That's a lava hot visualization ๐Ÿ”ฅNotice how k-Means identified real underlying patterns in the data, and forms geospatially coherent groups. # # ## 3. Cluster Analysis # # The clusters _look_ good, but let's see if they can be useful in our data exploration. First, let's append our cluster allocation data to our `DataFrame` as a new column: volcanos.loc[:, 'Cluster'] = y_kmeans.copy() volcanos.head() # Manipulating one object will be easier than two! Let's investigate distributional differences between the clusters (see lecture 2.3): volcanos.groupby('Cluster').mean() # Interestingly, the clusters have different `Evelation` averages. This suggests that by identifying volcanos that were close to eachother, k-Means also grouped the data by other criteria of similarity. In lecture 2.6, we learned how averages can be misleading, and that it's preferential to visualise entire _distributions_ of datasets. Let's do this with a [ridgeline plot](https://www.data-to-viz.com/graph/ridgeline.html): # + import matplotlib.pyplot as plt sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)}) df = volcanos[["Elevation (Meters)", 'Cluster']] # Initialize the FacetGrid object pal = sns.cubehelix_palette(15, rot=-.25, light=.7) g = sns.FacetGrid(df, row="Cluster", hue="Cluster", aspect=10, height=.5, palette=pal) # Draw the densities in a few steps g.map(sns.kdeplot, "Elevation (Meters)", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2) g.map(sns.kdeplot, "Elevation (Meters)", clip_on=False, color="w", lw=2, bw=.2) g.map(plt.axhline, y=0, lw=2, clip_on=False) # Define and use a simple function to label the plot in axes coordinates def label(x, color, label): ax = plt.gca() ax.text(0, .2, label, fontweight="bold", color=color, ha="left", va="center", transform=ax.transAxes) g.map(label, "Elevation (Meters)") # Set the subplots to overlap g.fig.subplots_adjust(hspace=-.25) # Remove axes details that don't play well with overlap g.set_titles("") g.set(yticks=[]) g.despine(bottom=True, left=True) # - # This is an example of a more "advanced" [seaborn](https://seaborn.pydata.org/) plot that can be both aesthetic and informative! # # # ## Summary # # Today was our introduction to **data analysis**. We learned how **machine learning algorithms** differ from rule-based algorithms, and how they fall into either **supervised learning** and **unsupervised learning**. Then, we explained what **clustering** is, and identified some of its major **applications**. We defined the most popular clustering method: **k-Means**, and visualized the **Expectation-Maximization** optimisation algorithm before giving it a try ourselves. It allowed us to infer structures in a **geospatial** dataset, which gave insights into the distributions of volcanos across the Globe. # # # # # Resources # # # ### Core Resources # # - [**Slides**](https://docs.google.com/presentation/d/19huVbcPfj-okCOjXIMG34cuQdZZP1ktswuMFjbT66ZA/edit?usp=sharing) # - [Python Data Science Handbook - k-Means](https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html) # - [k-Means applications and drawbacks](https://towardsdatascience.com/k-means-clustering-algorithm-applications-evaluation-methods-and-drawbacks-aa03e644b48a) # Excellent blog to further your k-Means skills with silhouette analysis and the elbow method # # ### Additional Resources # # - [k-Means clustering from the mathematicalmonk](https://youtu.be/0MQEt10e4NM) # Detailed but intuitive theoretical explanation of k-Means
data_analysis/3.1_introduction_to_machine_learning_and_clustering/clustering.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 numpy as np import pandas as pd import seaborn as sbn import matplotlib.pyplot as plt df=pd.read_csv('Mall_Customers.csv') df.describe() df.isnull().sum().sum() sbn.heatmap(df.isnull(),yticklabels=False,cmap='rainbow') # <h3> Removing Warning import warnings warnings.filterwarnings('ignore') # + plt.subplot(1,2,1) sbn.set(style='whitegrid') sbn.distplot(df['Annual Income (k$)']) plt.title('Distribution of annual income') plt.xlabel('Annual income') plt.ylabel('Count') plt.subplot(1,2,2) sbn.set(style='whitegrid') sbn.distplot(df['Age']) plt.xlabel('Age') plt.ylabel('Count') plt.show() # - labels=['Female', 'Male'] size=df['Gender'].value_counts() colors=['olive','lightgreen'] explode=[0,0.1] plt.figure(figsize=(9,10)) plt.pie(x=size,colors=colors,labels=labels,explode=explode,autopct='%0.2f%%') plt.title('Gender') plt.legend() plt.show() plt.figure(figsize=(15,8)) sbn.countplot(df['Age'], palette='hsv') plt.title('Distribution of age') plt.show() plt.figure(figsize=(15,8)) sbn.countplot(df['Annual Income (k$)'], palette='hsv') plt.title('Distribution of Income') plt.show() plt.figure(figsize=(15,8)) sbn.countplot(df['Spending Score (1-100)'], palette='hsv') plt.title('Distribution of Income') plt.show() # <h3> Clustering x=df.iloc[:,[3,4]].values x from sklearn.cluster import KMeans wcss=[] for i in range(1,15): km=KMeans(n_clusters=i,init='k-means++',max_iter=300, n_init=10, random_state=0) km.fit(x) wcss.append(km.inertia_) plt.plot(range(1,15),wcss) plt.title('Elbow Method') plt.xlabel('Value of K') plt.ylabel('Wcss') plt.show() # + ### Kmeans Visualization # - km=KMeans(n_clusters=5,init='k-means++',max_iter=300, n_init=10, random_state=0) ymean=km.fit_predict(x) plt.scatter(x[ymean==0,0], x[ymean==0,1],s=100,c='pink',label='miser') plt.scatter(x[ymean==1,0], x[ymean==1,1],s=100,c='olive',label='general') plt.scatter(x[ymean==2,0], x[ymean==2,1],s=100,c='yellow',label='target') plt.scatter(x[ymean==3,0], x[ymean==3,1],s=100,c='lightgreen',label='spendmachine') plt.scatter(x[ymean==4,0], x[ymean==4,1],s=100,c='green',label='careful') plt.title("Kmean clustering") plt.xlabel("Annual Income") plt.ylabel("Spending Score") plt.legend() plt.grid()
K mean Clusterning/K mean Clustering.ipynb