text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Eksplorasi Awal Data (10 poin)
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division # Gunakan print(...) dan bukan print ... import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.datasets import load_digits from sklearn.cluster import KMeans from sklearn.metrics import acc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Description Step2: From the above info(),We can see columns Age, Cabin and Embarked have missing values. Step3: lets decide should we rem...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from IPython.display import display %matplotlib inline # Load the dataset files = 'titanic_data.csv' data_titanic = pd.read_csv(files) display(data_titanic.head()) data =data_titanic # Show the dataset display(data.head()) data.info() #exculding s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: monuments_all_se-bbr_(sv) Step2: Let's check If we have extracted the two always occuring fields 'name' and 'buildId' for all objects Step3: H...
<ASSISTANT_TASK:> Python Code: cursor.execute("SELECT * FROM monuments_all WHERE country='se-bbr'") all_bbr = pd.io.sql.read_sql('select * from monuments_all WHERE country="se-bbr"', conn) all_bbr.shape table_name = "se_bbr" # I've renamed monuments_se-bbr_(se) to 'se_bbr' in local database, change to correct name se_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 훈련 후 동적 범위 양자화 Step2: TensorFlow 모델 훈련하기 Step3: 예를 들어, 단일 epoch에 대해서만 모델을 훈련했기 때문에 최대 96%의 정확성으로만 훈련됩니다. Step4: tflite 파일에 작성합니다. Step5: 내보낼...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create or load data set Step2: Data set characteristics Step3: Unknown parameters Step4: Estimate beta Step5: Alternatively, estimate beta b...
<ASSISTANT_TASK:> Python Code: import random import operator as op import optunity.metrics import semisup_metrics as ss import numpy as np from matplotlib import pyplot as plt import pickle import csv import util %matplotlib inline # fraction of positives/negatives that are known # known_neg_frac == 0 implies PU learn...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ¿Cómo? Step2: ¿Cómo? Step3: Ejemplo 1 Step4: Ejemplo 1
<ASSISTANT_TASK:> Python Code: from matplotlib import pyplot as plt import numpy as np x = np.linspace(1E-8,np.pi/6,1000) y = x*np.sin(1./x) plt.plot(x, y) plt.plot(x, x) plt.plot(x, -x) plt.show() from mat281_code import black_box black_box.iplot() # Calculando el promedio x = np.array([1.2, 2.2, 2.6, 3.1, 3.1, 3.2,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: The strategy, unlike our first attempt, requires a real train/test split in the dataset because we're going to fit an actual model (although a t...
<ASSISTANT_TASK:> Python Code: import numpy as np import networkx as nx import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import cPickle as pickle from copy import deepcopy %matplotlib inline plt.style.use("fivethirtyeight") sns.set() all_graphs = pickle.load(open("train-freq-graphs.pkl",'r')) a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 迁移学习和微调 Step2: 数据预处理 Step3: 显示训练集中的前九个图像和标签: Step4: 由于原始数据集不包含测试集,因此您需要创建一个。为此,请使用 tf.data.experimental.cardinality 确定验证集中有多少批次的数据,然后将其中的 20%...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The actual data that we will use comes from the GIANT consortium Step2: Next, we will read in the data for two groups. Step3: Lastly, we run t...
<ASSISTANT_TASK:> Python Code: # from assocplots.misc import mock_data_generation # data_m, data_w = mock_data_generation(M=100000, seed=42) # data_m['pval'] /= 500000.*np.exp(-(data_m['pos']-10000.)**2/50000.0) * (data_m['chr']=='4') * np.random.rand(len(data_m)) + 1. # Load standard libraries import numpy as np from...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The error is actually reassuring Step2: What should range_overlap do in this case Step3: Do two segments that touch at their endpoints overlap...
<ASSISTANT_TASK:> Python Code: assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0) assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0) assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0) assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == ??? assert range_overlap([ (0.0, 1.0), (1.0, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the Data into an SMPS object Step2: Explore the SMPS Object Step3: SMPS.bins and SMPS.midpoints Step4: SMPS.histogram and SMPS.raw Step5...
<ASSISTANT_TASK:> Python Code: import smps import seaborn as sns import os import matplotlib import matplotlib.pyplot as plt import json %matplotlib inline # You can use seaborn to easily control how your plots appear sns.set('notebook', style='ticks', font_scale=1.5, palette='dark') smps.set() print ("smps v{}".format...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Looking at Predicted Time of Onset Step2: Interestingly a lot of the paitents off the diagnonal in the recently diagnosed group have detectable...
<ASSISTANT_TASK:> Python Code: import NotebookImport from IPython.display import clear_output from HIV_Age_Advancement import * from Setup.DX_Imports import * import statsmodels.api as sm import seaborn as sns sns.set_context("paper", font_scale=1.7, rc={"lines.linewidth": 2.5}) sns.set_style("white") fig, ax = subplo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <div class="alert alert-info"><h4>Note</h4><p>An uninitialized matrix is declared, Step2: Construct a randomly initialized matrix Step3: Const...
<ASSISTANT_TASK:> Python Code: import torch x = torch.empty(5, 3) print(x) type(x) x = torch.rand(5, 3) print(x) x = torch.zeros(5, 3, dtype=torch.long) print(x) x = torch.tensor([5.5, 3]) print(x) x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes print(x) x = torch.randn_like(x, dtype=to...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: So what is going on? Well, Python variables are reference variables. You could say "the variable a (b) is assigned to a list" rather than "the...
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML # Allows us to embed HTML into our notebook. HTML('<iframe width="800" height="400" frameborder="0" src="http://pythontutor.com/iframe-embed.html#code=a%20%3D%20%5B1,%203,%205%5D%0Ab%20%3D%20a%0Aprint%28%22a%20%3D%20%7B0%7D%20and%20has%20id%20%7B1%7D%22.fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-2', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There are some infeasibilities without line extensions. Step2: Performing security-constrained linear OPF Step3: For the PF, set the P to the ...
<ASSISTANT_TASK:> Python Code: import pypsa, os import numpy as np network = pypsa.examples.scigrid_de(from_master=True) for line_name in ["316", "527", "602"]: network.lines.loc[line_name, "s_nom"] = 1200 now = network.snapshots[0] branch_outages = network.lines.index[:15] network.sclopf(now, branch_outages=bran...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For this simple circuit the questions are Step2: Components Step3: Explore and explain the results Step4: We also good visual diagnostics in...
<ASSISTANT_TASK:> Python Code: Image("res4.gif") import numpy as np import matplotlib.pyplot as plt import pymc3 as pm import pandas as pd import seaborn as sns sns.set() %matplotlib inline ## setup the model # these are the values and precision of each Datasheets = {'R1':(6.0, 0.01), 'R2':(8.0, 0.01)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Toolkit Step2: Binary Classification Step3: Confusion Matrix Step4: The above two confusion matrixes show the same network. The bottom (norm...
<ASSISTANT_TASK:> Python Code: from sklearn import preprocessing import matplotlib.pyplot as plt import numpy as np import pandas as pd # Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue) def encode_text_dummy(df,name): dummies = pd.get_dummies(df[name]) for x in dummies.col...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Train and deploy the model Step2: We one-hot encode the label... Step3: ...and create a train/test split. Step4: Swivel Model Step5: The bui...
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out PROJECT = 'munn-sandbox' BUCKET = 'munn-sandbox' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['TFVERSION'] = '2.1' import shutil import pandas as pd import tensorflow as tf from google.cloud import bigquery from...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating Evoked objects from Epochs Step2: Basic visualization of Evoked objects Step3: Like the plot() methods for Step4: To select based o...
<ASSISTANT_TASK:> Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False) events = mne.find...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now reset the notebook's session kernel! Since we're no longer using Cloud Dataflow, we'll be using the python3 kernel from here on out so don't...
<ASSISTANT_TASK:> Python Code: !pip3 install tensorflow_hub %%bash pip install --upgrade tensorflow # Import helpful libraries and setup our project, bucket, and region import os import tensorflow as tf import tensorflow_hub as hub PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-trainin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction Step2: Setup the operators, Hamiltonian, and initial state Step4: Below, we define the terms specific to the Bloch-Redfield solve...
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np import itertools from qutip import * from numpy import * n_Pi = 13 # 8 pi pulse area Om_list = np.linspace(0.001, n_Pi, 80) # dr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Classical expressions Step2: Or, using the diffs function we defined above Step3: Weighted Expressions Step4: And this is tightly connected w...
<ASSISTANT_TASK:> Python Code: import vcsn from IPython.display import Latex def diffs(r, ss): eqs = [] for s in ss: eqs.append(r'\frac{{\partial}}{{\partial {0}}} {1}& = {2}' .format(s, r.format('latex'), r.derivation(s).format('l...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Local Training with Vertex Local Mode and Auto Packaging Step2: Vertex Training using Vertex SDK and Vertex Local Mode Container Step3: Initia...
<ASSISTANT_TASK:> Python Code: PROJECT_ID = "YOUR PROJECT ID" BUCKET_NAME = "gs://YOUR BUCKET NAME" REGION = "YOUR REGION" SERVICE_ACCOUNT = "YOUR SERVICE ACCOUNT" content_name = "tf-keras-txt-cls-dist-single-worker-gpus-local-mode-cont" BASE_IMAGE_URI = "us-docker.pkg.dev/vertex-ai/training/tf-gpu.2-5:latest" SCRIPT_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now we find the peak at Pb-212 ~ 238 keV Step2: This is good enough for now but we can fix l8tr if needed Step3: expected Step4: Expected Ste...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit csv = np.genfromtxt('thorium_test_2019-02-19_D3S.csv', delimiter= ",").T summed = np.sum(csv[:-1], axis=1) # gets rid of last value plt.plot(summed) plt.yscale('log') plt.show() Pb_shift = 250 Pb_rang...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Comment. When you run the code cell above, its output appears below it. Step2: Create dataframes to play with Step3: Comment. In the previ...
<ASSISTANT_TASK:> Python Code: import sys # system module import pandas as pd # data package import matplotlib as mpl # graphics package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Overfit and underfit Step2: The Higgs dataset Step3: The tf.data.experimental.CsvDataset class can be used to read csv records directly from a...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Some Formal Background (Skip if you just want code examples) Step2: Apart from its apealling form, this curve has the nice property of given ri...
<ASSISTANT_TASK:> Python Code: %matplotlib inline # import all shogun classes from shogun import * import random import numpy as np import matplotlib.pyplot as plt import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from math import exp # plot likelihood for three different noise lebels $\sigma$ (w...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set defaults for plotting Step2: Dataframe and bins initialization Step3: Plotting O2 respiration rate and mitochondrial volume ratio as a fun...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import os.path as op import cPickle as pickle import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt plt.close('all') datadir = op.join(os.getcwd(), 'data') #Oxygen consumption data with open(op.join(datadir, 'o2data.pkl')...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In our case, we only want to check the modularization of our software for Java production code. So we just leave the files that are belonging to...
<ASSISTANT_TASK:> Python Code: from lib.ozapfdis.git_tc import log_numstat GIT_REPO_DIR = "../../dropover_git/" git_log = log_numstat(GIT_REPO_DIR)[['sha', 'file', 'author']] git_log.head() prod_code = git_log.copy() prod_code = prod_code[prod_code.file.str.endswith(".java")] prod_code = prod_code[prod_code.file.str.s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data preprocessing Step2: Encoding the words Step3: Encoding the labels Step4: Okay, a couple issues here. We seem to have one review with ze...
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf with open('reviews.txt', 'r') as f: reviews = f.read() with open('labels.txt', 'r') as f: labels = f.read() reviews[:2000] from string import punctuation all_text = ''.join([c for c in reviews if c not in punctuation]) reviews = all_text...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Aufgabe 2 Step2: Aufgabe 3 Step3: Groundtruth-Label anpassen Step4: Aufgabe 4 Step5: Aufgabe 5 Step6: Aufgabe 6
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pprint as pp hdfs = pd.HDFStore("../../data/raw/henrik/TestMessungen_NEU.hdf") hdfs.keys df1 = hdfs.get('/x1/t1/trx_1_2') df1.head(5) # Little function to retrieve sende...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the FIF file and display the projections present in the file. Here the Step2: Display the projections one by one Step3: Use the function ...
<ASSISTANT_TASK:> Python Code: # Author: Joan Massich <mailsik@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import read_proj from mne.io import read_raw_fif from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: These features are Step2: Derived Features Step3: Here is a broad description of the keys and what they mean Step4: We clearly want to discar...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris iris = load_iris() print(iris.data.shape) measurements = [ {'city': 'Dubai', 'temperature': 33.}, {'city': 'London', 'temperature': 12.}, {'city': 'San Francisco', 'temperature': 18.}, ] from sklearn.feature_extraction import DictVectori...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: How to build a simple text classifier with TF-Hub Step2: More detailed information about installing Tensorflow can be found at https Step3: Ge...
<ASSISTANT_TASK:> Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # 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...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Filling in Missing Values Step2: Generating Features Step3: Cross Validation Method Step4: Iteration 1 Step5: Iteration 2 Step6: Iteration ...
<ASSISTANT_TASK:> Python Code: import py_entitymatching as em import os import pandas as pd # specify filepaths for tables A and B. path_A = 'newTableA.csv' path_B = 'tableB.csv' # read table A; table A has 'ID' as the key attribute A = em.read_csv_metadata(path_A, key='id') # read table B; table B has 'ID' as the key...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Parameter Selection with Preprocessing Step2: Building Pipelines Step3: Using Pipelines in Grid-searches Step4: The General Pipeline Interfac...
<ASSISTANT_TASK:> Python Code: from sklearn.svm import SVC from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler # load and split the data cancer = load_breast_cancer() X_train, X_test, y_train, y_test = train_test_split( ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Exploration Step2: Question 1 - Feature Observation Step3: LSTAT Step4: PTRATIO Step6: Developing a Model Step7: Question 2 - Goodness...
<ASSISTANT_TASK:> Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the Boston housing dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Definitions Step2: Problem Statement Step3: Plotting the T-s diagram of the cycle, Step4: Summarizing the states Step5: <div class="alert al...
<ASSISTANT_TASK:> Python Code: from thermostate import State, Q_, units, SystemInternational as SI from thermostate.plotting import IdealGas, VaporDome %matplotlib inline import matplotlib.pyplot as plt import numpy as np substance = 'water' T_1 = Q_(560.0, 'degC') p_1 = Q_(16.0, 'MPa') mdot_1 = Q_(120.0, 'kg/s') p_2 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 通过 Keras 模型创建 Estimator Step2: 创建一个简单的 Keras 模型。 Step3: 编译模型并获取摘要。 Step4: 创建输入函数 Step5: 测试您的 input_fn Step6: 通过 tf.keras 模型创建 Estimator。 St...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: An existing MODFLOW6 model is in the directory freyberg_mf6. Lets check it out Step2: You can see that all the input array and list data for t...
<ASSISTANT_TASK:> Python Code: import os import shutil import numpy as np import pandas as pd import matplotlib.pyplot as plt import pyemu import flopy org_model_ws = os.path.join('freyberg_mf6') os.listdir(org_model_ws) id_arr = np.loadtxt(os.path.join(org_model_ws,"freyberg6.dis_idomain_layer3.txt")) top_arr = np.l...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can select the prices for the available time periods of Dubai crude oil by using the [] operator Step2: We can also pass a list of columns t...
<ASSISTANT_TASK:> Python Code: import pandas as pd SpotCrudePrices_2013_Data= { 'U.K. Brent' : {'2013-Q1':112.9, '2013-Q2':103.0, '2013-Q3':110.1, '2013-Q4':109.4}, 'Dubai': {'2013-Q1':108.1, '2013-Q2':10...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 可能小伙伴们会觉得设计模式这块的东西略微有些复杂,完全不用感到灰心,如果不是想要将软件开发作为自己的职业的话,可能一辈子也不需要了解,或者不经意间用到也不知道。但是这部分内容可以用来复习类的概念知识。 Step2: 每次函数都要输出一个print语句告知用户当前在哪个函数中,这样的操作...
<ASSISTANT_TASK:> Python Code: import os class Dog(object): def __init__(self): self.name = "Dog" def bark(self): return "woof!" class Cat(object): def __init__(self): self.name = "Cat" def meow(self): return "meow!" class Human(object): def __init__(self): se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Figure 33.1 Step2: 33.3 Step3: 33.5/6 Step5: 33.9
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import scipy as sp from scipy.stats import norm from scipy.signal import convolve2d import skimage.measure x = np.arange(-5,5, .01) pdf = norm.pdf(x) data = np.random.randn(1000) fig, ax = plt.subplots(1,2, sharex='all') ax[0].plot(x, pd...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Solve system of ODE's by Scipy Step2: Reproduction Ratio Step3: Note Step4: Conclusion Step5: Ebola Step6: Governed Differential Equations ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from numpy import log from scipy import integrate from scipy.optimize import fsolve import scipy.linalg as la import scipy.integrate as spi from IPython.html.widgets import interact, interactive, fixed from IPython.html...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's create two of the most common Fields, imagining we are preparing some data for a sentiment analysis model. Step2: Once we've made our Fie...
<ASSISTANT_TASK:> Python Code: # This cell just makes sure the library paths are correct. # You need to run this cell before you run the rest of this # tutorial, but you can ignore the contents! import os import sys module_path = os.path.abspath(os.path.join('../..')) if module_path not in sys.path: sys.path.appen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: %Set up useful MathJax (Latex) macros. Step2: Notes
<ASSISTANT_TASK:> Python Code: %matplotlib nbagg %config InlineBackend.figure_format='retina' # import libraries import numpy as np import matplotlib as mp import pandas as pd import matplotlib.pyplot as plt import pandas as pd from importlib import reload from datetime import datetime import laUtilities as ut import s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Preparation Step2: We are getting a dataset of dataset_size sequences of integers of length seq_len between 0 and max_num. We use split*10...
<ASSISTANT_TASK:> Python Code: import random import string import mxnet as mx from mxnet import gluon, nd import numpy as np max_num = 999 dataset_size = 60000 seq_len = 5 split = 0.8 batch_size = 512 ctx = mx.gpu() if len(mx.test_utils.list_gpus()) > 0 else mx.cpu() X = mx.random.uniform(low=0, high=max_num, shape=(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: DQN C51/Rainbow Step2: ハイパーパラメータ Step3: 環境 Step4: エージェント Step5: また、先ほど作成したネットワークをトレーニングするためのoptimizerと、ネットワークが更新された回数を追跡するためのtrain_step_coun...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic animation Step2: You can control which array to visualize, using the scatter.sequence_index property. Actually, the pylab.animate_glyphs ...
<ASSISTANT_TASK:> Python Code: import ipyvolume as ipv import numpy as np # only x is a sequence of arrays x = np.array([[-1, -0.8], [1, -0.1], [0., 0.5]]) y = np.array([0.0, 0.0]) z = np.array([0.0, 0.0]) ipv.figure() s = ipv.scatter(x, y, z, marker='sphere', size=10) ipv.xyzlim(-1, 1) ipv.animation_control(s) # show...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Player and odds data from 2010-2016 has beeen matched and stored. Retrieve, merge, and rename. Step5: Get additional training data. We'll inc...
<ASSISTANT_TASK:> Python Code: import sqlalchemy # pandas-mysql interface library import sqlalchemy.exc # exception handling from sqlalchemy import create_engine # needed to define db interface import sys # for defining behavior under errors import numpy as np # numerical libraries import scipy as sp import pandas a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: All countries except for Denmark seem to follow a normal distribution Step2: In this case we have run all the comparisons between countries. We...
<ASSISTANT_TASK:> Python Code: #Get info of the dataset once reduced to the trust variable #Slice the dataframe to the people trust variable ppltrust = raw_data[['cntry','cntry_year','ppltrst']] #Info ppltrust.info() #Clean the values in the dataframe that are null ppltrust_clean = ppltrust[ppltrust.ppltrst.notnull()] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data Format Step2: Parameters Step3: Network Parameters Step4: TensorFlow Graph Input Step5: MultiLayer Model Step6: Weights and Bias Step7...
<ASSISTANT_TASK:> Python Code: import tensorflow as tf # Import MINST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) type(mnist) type(mnist.train.images) #mnist.train.images[0] mnist.train.images[2].shape sample = mnist.train.images[2].resh...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading the simulation data Step2: The documentation shows us that mne.read_epochs takes one required parameter (fname) and three optional para...
<ASSISTANT_TASK:> Python Code: # Don't worry about warnings in this exercise, as they can be distracting. import warnings warnings.simplefilter('ignore') # Import the required Python modules import mne import conpy import surfer # Import and configure the 3D graphics backend from mayavi import mlab mlab.init_notebook('...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2. Linear Regression Step2: The orange line on the plot above is the number of page views in blue and the orange line is the CPU load that view...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (13.0, 8.0) %matplotlib inline import pickle import sklearn import sklearn.linear_model import sklearn.preprocessing import sklearn.gaussian_process import sklearn.ensemble import pickle # Pickle files al...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For this example, we're going to re-create the market segmentation Step2: We can use the query_cases method to create two separate datasets for...
<ASSISTANT_TASK:> Python Code: # TEST import larch.numba as lx import larch import pandas as pd pd.set_option("display.max_columns", 999) pd.set_option('expand_frame_repr', False) pd.set_option('display.precision', 3) larch._doctest_mode_ = True import larch.numba as lx d = lx.examples.MTC(format='dataset') d1 = d.dc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: To exercise our MLP skills, we will start with a very simple Dataset. It consists of wave forms over time. They can be thought of captured accel...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import logging logging.basicConfig(level=40) logger = logging.getLogger() import numpy as np import math import random from neon.datasets.dataset import Dataset class GeneratedDS(Dataset): # for each example we will generate 400 time steps feature_count = 4...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example 1 Step2: Next, we can open a file containing pre calculated spatial weights for "sids2.dbf". In case you don't have spatial weights, ch...
<ASSISTANT_TASK:> Python Code: from pysal.lib.weights.contiguity import Queen from pysal.lib import examples import pysal.lib as lp import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt import matplotlib import numpy as np %matplotlib inline f = gpd.read_file(examples.get_path("sids2.dbf")) varna...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This plot shows the simulated data as black points with error bars and the true function is shown as a gray line. Step2: Then we wrap this kern...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt np.random.seed(42) t = np.sort(np.append( np.random.uniform(0, 3.8, 57), np.random.uniform(5.5, 10, 68), )) # The input coordinates must be sorted yerr = np.random.uniform(0.08, 0.22, len(t)) y = 0.2 * (t-5) + np.sin(3*t + 0.1*(t...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: A Series is like a cross between a list and a dictionary. The items are stored in an order and there are labels Step2: Querying a Series Step3...
<ASSISTANT_TASK:> Python Code: import pandas as pd animals = ["Lion", "Tiger", "Monkey", None] s = pd.Series(animals) print(s) print("The name of this Series: ", s.name) numbers = [1, 2, 3, None] pd.Series(numbers) import numpy as np np.NaN == None np.NaN == np.NaN np.isnan(np.NaN) sports = {'Cricket': 'India', 'Footb...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reading data back from npz file Step2: I use interact on my plotter function to plot the positions of the stars and galaxies in my system at ev...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, interactive, fixed from plotting_function import plotter f = open('two_star_test_sol+ic.npz','r') r = np.load('two_star_test_sol+ic.npz') so...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TQDM Progress Bar (ipywidget) Step2: TQDM Progress Bar (text)
<ASSISTANT_TASK:> Python Code: from mnist_model import mnist_model from keras_tqdm import TQDMCallback, TQDMNotebookCallback mnist_model(0, [TQDMNotebookCallback()]) mnist_model(0, [TQDMCallback()]) <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Selection and Indexing Step2: DataFrame Columns are just Series Step3: Creating a new column Step4: Removing Columns Step5: Can also drop ro...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from numpy.random import randn np.random.seed(101) df = pd.DataFrame(randn(5, 4), index = 'A B C D E'.split(), columns = 'W X Y Z'.split()) df df['W'] # Pass a list of column names df[['W', 'Z']] # SQL Syntax (NOT...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example 2 Step2: The previous step constructs a log-linear approximation of the model and then solves for the endogenous variables as functions...
<ASSISTANT_TASK:> Python Code: # 1. Input model parameters parameters = pd.Series() parameters['rhoa'] = .9 parameters['sigma'] = 0.001 print(parameters) # 2. Define a function that evaluates the equilibrium conditions def equilibrium_equations(variables_forward,variables_current,parameters): # Parameters ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 測試資料: Step2: (三)FeatureUnionc Step3: (四)找到最佳的結果
<ASSISTANT_TASK:> Python Code: from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.grid_search import GridSearchCV from sklearn.svm import SVC from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest iris = load_iris() X, y = iris.data, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sorting Step2: Q2. Sort pairs of surnames and first names and return their indices. (first by surname, then by name). Step3: Q3. Get the indic...
<ASSISTANT_TASK:> Python Code: import numpy as np np.__version__ author = 'kyubyong. longinglove@nate.com' x = np.array([[1,4],[3,1]]) out = np.sort(x, axis=1) x.sort(axis=1) assert np.array_equal(out, x) print out surnames = ('Hertz', 'Galilei', 'Hertz') first_names = ('Heinrich', 'Galileo', 'Gustav') print np...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create a new Workspace and Run in a workspace Step2: Create an execution in a run Step3: Log a data set and a model Step4: A Log_output log a...
<ASSISTANT_TASK:> Python Code: # To use the latest publish `kubeflow-metadata` library, you can run: !pip install kubeflow-metadata --user # Install other packages: !pip install pandas --user # Then restart the Notebook kernel. import pandas from kubeflow.metadata import metadata from datetime import datetime from uuid...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-3', 'landice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Make code compatible with AI Platform Training Service Step2: Move code into a python package Step3: Paste existing code into model.py Step4: ...
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out PROJECT = <YOUR PROJECT> BUCKET = <YOUR PROJECT> REGION = <YOUR REGION> import os os.environ['PROJECT'] = PROJECT os.environ['BUCKET'] = BUCKET os.environ['REGION'] = REGION os.environ['TFVERSION'] = "2.1" %%bash gcloud config set project $PROJECT g...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create Dataframe Step2: View Column Step3: View Two Columns Step4: View First Two Rows Step5: View Rows Where Coverage Is Greater Than 50 St...
<ASSISTANT_TASK:> Python Code: import pandas as pd data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'year': [2012, 2012, 2013, 2014, 2014], 'reports': [4, 24, 31, 2, 3], 'coverage': [25, 94, 57, 62, 70]} df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', '...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Downloading Data Step2: Munging Data Step3: Training Models Step4: Trying different hyperparameters Step5: Creating your own estimator Step6...
<ASSISTANT_TASK:> Python Code: # packages for downloading the data import os import urllib # packages for munging, plotting, machine learning import pandas as pd import numpy as np import warnings # xgboost uses the deprecated sklearn.cross_validate module, but we don't depend on it with warnings.catch_warnings(): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python for Everyone!<br/>Oregon Curriculum Network Step2: y's value is an ordinary int, equivalently the value of MyClass.__dict__['y'], wherea...
<ASSISTANT_TASK:> Python Code: class RevealAccess(object): A data descriptor that sets and returns values normally and prints a message logging their access. Descriptor Example: https://docs.python.org/3/howto/descriptor.html def __init__(self, initval=None, name='var'): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We first generate some random input points within a specified region using v.random (we use a fixed seed here for reproducibility) Step2: Workf...
<ASSISTANT_TASK:> Python Code: import os os.environ['GRASS_OVERWRITE'] = '1' import grass.script as gscript gscript.run_command('g.region', n=225200, s=222500, w=637500, e=640000, raster='elevation') gscript.run_command('v.random', output='input_points', npoints=20, seed=2, quiet=True) from grass.pygrass.vector.geome...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 量子卷积神经网络 Step2: 安装 TensorFlow Quantum: Step3: 现在,导入 TensorFlow 和模块依赖项: Step4: 1. 构建 QCNN Step5: 检查输入张量: Step6: 检查输出张量: Step8: 虽然不使用 tfq.la...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now, as data scientists we dont know this relationship between y and x. Rather we have collected observations of y. These observations are bound...
<ASSISTANT_TASK:> Python Code: # import libraries import matplotlib import IPython import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl import pylab import seaborn as sns import sklearn as sk %matplotlib inline # Ignore for now! x = np.array(np.linspace(0,10,400)) y = 10*x+3 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next get the login credentials Step2: Making requests Step3: Finding available cols/frags Step4: transcriptions Step5: The actual data looks...
<ASSISTANT_TASK:> Python Code: import sys, pprint, json try: import requests except ImportError: !conda install --yes --prefix {sys.prefix} requests import requests try: from genson import SchemaBuilder except ImportError: !conda install --yes --prefix {sys.prefix} genson from genson import...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The basics of generators Step2: Advanced uses of generators Step3: Generator.throw Step4: Generator.close Step5: Generators as suspendable/r...
<ASSISTANT_TASK:> Python Code: def range_generator_function(stop): Naive implementation of builtins.range generator. # This function runs immediately, since it has no `yield` statements. # It is a normal function, which happens to return a generator iterator. print("Running line 1") if not isinstanc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: one-liner equivalent Step2: The general form of list comprehension is Step3: which is equivalent to Step4: since this expression implements a...
<ASSISTANT_TASK:> Python Code: l = [] for i in range(10): l.append(2*i+1) l l = [2*i+1 for i in range(10)] l even = [n*n for n in range(20) if n % 2 == 0] even even = [] for n in range(20): if n % 2 == 0: even.append(n) even l = [1, 0, -2, 3, -1, -5, 0] signum_l = [int(n / abs(n)) if n != 0 else 0 f...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Download Necessary Models Step3: Example Step4: We can query all entities mentioned in a text. Step5: Or, we can query entites per sentence S...
<ASSISTANT_TASK:> Python Code: from polyglot.downloader import downloader print(downloader.supported_languages_table("ner2", 3)) %%bash polyglot download embeddings2.en ner2.en from polyglot.text import Text blob = The Israeli Prime Minister Benjamin Netanyahu has warned that Iran poses a "threat to the entire world"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Introduction to Fairness Indicators Step2: You must restart the Colab runtime after installing. Select Runtime > Restart runtime from the Colab...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Physical Data Step2: The IncidentNeutron class Step3: Cross sections Step4: Cross sections for each reaction can be stored at multiple temper...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os from pprint import pprint import shutil import subprocess import urllib.request import h5py import numpy as np import matplotlib.pyplot as plt import matplotlib.cm from matplotlib.patches import Rectangle import openmc.data openmc.data.atomic_mass('Fe54') ope...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If CPLEX is not installed, you can install CPLEX Community edition. Step2: 2. Model the data Step3: 3. Set up the prescriptive model Step4: W...
<ASSISTANT_TASK:> Python Code: import sys try: import docplex.mp except: raise Exception('Please install docplex. See https://pypi.org/project/docplex/') try: import cplex except: raise Exception('Please install CPLEX. See https://pypi.org/project/cplex/') B = [15, 15, 15] C = [ [ 6, 10, 1], [...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the data from the publication Step2: Create and fit a receptive field model Step3: Investigate model coefficients Step4: Create and fit ...
<ASSISTANT_TASK:> Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Nicolas Barascud <nicolas.barascud@ens.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from os.path import join impor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: .csv — Comma-Separated Values Step2: But there are more than just strings or rows with a single data type. We can use the csv library to handle...
<ASSISTANT_TASK:> Python Code: #pandas is commonly imported as pd import pandas as pd #We'll import the other libraries as needed print("Split on comma as strings") csv_row = '1,2.0,Three point five,True' print(csv_row.split(',')) print("\nSplit on comma and converted to ints") csv_row = '1,2,3,4,5,6,7,8,9' print([int...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modify the network a bit Step2: Add ramp limit Step3: Add additional storage units (cyclic and non-cyclic) and fix one state_of_charge Step4: ...
<ASSISTANT_TASK:> Python Code: import pypsa import pandas as pd import os n = pypsa.examples.ac_dc_meshed(from_master=True) n.generators.loc[n.generators.carrier == "gas", "p_nom_extendable"] = False n.generators.loc[n.generators.carrier == "gas", "ramp_limit_down"] = 0.2 n.generators.loc[n.generators.carrier == "gas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup of the current experiment Step2: Setup of the model priors Step3: Setup of the forecast Fisher matrix Step4: Running the main foxi algo...
<ASSISTANT_TASK:> Python Code: import sys path_to_foxi = '/Users/Rob/work/foxi' # Give your path to foxi here. sys.path.append(path_to_foxi + '/foxisource/') from foxi import foxi # These imports aren't stricly necessary to run foxi but they will be useful in our examples. import numpy as np from scipy.stats import mu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Train Step2: Predict Step4: Analyze
<ASSISTANT_TASK:> Python Code: from __future__ import division import re import numpy as np from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt %matplotlib inline #%qtconsole !rm train_ect.vw.cache !rm mnist_train_ect.model !vw -d data/mnist_train.vw -b 19 --ect 10 -f mnist_train_ect.model ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text...
<ASSISTANT_TASK:> Python Code: # If you'd like to download it through the command line... !curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz # And then extract it through the command line... !tar -zxf convote_v1.1.tar.gz # glob finds files matching a certain filename pattern import glob # Gi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 합성곱 신경망 Step2: MNIST 데이터셋 다운로드하고 준비하기 Step3: 합성곱 층 만들기 Step4: 지금까지 모델의 구조를 출력해 보죠. Step5: 위에서 Conv2D와 MaxPooling2D 층의 출력은 (높이, 너비, 채널) 크기의 3...
<ASSISTANT_TASK:> Python Code: #@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 writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading the Books Dataset Step2: Some Books don't have unique ISBN, creating a 1 Step3: Data Preparation/ Cleaning <br> Step4: Sampling <br> ...
<ASSISTANT_TASK:> Python Code: ratings = pd.read_csv('../raw-data/BX-Book-Ratings.csv', encoding='iso-8859-1', sep = ';') ratings.columns = ['user_id', 'isbn', 'book_rating'] print(ratings.dtypes) print() print(ratings.head()) print() print("Data Points :", ratings.shape[0]) books = pd.read_csv('../raw-data/BX-Books.c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: When read() receives no data from the socket, it interprets the read event as the other side of the connection being closed instead of sending d...
<ASSISTANT_TASK:> Python Code: # %load selectors_echo_server.py import selectors import socket mysel = selectors.DefaultSelector() keep_running = True def read(connection, mask): "Callback for read events" global keep_running client_address = connection.getpeername() print('read({})'.format(client_addre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: A simple function Step2: Using header files Step3: Notes Step4: A reusable Makefile Step5: Linking to a library Step6: Arrays, pointers and...
<ASSISTANT_TASK:> Python Code: %mkdir hello %cd hello %%file hello.cpp #include <iostream> using std::cout; using std::endl; int main() { cout << "Hello, world" << endl; } ! g++ hello.cpp -o hello ! ./hello %cd .. %mkdir add1 %cd add1 %%file add.cpp #include <iostream> using std::cout; using std::...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: $\langle \rho_{diffuse, cosmic}\rangle$ Step2: $\langle n_{e,cosmic}\rangle$ Step3: $\langle DM_{cosmic}\rangle$ Step4: $\langle DM_{halos}\r...
<ASSISTANT_TASK:> Python Code: # imports from importlib import reload import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline as IUS from astropy import units as u from frb.halos import ModifiedNFW from frb import halos as frb_halos from frb import igm as frb_igm from frb.figures import utils as f...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import TensorFlow and enable eager execution Step2: Load the dataset Step3: Use tf.data to create batches and shuffle the dataset Step4: Writ...
<ASSISTANT_TASK:> Python Code: # to generate gifs !pip install imageio from __future__ import absolute_import, division, print_function # Import TensorFlow >= 1.10 and enable eager execution import tensorflow as tf tf.enable_eager_execution() import os import time import numpy as np import glob import matplotlib.pyplo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Emulate the Distribution Step2: The diagram below is what our volume's max-intensity projection would look like if it were perfectly uniform. Q...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy import csv data = open('../data/data.csv', 'r').readlines() fieldnames = ['x', 'y', 'z', 'unmasked', 'synapses'] reader = csv.reader(data) reader.next() rows = [[int(col) for col in row] for row in reader] sorted_x = sor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Упражнение Step3: Что такое потоки? Step4: Упражнение Step5: Ipyparallel Step6: Примитивы синхронизации - мьютекс
<ASSISTANT_TASK:> Python Code: a = 1 b = 3 a + b a.__add__(b) type(a) isinstance(a, int) class Animal(object): mammal = True # class variable def __init__(self, name, voice, color="black"): self.name = name self.__voice = voice # "приватный" или "защищенный" атрибут self._col...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <u>Do preprocessing</u> Step2: Tokenize and load the corpus data Step3: Create a Hash Table for Probable words for Trigram sentences Step4: S...
<ASSISTANT_TASK:> Python Code: from nltk.util import ngrams from collections import defaultdict from collections import OrderedDict import string import time import gc start_time = time.time() #returns: string #arg: string #remove punctuations and make the string lowercase def removePunctuations(sen): #split the s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Linear Gaussian Models - The Process
<ASSISTANT_TASK:> Python Code: # from pgmpy.factors.continuous import LinearGaussianCPD import sys import numpy as np import pgmpy sys.path.insert(0, "../pgmpy/") from pgmpy.factors.continuous import LinearGaussianCPD mu = np.array([7, 13]) sigma = np.array([[4 , 3], [3 , 6]]) cpd = LinearGaussianCPD...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Define the flash LED task Step2: Create the task Step3: Monitoring the CPU Usage Step4: Run the event loop Step5: Clean up Step6: Now if we...
<ASSISTANT_TASK:> Python Code: from pynq import Overlay, PL from pynq.board import LED, Switch, Button Overlay('base.bit').download() buttons = [Button(i) for i in range(4)] leds = [LED(i) for i in range(4)] switches = [Switch(i) for i in range(2)] import asyncio @asyncio.coroutine def flash_led(num): while True: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From 1D to 2D acoustic finite difference modelling Step2: Comparison of 2D finite difference with analytical solution
<ASSISTANT_TASK:> Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) # Import Libraries # ---------------- import numpy as np import matplotlib import matplotlib.pyplot as plt from ...