markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Build docker containerSince we're working with a custom environment with custom dependencies, we create our own container for training. We:1. Fetch the base MXNet and Coach container image,2. Install EnergyPlus and its dependencies on top,3. Upload the new container image to AWS ECR. | cpu_or_gpu = 'gpu' if instance_type.startswith('ml.p') else 'cpu'
repository_short_name = "sagemaker-hvac-coach-%s" % cpu_or_gpu
docker_build_args = {
'CPU_OR_GPU': cpu_or_gpu,
'AWS_REGION': boto3.Session().region_name,
}
custom_image_name = build_and_push_docker_image(repository_short_name, build_args=docker_... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Setup the environmentThe environment is defined in a Python file called `data_center_env.py` and for SageMaker training jobs, the file will be uploaded inside the `/src` directory.The environment implements the init(), step() and reset() functions that describe how the environment behaves. This is consistent with Open... | !pygmentize src/preset-energy-plus-clipped-ppo.py | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Write the Training Code The training code is written in the file “train-coach.py” which is uploaded in the /src directory. First import the environment files and the preset files, and then define the main() function. | !pygmentize src/train-coach.py | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Train the RL model using the Python SDK Script modeIf you are using local mode, the training will run on the notebook instance. When using SageMaker for training, you can select a GPU or CPU instance. The RLEstimator is used for training RL jobs. 1. Specify the source directory where the environment, presets and train... | %%time
estimator = RLEstimator(entry_point="train-coach.py",
source_dir='src',
dependencies=["common/sagemaker_rl"],
image_uri=custom_image_name,
role=role,
instance_type=instance_type,
... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Store intermediate training output and model checkpoints The output from the training job above is stored on S3. The intermediate folder contains gifs and metadata of the training. | s3_url = "s3://{}/{}".format(s3_bucket,job_name)
if local_mode:
output_tar_key = "{}/output.tar.gz".format(job_name)
else:
output_tar_key = "{}/output/output.tar.gz".format(job_name)
intermediate_folder_key = "{}/output/intermediate/".format(job_name)
output_url = "s3://{}/{}".format(s3_bucket, output_tar_key... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Visualization Plot metrics for training jobWe can pull the reward metric of the training and plot it to see the performance of the model over time. | %matplotlib inline
import pandas as pd
csv_file_name = "worker_0.simple_rl_graph.main_level.main_level.agent_0.csv"
key = os.path.join(intermediate_folder_key, csv_file_name)
wait_for_s3_object(s3_bucket, key, tmp_dir)
csv_file = "{}/{}".format(tmp_dir, csv_file_name)
df = pd.read_csv(csv_file)
df = df.dropna(subset=... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Evaluation of RL modelsWe use the last checkpointed model to run evaluation for the RL Agent. Load checkpointed modelCheckpointed data from the previously trained models will be passed on for evaluation / inference in the checkpoint channel. In local mode, we can simply use the local directory, whereas in the SageMak... | wait_for_s3_object(s3_bucket, output_tar_key, tmp_dir)
if not os.path.isfile("{}/output.tar.gz".format(tmp_dir)):
raise FileNotFoundError("File output.tar.gz not found")
os.system("tar -xvzf {}/output.tar.gz -C {}".format(tmp_dir, tmp_dir))
if local_mode:
checkpoint_dir = "{}/data/checkpoint".format(tmp_dir... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Run the evaluation stepUse the checkpointed model to run the evaluation step. | estimator_eval = RLEstimator(entry_point="evaluate-coach.py",
source_dir='src',
dependencies=["common/sagemaker_rl"],
image_uri=custom_image_name,
role=role,
instance_type=ins... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Model deployment Since we specified MXNet when configuring the RLEstimator, the MXNet deployment container will be used for hosting. | from sagemaker.mxnet.model import MXNetModel
model = MXNetModel(model_data=estimator.model_data,
entry_point='src/deploy-mxnet-coach.py',
framework_version='1.8.0',
py_version="py37",
role=role)
predictor = model.deploy(initial_instance_count=1,
... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
We can test the endpoint with a samples observation, where the current room temperature is high. Since the environment vector was of the form `[outdoor_temperature, outdoor_humidity, indoor_humidity]` and we used observation normalization in our preset, we choose an observation of `[0, 0, 2]`. Since we're deploying a P... | action, action_mean, action_std = predictor.predict(np.array([0., 0., 2.,]))
action_mean | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
We can see heating and cooling setpoints are returned from the model, and these can be used to control the HVAC system for efficient energy usage. More training iterations will help improve the model further. Clean up endpoint | predictor.delete_endpoint() | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Pendulum Data | full_df = pd.DataFrame()
cols = ['Trial', "tr_mse", 'te_mse']
fname = "./saved-outputs/log_mixedemlp_basic1e-05_equiv1e-05.pkl"
rpp_df = pd.read_pickle(fname)
rpp_df.columns = cols
rpp_df['type'] = 'RPP'
full_df = pd.concat((full_df, rpp_df))
fname = "./saved-outputs/log_mlp_basic0.01_equiv0.0001.pkl"
mlp_df = pd.re... | _____no_output_____ | BSD-2-Clause | experiments/misspec-symmetry/plotter.ipynb | mfinzi/residual-pathway-priors |
Music Generation Using Deep Learning Real World ProblemThis case-study focuses on generating music automatically using Recurrent Neural Network(RNN). We do not necessarily have to be a music expert in order to generate music. Even a non expert can generate a decent quality music using RNN.We all like to listen intere... | import os
import json
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dropout, TimeDistributed, Dense, Activation, Embedding
data_directory = "../Data/"
data_file = "Data_Tunes.txt"
charIndex_json = "char_to_index.json"
model_weights_directory = '../Data/Model_W... | _____no_output_____ | MIT | LSTM/Music_Generation_Train1.ipynb | AbhilashPal/MuseNet |
Make sure the number of minority class (lbl==1) is smaller than number of majority class (lbl==-1) | sum(df.lbl)
len(df)
df.to_csv('test_men_binary.csv',header=None, sep=',', index=None) | _____no_output_____ | BSD-2-Clause | src/datasets/ConvertMultipleClasses2BinaryClasses.ipynb | robertu94/mlsvm |
Dask jobqueue example for NEC Linux clustercovers the following aspects, i.e. how to* load project and machine specific Dask jobqueue configurations* open, scale and close a default jobqueue cluster* do an example calculation on larger than memory data Load jobqueue configuration defaults | import os
os.environ['DASK_CONFIG']='.' # use local directory to look up Dask configurations
import dask.config
dask.config.get('jobqueue') # prints available jobqueue configurations | _____no_output_____ | MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
Set up jobqueue cluster ... | import dask_jobqueue
default_cluster = dask_jobqueue.PBSCluster(config_name='nesh-jobqueue-config')
print(default_cluster.job_script()) | #!/bin/bash
#PBS -N dask-worker
#PBS -q clmedium
#PBS -l elapstim_req=00:45:00,cpunum_job=4,memsz_job=24gb
#PBS -o dask_jobqueue_logs/dask-worker.o%s
#PBS -e dask_jobqueue_logs/dask-worker.e%s
JOB_ID=${PBS_JOBID%%.*}
/sfs/fs6/home-geomar/smomw260/miniconda3/envs/dask-minimal-20191218/bin/python -m distributed.cli.das... | MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
... and the client process | import dask.distributed as dask_distributed
default_cluster_client = dask_distributed.Client(default_cluster) | _____no_output_____ | MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
Start jobqueue workers | default_cluster.scale(jobs=2)
!qstat
default_cluster_client | _____no_output_____ | MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
Do calculation on larger than memory data | import dask.array as da
fake_data = da.random.uniform(0, 1, size=(365, 1e4, 1e4), chunks=(365,500,500)) # problem specific chunking
fake_data
import time
start_time = time.time()
fake_data.mean(axis=0).compute()
elapsed = time.time() - start_time
print('elapse time ',elapsed,' in seconds') | elapse time 46.89112448692322 in seconds
| MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
Close jobqueue cluster and client process | !qstat
default_cluster.close()
default_cluster_client.close()
!qstat | _____no_output_____ | MIT | nesh/01_default_cluster_example.ipynb | ExaESM-WP4/Dask-jobqueue-configs |
 _*Qiskit Aqua: Experimenting with Max-Cut problem and Traveling Salesman problem with variational quantum eigensolver*_ The latest version of this notebook is available on https://github.com/Qiskit/qiskit-tutorial.*** ContributorsAntonio Mezzacapo[1], Jay Gambetta[1],... | # useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.optimization.ising import max_cut, tsp
from qiskit.aqua.algorithms impor... | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
[Optional] Setup token to run the experiment on a real deviceIf you would like to run the experiment on a real device, you need to setup your account first.Note: If you do not store your token yet, use `IBMQ.save_account('MY_API_TOKEN')` to store it first. | from qiskit import IBMQ
# provider = IBMQ.load_account() | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Max-Cut problem | # Generating a graph of 4 nodes
n=4 # Number of nodes in graph
G=nx.Graph()
G.add_nodes_from(np.arange(0,n,1))
elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
defa... | [[0. 1. 1. 1.]
[1. 0. 1. 0.]
[1. 1. 0. 1.]
[1. 0. 1. 0.]]
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Brute force approachTry all possible $2^n$ combinations. For $n = 4$, as in this example, one deals with only 16 combinations, but for n = 1000, one has 1.071509e+30 combinations, which is impractical to deal with by using a brute force approach. | best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i,j]*x[i]*(1-x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print('case = '... | case = [0, 0, 0, 0] cost = 0.0
case = [1, 0, 0, 0] cost = 3.0
case = [0, 1, 0, 0] cost = 2.0
case = [1, 1, 0, 0] cost = 3.0
case = [0, 0, 1, 0] cost = 3.0
case = [1, 0, 1, 0] cost = 4.0
case = [0, 1, 1, 0] cost = 3.0
case = [1, 1, 1, 0] cost = 2.0
case = [0, 0, 0, 1] cost = 2.0
case = [1, 0, 0, 1] cost = 3.0
case = [0,... | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Mapping to the Ising problem | qubitOp, offset = max_cut.get_operator(w) | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
[Optional] Using DOcplex for mapping to the Ising problemUsing ```docplex.get_qubitops``` is a different way to create an Ising Hamiltonian of Max-Cut. ```docplex.get_qubitops``` can create a corresponding Ising Hamiltonian from an optimization model of Max-Cut. An example of using ```docplex.get_qubitops``` is as bel... | from docplex.mp.model import Model
from qiskit.optimization.ising import docplex
# Create an instance of a model and variables.
mdl = Model(name='max_cut')
x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
# Object function
max_cut_func = mdl.sum(w[i,j]* x[i] * ( 1 - x[j] ) for i in range(n) for j in ... | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Checking that the full Hamiltonian gives the right cost | #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
x = sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('max-cut objective:', result['energy'] + offset)
print('solution:', max_cut.get_graph_so... | energy: -1.5
max-cut objective: -4.0
solution: [0. 1. 0. 1.]
solution objective: 4.0
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Running it on quantum computerWe run the optimization routine using a feedback loop with a quantum computer that uses trial functions built with Y single-qubit rotations, $U_\mathrm{single}(\theta) = \prod_{i=1}^n Y(\theta_{i})$, and entangler steps $U_\mathrm{entangler}$. | seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
x = samp... | energy: -1.5
time: 11.74726128578186
max-cut objective: -4.0
solution: [0 1 0 1]
solution objective: 4.0
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
[Optional] Checking that the full Hamiltonian made by ```docplex.get_operator``` gives the right cost | #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = ExactEigensolver(qubitOp_docplex, k=1)
result = ee.run()
x = sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('max-cut objective:', result['energy'] + offset_docplex)
print('solution:', max_... | energy: -1.5
max-cut objective: -4.0
solution: [0. 1. 0. 1.]
solution objective: 4.0
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Traveling Salesman ProblemIn addition to being a notorious NP-complete problem that has drawn the attention of computer scientists and mathematicians for over two centuries, the Traveling Salesman Problem (TSP) has important bearings on finance and marketing, as its name suggests. Colloquially speaking, the traveling ... | # Generating a graph of 3 nodes
n = 3
num_qubits = n ** 2
ins = tsp.random_tsp(n)
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
colors = ['r' for node in G.nodes()]
pos = {k: v for k, v in enumerate(ins.coord)}
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, a... | distance
[[ 0. 25. 19.]
[25. 0. 27.]
[19. 27. 0.]]
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Brute force approach | from itertools import permutations
def brute_force_tsp(w, N):
a=list(permutations(range(1,N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j,pre_j]
pre_j = j
distance = distance + w[pre_j,0]
... | order = (0, 1, 2) Distance = 71.0
Best order from brute force = (0, 1, 2) with total distance = 71.0
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Mapping to the Ising problem | qubitOp, offset = tsp.get_operator(ins) | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
[Optional] Using DOcplex for mapping to the Ising problemUsing ```docplex.get_qubitops``` is a different way to create an Ising Hamiltonian of TSP. ```docplex.get_qubitops``` can create a corresponding Ising Hamiltonian from an optimization model of TSP. An example of using ```docplex.get_qubitops``` is as below. | # Create an instance of a model and variables
mdl = Model(name='tsp')
x = {(i,p): mdl.binary_var(name='x_{0}_{1}'.format(i,p)) for i in range(n) for p in range(n)}
# Object function
tsp_func = mdl.sum(ins.w[i,j] * x[(i,p)] * x[(j,(p+1)%n)] for i in range(n) for j in range(n) for p in range(n))
mdl.minimize(tsp_func)
... | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Checking that the full Hamiltonian gives the right cost | #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
print('energy:', result['energy'])
print('tsp objective:', result['energy'] + offset)
x = sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z =... | energy: -600035.5
tsp objective: 71.0
feasible: True
solution: [0, 1, 2]
solution objective: 71.0
| Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
Running it on quantum computerWe run the optimization routine using a feedback loop with a quantum computer that uses trial functions built with Y single-qubit rotations, $U_\mathrm{single}(\theta) = \prod_{i=1}^n Y(\theta_{i})$, and entangler steps $U_\mathrm{entangler}$. | seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
print('e... | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
[Optional] Checking that the full Hamiltonian made by ```docplex.get_operator``` gives the right cost | ee = ExactEigensolver(qubitOp_docplex, k=1)
result = ee.run()
print('energy:', result['energy'])
print('tsp objective:', result['energy'] + offset_docplex)
x = sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:'... | _____no_output_____ | Apache-2.0 | qiskit/advanced/aqua/optimization/max_cut_and_tsp.ipynb | gvvynplaine/qiskit-iqx-tutorials |
**Read Later:**Module Documentationhttps://pytorch.org/docs/stable/generated/torch.nn.Module.html A Gentle Introduction to ``torch.autograd``---------------------------------``torch.autograd`` is PyTorch’s automatic differentiation engine that powersneural network training. In this section, you will get a conceptualund... | import torch, torchvision
model = torchvision.models.resnet18(pretrained=True)
data = torch.rand(1, 3, 64, 64)
labels = torch.rand(1, 1000)
print(data.size(),labels.size()) | torch.Size([1, 3, 64, 64]) torch.Size([1, 1000])
| MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Next, we run the input data through the model through each of its layers to make a prediction.This is the **forward pass**. | prediction = model(data) # forward pass
print(prediction.size()) | torch.Size([1, 1000])
| MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
We use the model's prediction and the corresponding label to calculate the error (``loss``).The next step is to backpropagate this error through the network.Backward propagation is kicked off when we call ``.backward()`` on the error tensor.Autograd then calculates and stores the gradients for each model parameter in t... | loss = (prediction - labels).sum()
loss.backward() # backward pass | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Next, we load an optimizer, in this case SGD with a learning rate of 0.01 and momentum of 0.9.We register all the parameters of the model in the optimizer.model.parameters() can acesss all model's parameters | optim = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9) | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Finally, we call ``.step()`` to initiate gradient descent. The optimizer adjusts each parameter by its gradient stored in ``.grad``. | optim.step() #gradient descent | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
At this point, you have everything you need to train your neural network.The below sections detail the workings of autograd - feel free to skip them. -------------- Differentiation in Autograd~~~~~~~~~~~~~~~~~~~~~~~~~~~Let's take a look at how ``autograd`` collects gradients. We create two tensors ``a`` and ``b`` with`... | import torch
a = torch.tensor([2., 3.], requires_grad=True)
b = torch.tensor([6., 4.], requires_grad=True) | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
We create another tensor ``Q`` from ``a`` and ``b``.\begin{align}Q = 3a^3 - b^2\end{align} | Q = 3*a**3 - b**2
print(Q) | tensor([-12., 65.], grad_fn=<SubBackward0>)
| MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Let's assume ``a`` and ``b`` to be parameters of an NN, and ``Q``to be the error. In NN training, we want gradients of the errorw.r.t. parameters, i.e.\begin{align}\frac{\partial Q}{\partial a} = 9a^2\end{align}\begin{align}\frac{\partial Q}{\partial b} = -2b\end{align}When we call ``.backward()`` on ``Q``, autograd ca... | external_grad = torch.tensor([1,1])
Q.backward(gradient=external_grad) | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Gradients are now deposited in ``a.grad`` and ``b.grad`` | # check if collected gradients are correct
print(a.grad)
print(9*a**2)
print(9*a**2 == a.grad)
print(-2*b == b.grad) | tensor([36., 81.])
tensor([36., 81.], grad_fn=<MulBackward0>)
tensor([True, True])
tensor([True, True])
| MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Optional Reading - Vector Calculus using ``autograd``^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Mathematically, if you have a vector valued function$\vec{y}=f(\vec{x})$, then the gradient of $\vec{y}$ withrespect to $\vec{x}$ is a Jacobian matrix $J$:\begin{align}J = \left(\begin{array}{cc} \frac{\part... | x = torch.rand(5, 5)
y = torch.rand(5, 5)
z = torch.rand((5, 5), requires_grad=True)
a = x + y
print(f"Does `a` require gradients? : {a.requires_grad}")
b = x + z
print(f"Does `b` require gradients?: {b.requires_grad}") | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
In a NN, parameters that don't compute gradients are usually called **frozen parameters**.It is useful to "freeze" part of your model if you know in advance that you won't need the gradients of those parameters(this offers some performance benefits by reducing autograd computations).Another common usecase where exclusi... | from torch import nn, optim
model = torchvision.models.resnet18(pretrained=True)
# Freeze all the parameters in the network
for param in model.parameters():
param.requires_grad = False | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Let's say we want to finetune the model on a new dataset with 10 labels.In resnet, the classifier is the last linear layer ``model.fc``.We can simply replace it with a new linear layer (unfrozen by default)that acts as our classifier. | model.fc = nn.Linear(512, 10) | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Now all parameters in the model, except the parameters of ``model.fc``, are frozen.The only parameters that compute gradients are the weights and bias of ``model.fc``. | # Optimize only the classifier
optimizer = optim.SGD(model.parameters(), lr=1e-2, momentum=0.9) | _____no_output_____ | MIT | official_tutorial/lesson2b_autograd_tutorial_deep_learning_usage.ipynb | zhennongchen/pytorch-tutorial |
Thai2Vec Classification Using ULMFitThis notebook demonstrates how to use the [ULMFit model](https://arxiv.org/abs/1801.06146) implemented by`thai2vec` for text classification. We use [Wongnai Challenge: Review Rating Prediction](https://www.kaggle.com/c/wongnai-challenge-review-rating-prediction) as our benchmark as ... | %reload_ext autoreload
%autoreload 2
%matplotlib inline
import re
import html
import numpy as np
import dill as pickle
from IPython.display import Image
from IPython.core.display import HTML
from collections import Counter
from sklearn.model_selection import train_test_split
from fastai.text import *
from pythainlp.... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Train/Validation SetsWe use data from [Wongnai Challenge: Review Rating Prediction](https://www.kaggle.com/c/wongnai-challenge-review-rating-prediction). The training data consists of 39,999 restaurant reviews from unknown number of reviewers labeled one to five stars, with the schema `(label,review)`. We use 75/15 tr... | raw_train = pd.read_csv(f'{RAW_PATH}w_review_train.csv',sep=';',header=None)
raw_train = raw_train.iloc[:,[1,0]]
raw_train.columns = ['label','review']
raw_test = pd.read_csv(f'{RAW_PATH}test_file.csv',sep=';')
submission = pd.read_csv(f'{RAW_PATH}sample_submission.csv',sep=',')
print(raw_train.shape)
raw_train.head()... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Language Modeling Text Processing We first determine the vocab for the reviews, then train a language model based on our training set. We perform the following minimal text processing:* The token `xbos` is used to note start of a text since we will be chaining them together for the language model training. * `pyThaiN... | max_vocab = 60000
min_freq = 2
df_lm = pd.read_csv(f'{DATA_PATH}train_lm.csv',header=None,chunksize=30000)
df_val = pd.read_csv(f'{DATA_PATH}valid.csv',header=None,chunksize=30000)
trn_lm,trn_tok,trn_labels,itos_cls,stoi_cls,freq_trn = numericalizer(df_trn)
val_lm,val_tok,val_labels,itos_cls,stoi_cls,freq_val = numer... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Load Pretrained Language Model Instead of starting from random weights, we import the language model pretrained on Wikipedia (see `pretrained_wiki.ipynb`). For words that appear only in the Wongnai dataset but not Wikipedia, we start with the average of all embeddings instead. Max vocab size is set at 60,000 and minim... | em_sz = 300
vocab_size = len(itos_cls)
wgts = torch.load(f'{MODEL_PATH}thwiki_model2.h5', map_location=lambda storage, loc: storage)
itos_pre = pickle.load(open(f'{MODEL_PATH}itos_pre.pkl','rb'))
stoi_pre = collections.defaultdict(lambda:-1, {v:k for k,v in enumerate(itos_pre)})
#pretrained weights
wgts = merge_wgts(em... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Train Language Model | em_sz,nh,nl = 300,1150,3
wd=1e-7
bptt=70
bs=60
opt_fn = partial(optim.Adam, betas=(0.8, 0.99))
weight_factor = 0.7
drops = np.array([0.25, 0.1, 0.2, 0.02, 0.15])*weight_factor
#data loader
trn_dl = LanguageModelLoader(np.concatenate(trn_lm), bs, bptt)
val_dl = LanguageModelLoader(np.concatenate(val_lm), bs, bptt)
md = ... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Classification With the language model trained on Wongnai dataset, we use its embeddings to initialize the review classifier. We train the classifier using discriminative learning rates, slanted triangular learning rates, gradual unfreezing and a few other tricks detailed in the [ULMFit paper](https://arxiv.org/abs/18... | #load csvs and tokenizer
max_vocab = 60000
min_freq = 2
df_trn = pd.read_csv(f'{DATA_PATH}train.csv',header=None,chunksize=30000)
df_val = pd.read_csv(f'{DATA_PATH}valid.csv',header=None,chunksize=30000)
df_tst = pd.read_csv(f'{DATA_PATH}test.csv',header=None,chunksize=30000)
trn_cls,trn_tok,trn_labels,itos_cls,stoi_c... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Create Data Loader | #dataset object
bs = 60
trn_ds = TextDataset(trn_cls, trn_labels)
val_ds = TextDataset(val_cls, val_labels)
tst_ds = TextDataset(tst_cls, tst_labels)
#sampler
trn_samp = SortishSampler(trn_cls, key=lambda x: len(trn_cls[x]), bs=bs//2)
val_samp = SortSampler(val_cls, key=lambda x: len(val_cls[x]))
tst_samp = SortSample... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Train Classifier | #parameters
weight_factor = 0.5
drops = np.array([0.25, 0.1, 0.2, 0.02, 0.15])*weight_factor
bptt = 70
em_sz = 300
nh = 1150
nl = 3
vocab_size = len(itos_cls)
nb_class=int(trn_labels.max())+1
opt_fn = partial(optim.Adam, betas=(0.7, 0.99))
bs = 60
wd = 1e-7
#classifier model
# em_sz*3 for max, mean, just activations
m... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Validation Performance | learner.load('last_two_layers')
#get validation performance
probs,y= learner.predict_with_targs()
preds = np.argmax(np.exp(probs),1)
Counter(preds)
Counter(y)
from sklearn.metrics import confusion_matrix
from sklearn.metrics import fbeta_score
most_frequent = np.array([4]*len(preds))
print(f'Baseline Micro F1: {fbeta_... | Baseline Micro F1: 0.176
Micro F1: 0.5976666666666667
Confusion matrix, without normalization
[[ 14 36 13 1 1]
[ 13 80 150 22 2]
[ 5 36 945 814 28]
[ 0 0 344 2210 230]
[ 0 1 22 696 337]]
| MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Submission | probs,y= learner.predict_with_targs(is_test=True)
preds = np.argmax(np.exp(probs),1) + 1
Counter(preds)
submit_df = pd.DataFrame({'a':y,'b':preds})
submit_df.columns = ['reviewID','rating']
submit_df.head()
submit_df.to_csv(f'{DATA_PATH}valid10_2layers_newmm.csv',index=False) | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Benchmark with FastText We used [fastText](https://github.com/facebookresearch/fastText)'s own [pretrained embeddings](https://github.com/facebookresearch/fastText/blob/master/pretrained-vectors.md) and a relatively "default" settings in order to benchmark our results. This gave us the micro-averaged F1 score of 0.504... | df_trn = pd.read_csv(f'{DATA_PATH}train.csv',header=None)
df_val = pd.read_csv(f'{DATA_PATH}valid.csv',header=None)
df_tst = pd.read_csv(f'{DATA_PATH}test.csv', header=None)
train_set = []
for i in range(df_trn.shape[0]):
label = df_trn.iloc[i,0]
line = df_trn.iloc[i,1].replace('\n', ' ')
train_set.append(f... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Train FastText | !/home/ubuntu/theFastText/fastText-0.1.0/fasttext supervised -input '{DATA_PATH}train.txt' -pretrainedVectors '{MODEL_PATH}wiki.th.vec' -epoch 10 -dim 300 -wordNgrams 2 -output '{MODEL_PATH}fasttext_model'
!/home/ubuntu/theFastText/fastText-0.1.0/fasttext test '{MODEL_PATH}fasttext_model.bin' '{DATA_PATH}valid.txt'
pre... | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Submission | submit_df = pd.DataFrame({'a':[i+1 for i in range(len(preds))],'b':preds})
submit_df.columns = ['reviewID','rating']
submit_df['rating'] = submit_df['rating'].apply(lambda x: x.split('__')[2])
submit_df.head()
submit_df.to_csv(f'{DATA_PATH}fasttext.csv',index=False) | _____no_output_____ | MIT | notebook/ulmfit_wongnai.ipynb | titipata/thai2vec |
Generate and Save Results from Different ANN Methods | import numpy as np
import pandas as pd
import os
import json
import ast
import random
import tensorflow as tf
import tensorflow_addons as tfa
from bpmll import bp_mll_loss
import sklearn_json as skljson
from sklearn.model_selection import train_test_split
from sklearn import metrics
import sys
os.chdir('C:\\Users\\robe... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Models on Reduced Dataset (each instance has atleast one label) | ## Load the reduced tfidf dataset
file_object = open('../BP-MLL Text Categorization/tfidf_trainTest_data_reduced.json',)
tfidf_data_reduced = json.load(file_object)
X_train_hasLabel = np.array(tfidf_data_reduced['X_train_hasLabel'])
X_test_hasLabel = np.array(tfidf_data_reduced['X_test_hasLabel'])
Y_train_hasLabel = np... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Feed-Forward Cross-Entropy Network | ## Start by defining and compiling the cross-entropy loss network (bpmll used later)
tf.random.set_seed(123)
num_labels = 13
model_ce_FF = tf.keras.models.Sequential([
tf.keras.layers.Dense(32, activation = 'relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_labels, activation = 'sigmoid')
])
... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Feed-Forward BP-MLL Network | ## Start by defining and compiling the bp-mll loss network
tf.random.set_seed(123)
model_bpmll_FF = tf.keras.models.Sequential([
tf.keras.layers.Dense(32, activation = 'relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_labels, activation = 'sigmoid')
])
optim_func = tf.keras.optimizers.Adam(... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
BPMLL Bidirectional LSTM Recurrent Network | ## Load the pre-processed data
file_object_reduced = open('../RNN Text Categorization/RNN_data_dict_reduced.json',)
RNN_data_dict_reduced = json.load(file_object_reduced)
RNN_data_dict_reduced = ast.literal_eval(RNN_data_dict_reduced)
train_padded_hasLabel = np.array(RNN_data_dict_reduced['train_padded_hasLabel'])
test... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Cross-Entropy Bidirectional LSTM Recurrent Network | ## Define the bidirectional LSTM RNN architecture
tf.random.set_seed(123)
num_labels = 13
max_length = 100
num_unique_words = 2711
model_ce_biLSTM = tf.keras.models.Sequential([
tf.keras.layers.Embedding(num_unique_words, 32, input_length = max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(16, re... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Models on Full Dataset (some instances have no labels) | ## Load the full tfidf dataset
file_object = open('../BP-MLL Text Categorization/tfidf_trainTest_data.json',)
tfidf_data_full = json.load(file_object)
X_train = np.array(tfidf_data_full['X_train'])
X_test = np.array(tfidf_data_full['X_test'])
Y_train = np.array(tfidf_data_full['Y_train'])
Y_test = np.array(tfidf_data_f... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Feed-Forward Cross-Entropy Network | ## Use same architecture as the previous cross-entropy feed-forward network and train on full dataset
tf.random.set_seed(123)
num_labels = 13
model_ce_FF_full = tf.keras.models.Sequential([
tf.keras.layers.Dense(32, activation = 'relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_labels, activ... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
LSTM Reccurrent Network | ## Load the pre-processed data
file_object = open('../RNN Text Categorization/RNN_data_dict.json',)
RNN_data_dict = json.load(file_object)
RNN_data_dict = ast.literal_eval(RNN_data_dict)
train_padded = np.array(RNN_data_dict['train_padded'])
test_padded = np.array(RNN_data_dict['test_padded'])
Y_train = np.array(RNN_da... | _____no_output_____ | MIT | codes/ANN Results/Generate_ANN_Results.ipynb | architdatar/NewsArticleClassification |
Azure Content Moderator API Reference: https://docs.microsoft.com/en-us/azure/cognitive-services/Content-Moderator/api-reference | import requests
subscripiton_key = 'YOUR_SUBSCRIPTION_KEY'
endpoint = 'YOUR_ENDPOINT_URL'
request_url = f'{endpoint}/contentmoderator/moderate/v1.0/ProcessText/Screen'
headers = {
'Content-Type': 'text/plain',
'Ocp-Apim-Subscription-Key': subscripiton_key,
}
params = {
'classify': True,
}
body = 'Is this a ... | _____no_output_____ | MIT | evaluate-text-with-azure-cognitive-language-services/content-moderator.ipynb | zkan/azure-ai-engineer-associate-workshop |
Data Analytic Boot Camp - ETL Project How is the restaurant's inspection score compare to the Yelp customer review rating? We always rely on the application on our digital device to look for high rating restaurant. However,does the high rating restaurants (rank by customers) provide a clearn and healthy food environme... | # Dependencies
import pandas as pd
import os
import csv
import requests
import json
import numpy as np
from config_1 import ykey
# Database Connection Dependencies
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, inspect
import s... | _____no_output_____ | MIT | ETL_Project_Completed.ipynb | NormanLo4319/ETL-Project |
Yelp API Request We tried two ways to extract data from Yelp API request, 1. Search by city location, San Francisco 2. Search by zip codes This project choose to use method 1 because method 2 create bunch of duplicates that is difficult to clean in the later time. | # Testing Yelp API request for extracting the business related data
# Yelp API key is stored in ykey
headers = {"Authorization": "bearer %s" % ykey}
endpoint = "https://api.yelp.com/v3/businesses/search"
name = []
rating = []
review_count = []
address = []
city = []
state = []
zip_ = []
phone = []
# Define the ... | _____no_output_____ | MIT | ETL_Project_Completed.ipynb | NormanLo4319/ETL-Project |
Storing the data to SQLite database: There are two ways to store the data into SQLite database, 1. Using pandas method "dataframe.to_sql()" 2. Create metadata base and append data from data frames to the specific tables in the database This project use the second method to append data because to_sql() method does not ... | # Import SQL Alchemy
from sqlalchemy import create_engine
# Import and establish Base for which classes will be constructed
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Import modules to declare columns and column data types
from sqlalchemy import Column, Integer, String, Float... | _____no_output_____ | MIT | ETL_Project_Completed.ipynb | NormanLo4319/ETL-Project |
Analysis on restaurant inspection scores and customer-based rating Using matplotly for ploting the joined data. After joining the data, only 122 business can be matched by the business name and it's zip code | joined_df = pd.merge(inspection_df, yelp_df, on=['name', 'zip'])
# joined_df.head(100)
# print(len(joined_df))
joined_df['name'].nunique()
# Cleaning the data in the joined data frame
joined_df = joined_df.dropna(subset=['inspection_score'])
joined_df = joined_df.drop_duplicates(subset='business_id', keep='first')
join... | _____no_output_____ | MIT | ETL_Project_Completed.ipynb | NormanLo4319/ETL-Project |
Desafio 1 - Escolher um título mais descritivo que passe a mensagem adequada | UF = "Unidade da Federação"
Ano_Mes = "2008/Ago"
ax = dados.plot(x = UF, y = Ano_Mes, kind = "bar", figsize = (9, 6))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:,.2f}"))
plt.title("Despesas em procedimentos hospitalares do SUS \n {} - Processados em {}".format(UF, Ano_Mes))
plt.show() | _____no_output_____ | MIT | notebooks/modulo_01/aula_02_primeiras_visualizacoes_de_dados.ipynb | daviramalho/Bootcamp-DS2-Alura |
Desafio 01.2 - Faça a mesma análise para o mês mais recente que você possui. | UF = "Unidade da Federação"
Ano_Mes = "2021/Mar"
ax = dados.plot(x = UF, y = Ano_Mes, kind = "bar", figsize = (9, 6))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:,.2f}"))
plt.title("Despesas em procedimentos hospitalares do SUS \n {} - Processados em {}".format(UF, Ano_Mes))
#plt.savefig("../../reports/... | _____no_output_____ | MIT | notebooks/modulo_01/aula_02_primeiras_visualizacoes_de_dados.ipynb | daviramalho/Bootcamp-DS2-Alura |
AULA 02 - Primeiras Visualizações de Dados | dados[["2008/Ago", "2008/Set"]].head()
dados.mean()
colunas_usaveis = dados.mean().index.tolist()
colunas_usaveis.insert(0, "Unidade da Federação")
colunas_usaveis
usaveis = dados[colunas_usaveis]
usaveis.head()
usaveis = usaveis.set_index("Unidade da Federação")
usaveis.head()
usaveis["2019/Ago"].head()
usaveis.loc["1... | _____no_output_____ | MIT | notebooks/modulo_01/aula_02_primeiras_visualizacoes_de_dados.ipynb | daviramalho/Bootcamp-DS2-Alura |
DESAFIO 02.1 - Reposicionar a legenda fora do gráfico | estados = "Todos os Estados"
ano_selecionado = "2007/Ago a 2021/Mar"
ax2 = usaveis.T.plot(figsize = (12,6))
ax2.legend(loc = 6, bbox_to_anchor = (1, 0.5))
ax2.yaxis.set_major_formatter(ticker.StrMethodFormatter("R$ {x:,.2f}"))
plt.title("Despesas em procedimentos hospitalares do SUS por local de internação \n {} - Pro... | _____no_output_____ | MIT | notebooks/modulo_01/aula_02_primeiras_visualizacoes_de_dados.ipynb | daviramalho/Bootcamp-DS2-Alura |
DESAFIO 02.2 - Plotar o Gráfico de linha com apenas 5 estados de sua preferência | estados = "PA, MG, CE, RS e SP"
ano_selecionado = "2007/Ago a 2021/Mar"
usaveis_selecionados = usaveis.loc[["15 Pará", "31 Minas Gerais", "23 Ceará", "43 Rio Grande do Sul", "35 São Paulo"]]
ax3 = usaveis_selecionados.T.plot(figsize = (12,6))
ax3.legend(loc = 6, bbox_to_anchor = (1, 0.5))
ax3.yaxis.set_major_formatter... | _____no_output_____ | MIT | notebooks/modulo_01/aula_02_primeiras_visualizacoes_de_dados.ipynb | daviramalho/Bootcamp-DS2-Alura |
--- | md = webdriver.Chrome() # 오픈
md.get('https://cloud.google.com/vision/') # 해당 주소로 이동
md.set_window_size(900,700) # size setting
md.execute_script("window.scrollTo(0, 1000);") # 브라우저 스크롤 이동 | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
현재 윈도우 위치 저장 | main = md.current_window_handle | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
새로운 탭 오픈 (포커스는 변경x) | md.execute_script("window.open('https://www.google.com');")
windows = md.window_handles # 윈도우 체크
windows | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
switch_to_window : focus 변경 | md.switch_to_window(windows[1])
md.get('https://www.naver.com')
md.switch_to_window(main)
md.execute_script('location.reload()') #새로고침 | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
control alert | md.execute_script('alert("selenium test")')
alert = md.switch_to_alert()
print(alert.text)
alert.accept()
md.execute_script('alert("selenium test")')
md.switch_to_alert().accept()
md.execute_script("confirm('confirm?')")
# alert = md.switch_to_alert()
print(alert.text)
# alert.accept()
alert.dismiss() | confirm?
| MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
input key & button | md.switch_to_window(windows[1])
md.find_element_by_css_selector('#query').send_keys('test')
md.find_element_by_css_selector(".ico_search_submit").click() | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
close driver | md.close() # one for one
for i in md.window_handles:
md.switch_to_window(i)
md.close() | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
--- file uploadhttps://visual-recognition-demo.ng.bluemix.nethttps://cloud.google.com/vision/ | cr = webdriver.Chrome()
cr.get('https://cloud.google.com/vision/') | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
iframe의 경우 포커스 이동이 필요함 | iframe = cr.find_element_by_css_selector('#vision_demo_section > iframe ')
cr.switch_to_frame(iframe)
# Switch back default content
# cr.switch_to_default_content() #아이프레임 밖으로 포커스 이동
path = !pwd #현재 디렉토리위치 리스트
print(type(path), path)
file_path = path[0] + "/screenshot_element.png"
cr.find_element_by_css_selector('#inpu... | _____no_output_____ | MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
safe search 항목 점수 출력 | a = cr.find_elements_by_css_selector('#card div.row.style-scope.vs-safe')
for i in a:
print(i.text) | Adult Very Unlikely
Spoof Unlikely
Medical Very Unlikely
Violence Very Unlikely
Racy Very Unlikely
| MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
--- 한번에 실행 | driver = webdriver.Chrome()
driver.get('https://cloud.google.com/vision/')
iframe = driver.find_element_by_css_selector("#vision_demo_section iframe")
driver.switch_to_frame(iframe)
file_path = path[0] + "/screenshot_element.png"
driver.find_element_by_css_selector("#input").send_keys(file_path)
time.sleep(15) # 이미지를... | Adult Very Unlikely
Spoof Unlikely
Medical Very Unlikely
Violence Very Unlikely
Racy Very Unlikely
| MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
element 체크하면서 실행 | def check_element(driver, selector):
try:
driver.find_element_by_css_selector(selector)
return True
except:
return False
driver = webdriver.Chrome()
driver.get('https://cloud.google.com/vision/')
iframe = driver.find_element_by_css_selector("#vision_demo_section iframe")
driver.switch_... | 1sec
2sec
3sec
4sec
Adult Very Unlikely
Spoof Unlikely
Medical Very Unlikely
Violence Very Unlikely
Racy Very Unlikely
| MIT | Past/DSS/Programming/Scraping/180220_selenium.ipynb | Moons08/TIL |
Precious function | U.shape
def get_dfU(U, b,step):
d = U.T.shape[1]
dfU = pd.DataFrame(u)
dim = [i for i in range(d)]
dfU[[str(i)+"_follower" for i in list(dfU.columns)]] = dfU[dfU.columns]
for k in range(d):
dfU_temp = dfU.copy()
dfU_temp[k] = dfU_temp[k].apply(lambda x: x+step if x<1 else x-ste... | _____no_output_____ | BSD-3-Clause | .ipynb_checkpoints/Python Implementation-checkpoint.ipynb | DatenBiene/Vector_Quantile_Regression |
Building a RF model for $\alpha _x$ | from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
rscl_df = pd.DataFrame(rscl_data, columns=[f"Feat_{i}" for i in range(300)])
rscl_df.head()
model = RandomForestRegressor(n_estimators=40, max_features='sqrt', min_samples_split=5, n_jobs=-1)
X_train, X_test, y_train... | _____no_output_____ | MIT | Week7/july19_hierarchial_clustering.ipynb | Anantha-Rao12/NMR-quantumstates-GSOC21 |
Removing redundant features | import scipy
from scipy.cluster import hierarchy as hc
corr = np.round(scipy.stats.spearmanr(df_keep).correlation, 4)
corr_condensed = hc.distance.squareform(1-corr)
z = hc.linkage(corr_condensed, method='average')
fig = plt.figure(figsize=(18,14))
dendrogram = hc.dendrogram(z, labels=df_keep.columns, orientation='l... | _____no_output_____ | MIT | Week7/july19_hierarchial_clustering.ipynb | Anantha-Rao12/NMR-quantumstates-GSOC21 |
Let's try removing some of these related features to see if the model can be simplified without impacting the accuracy. | def get_oob(df):
m = RandomForestRegressor(n_estimators=30, min_samples_leaf=5, max_features=0.6, n_jobs=-1, oob_score=True)
x, _ = split_vals(df, n_trn)
m.fit(x, y_train)
return m.oob_score_
!pip install pdpbox
from pdpbox import pdp
from plotnine import *
| _____no_output_____ | MIT | Week7/july19_hierarchial_clustering.ipynb | Anantha-Rao12/NMR-quantumstates-GSOC21 |
Examine sample file from shipboard real-time processed ADCPThis is a pre-cruise examination of the data file to see how to truncate it for sending to shore during the cruise. | import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import cftime
datapath = '../data/raw/shipboard_adcp_initial_look/'
file = datapath + 'wh300.nc'
ds = xr.open_dataset(file,drop_variables=['amp','pg','pflag','num_pings','tr_temp'])
ds
ds2=ds.sel(time=slice("2021-09-06", "2021... | _____no_output_____ | MIT | code/truncate_shipboard_adcp.ipynb | jtomfarrar/S-MODE_analysis |
METAS uncLib https://www.metas.ch/metas/en/home/fabe/hochfrequenz/unclib.html | from metas_unclib import *
import matplotlib.pyplot as plt
from sigfig import round
%matplotlib inline
use_mcprop(n=100000)
#use_linprop()
def uncLib_PlotHist(mcValue, xLabel='Value / A.U.', yLabel='Probability', title='Histogram of value', bins=1001, coverage=0.95):
hObject = mcValue.net_object
hValues = [fl... | _____no_output_____ | CC0-1.0 | empir19nrm02/Jupyter/IBudgetMETAS.ipynb | AndersThorseth/empir19nrm02 |
Measurement Uncertainty Simplest Possible Example Define the parameter for the calibration factor | k_e = ufloat(0.01, 0.0000045)
k_e | _____no_output_____ | CC0-1.0 | empir19nrm02/Jupyter/IBudgetMETAS.ipynb | AndersThorseth/empir19nrm02 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.