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 |
|---|---|---|---|---|---|
モデルの登録 | import os
from azureml.core.model import Model
# Register model
model = Model.register(workspace = ws,
model_path = modelfilespath + '/model.pkl',
model_name = 'bankmarketing',
tags = {'automl': 'use generated file'},
descr... | Registering model bankmarketing
| MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
推論環境定義 | from azureml.core.environment import Environment
myenv = Environment.from_conda_specification(name = 'myenv',
file_path = modelfilespath + '/conda_env_v_1_0_0.yml')
myenv.register(workspace=ws) | _____no_output_____ | MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
推論環境設定 | from azureml.core.model import InferenceConfig
myenv = Environment.get(workspace=ws, name='myenv', version='1')
inference_config = InferenceConfig(entry_script= modelfilespath + '/scoring_file_v_1_0_0.py',
environment=myenv) | _____no_output_____ | MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
Azure Functions 用 イメージ作成HTTP Trigger 用:https://docs.microsoft.com/ja-jp/python/api/azureml-contrib-functions/azureml.contrib.functions?view=azure-ml-pypackage-http-workspace--models--inference-config--generate-dockerfile-false--auth-level-none- | from azureml.contrib.functions import package_http
httptrigger = package_http(ws, [model], inference_config, generate_dockerfile=True, auth_level=None)
httptrigger.wait_for_creation(show_output=True)
# Display the package location/ACR path
print(httptrigger.location) | Package creation Succeeded
https://dahatakeml5466187599.blob.core.windows.net/azureml/LocalUpload/d81db5dd-82ae-41fd-a56c-89010d382c36/build_context_manifest.json?sv=2019-02-02&sr=b&sig=ktxPIr5t%2F00E4lxDUQ4OjfiTxn00Yo0VfABY3BbQ4gQ%3D&st=2020-09-10T07%3A39%3A46Z&se=2020-09-10T15%3A49%3A46Z&sp=r
| MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
Scenario Analysis: Pop Up ShopKürschner (talk) 17:51, 1 December 2020 (UTC), CC0, via Wikimedia Commons | # install Pyomo and solvers for Google Colab
import sys
if "google.colab" in sys.modules:
!wget -N -q https://raw.githubusercontent.com/jckantor/MO-book/main/tools/install_on_colab.py
%run install_on_colab.py | _____no_output_____ | MIT | _build/jupyter_execute/notebooks/01/Pop-Up-Shop.ipynb | jckantor/MO-book |
The problemThere is an opportunity to operate a pop-up shop to sell a unique commemorative item for events held at a famous location. The items cost 12 € each and will selL for 40 €. Unsold items can be returned to the supplier at a value of only 2 € due to their commemorative nature.| Parameter | Symbo... | import numpy as np
import pandas as pd
# price information
r = 40
c = 12
w = 2
# scenario information
scenarios = {
"sunny skies" : {"probability": 0.10, "demand": 650},
"good weather": {"probability": 0.60, "demand": 400},
"poor weather": {"probability": 0.30, "demand": 200},
}
df = pd.DataFrame.from_di... | Expected demand = 365.0
| MIT | _build/jupyter_execute/notebooks/01/Pop-Up-Shop.ipynb | jckantor/MO-book |
Subsequent calculations can be done directly withthe pandas dataframe holding the scenario data. | df["order"] = expected_demand
df["sold"] = df[["demand", "order"]].min(axis=1)
df["salvage"] = df["order"] - df["sold"]
df["profit"] = r * df["sold"] + w * df["salvage"] - c * df["order"]
EVM = sum(df["probability"] * df["profit"])
print(f"Mean demand = {expected_demand}")
print(f"Expected value of the mean demand (E... | Mean demand = 365.0
Expected value of the mean demand (EVM) = 8339.0
| MIT | _build/jupyter_execute/notebooks/01/Pop-Up-Shop.ipynb | jckantor/MO-book |
Expected value of the stochastic solution (EVSS)The optimization problem is to find the order size $x$ that maximizes expected profit subject to operational constraints on the decision variables. The variables $x$ and $y_s$ are non-negative integers, while $f_s$ is a real number that can take either positive and negat... | import pyomo.environ as pyo
import pandas as pd
# price information
r = 40
c = 12
w = 2
# scenario information
scenarios = {
"sunny skies" : {"demand": 650, "probability": 0.1},
"good weather": {"demand": 400, "probability": 0.6},
"poor weather": {"demand": 200, "probability": 0.3},
}
# create model in... | Solver Termination Condition: optimal
Expected Profit: 8920.0
| MIT | _build/jupyter_execute/notebooks/01/Pop-Up-Shop.ipynb | jckantor/MO-book |
Optimizing over all scenarios provides an expected profit of 8,920 €, an increase of 581 € over the base case of simply ordering the expected number of items sold. The new solution places a larger order. In poor weather conditions there will be more returns and lower profit that is more than compensated by th... | import pyomo.environ as pyo
import pandas as pd
# price information
r = 40
c = 12
w = 2
# scenario information
scenarios = {
"sunny skies" : {"demand": 650, "probability": 0.1},
"good weather": {"demand": 400, "probability": 0.6},
"poor weather": {"demand": 200, "probability": 0.3},
}
# create model in... | Solver Termination Condition: optimal
Expected Profit: 10220.0
| MIT | _build/jupyter_execute/notebooks/01/Pop-Up-Shop.ipynb | jckantor/MO-book |
Copyright (c) 2014-2021 National Technology and Engineering Solutions of Sandia, LLC. Under the terms of Contract DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government retains certain rights in this software. Redistribution and use in source and binary forms, with or wi... | from tracktable.core import data_directory
import os.path
data_filename = os.path.join(data_directory(), 'NYHarbor_2020_06_30_first_hour.csv') | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Step 2: Create a TrajectoryPointReader object. We will create a Terrestrial point reader, which will expect **(longitude, latitude)** coordinates. Alternatively, if our data points were in a Cartesian coordinate system, we would import the `TrajectoryPointReader` object from `tracktable.domain.cartesian2d` or `trackt... | from tracktable.domain.terrestrial import TrajectoryPointReader
reader = TrajectoryPointReader() | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Step 3: Give the TrajectoryPointReader object info about the file. Have the reader open an input stream to the data file. | reader.input = open(data_filename, 'r') | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
*Additional Settings* Identify the comment character for the data file. Any lines with this as the first non-whitespace character will be ignored. This is optional and defaulted to ``. | reader.comment_character = '#' | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Identify the file's delimiter. For comma-separated (CSV) files, the delimiter should be set to `,`. For tab-separated files, this should be `\t`. This is optional, and the default value is `,`. | reader.field_delimiter = ',' | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Identify the string associated with a null value in a cell. This is optional and defaulted to an empty string. | reader.null_value = 'NaN' | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
*Required Columns* We must tell the reader where to find the **unique object ID**, **timestamp**, **longitude** and **latitude** columns. Column numbering starts at zero.If no column numbers are given, the reader will assume they are in the order listed above. Note that terrestrial points are stored as (longitude, l... | reader.object_id_column = 3
reader.timestamp_column = 0
reader.coordinates[0] = 1 # longitude
reader.coordinates[1] = 2 # latitude | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
*Optional Columns* Your data file may contain additional information (e.g. speed, heading, altitude, etc.) that you wish to store with your trajectory points. These can be stored as either floats, strings or datetime objects. An example of each is shown below, respectively. | reader.set_real_field_column('heading', 6)
reader.set_string_field_column('vessel-name', 7)
reader.set_time_field_column('eta', 17) | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Step 4: Convert the Reader to a List of Trajectory Points | trajectory_points = list(reader) | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
How many trajectory points do we have? | len(trajectory_points) | _____no_output_____ | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Step 5: Accessing Trajectory Point Info The information from the required columns of the csv can be accessed for a single `trajectory_point` object as* **unique object identifier:** `trajectory_point.object_id`* **timestamp:** `trajectory_point.timestamp`* **longitude:** `trajectory_point[0]`* **latitude:** `trajector... | for traj_point in trajectory_points[:10]:
object_id = traj_point.object_id
timestamp = traj_point.timestamp
longitude = traj_point[0]
latitude = traj_point[1]
heading = traj_point.properties["heading"]
vessel_name = traj_point.properties["vessel-name"]
eta = traj_... | Unique ID: 367000140
Timestamp: 2020-06-30 00:00:00+00:00
Longitude: -74.07157
Latitude: 40.64409
Heading: 246.0
Vessel Name: SAMUEL I NEWHOUSE
ETA: 2020-06-30 12:01:00+00:00
Unique ID: 366999618
Timestamp: 2020-06-30 00:00:00+00:00
Longitude: -74.02433
Latitude: 40.54291
Heading: 349.0
Vessel Name: CG SHRIKE
ETA: 202... | Unlicense | tutorial_notebooks/Tutorial_01.ipynb | sandialabs/tracktable-docs |
Optimization of a Voigt profile | from exojax.spec.rlpf import rvoigt
import jax.numpy as jnp
import matplotlib.pyplot as plt | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Let's optimize the Voigt function $V(\nu, \beta, \gamma_L)$ using exojax!$V(\nu, \beta, \gamma_L)$ is a convolution of a Gaussian with a STD of $\beta$ and a Lorentian with a gamma parameter of $\gamma_L$. Note that we use spec.rlpf.rvoigt instead of spec.voigt. This function is a voigt profile with VJP while voigt is ... | nu=jnp.linspace(-10,10,100)
plt.plot(nu, rvoigt(nu,1.0,2.0)) #beta=1.0, gamma_L=2.0 | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
optimization of a simple absorption model Next, we try to fit a simple absorption model to mock data.The absorption model is $ f= 1 - e^{-a V(\nu,\beta,\gamma_L)}$ | def absmodel(nu,a,beta,gamma_L):
return 1.0 - jnp.exp(a*rvoigt(nu,beta,gamma_L)) | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Adding a noise... | from numpy.random import normal
data=absmodel(nu,2.0,1.0,2.0)+normal(0.0,0.01,len(nu))
plt.plot(nu,data,".") | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Let's optimize the multiple parameters | from jax import grad, vmap | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
We define the objective function as $obj = |d - f|^2$ | # loss or objective function
def obj(a,beta,gamma_L):
f=data-absmodel(nu,a,beta,gamma_L)
g=jnp.dot(f,f)
return g
#These are the derivative of the objective function
h_a=grad(obj,argnums=0)
h_beta=grad(obj,argnums=1)
h_gamma_L=grad(obj,argnums=2)
print(h_a(2.0,1.0,2.0),h_beta(2.0,1.0,2.0),h_gamma_L(2.0,1.0,... | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Here, we use the ADAM optimizer | #adam
from jax.experimental import optimizers
opt_init, opt_update, get_params = optimizers.adam(1.e-1)
r0 = jnp.array([1.5,1.5,1.5])
trajadam, padam=doopt(r0,opt_init,get_params,1000) | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Optimized values are given in padam | padam
traj=jnp.array(trajadam)
plt.plot(traj[:,0],label="$\\alpha$")
plt.plot(traj[:,1],ls="dashed",label="$\\beta$")
plt.plot(traj[:,2],ls="dotted",label="$\\gamma_L$")
plt.xscale("log")
plt.legend()
plt.show()
plt.plot(nu,data,".",label="data")
plt.plot(nu,absmodel(nu,padam[0],padam[1],padam[2]),label="optimized")
pl... | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Using SGD instead..., you need to increase the number of iteration for convergence | #sgd
from jax.experimental import optimizers
opt_init, opt_update, get_params = optimizers.sgd(1.e-1)
r0 = jnp.array([1.5,1.5,1.5])
trajsgd, psgd=doopt(r0,opt_init,get_params,10000)
traj=jnp.array(trajsgd)
plt.plot(traj[:,0],label="$\\alpha$")
plt.plot(traj[:,1],ls="dashed",label="$\\beta$")
plt.plot(traj[:,2],ls="dott... | _____no_output_____ | MIT | examples/tutorial/optimize_voigt.ipynb | ykawashima/exojax |
Machine Learning Trading BotIn this Challenge, you’ll assume the role of a financial advisor at one of the top five financial advisory firms in the world. Your firm constantly competes with the other major firms to manage and automatically trade assets in a highly dynamic environment. In recent years, your firm has he... | # Imports
import pandas as pd
import numpy as np
from pathlib import Path
import hvplot.pandas
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn import metrics
from sklearn.ensemble import AdaBoostClassifier
from sklearn.preprocessing import StandardScaler
from pandas.tseries.offsets import DateOffse... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
--- Establish a Baseline PerformanceIn this section, you’ll run the provided starter code to establish a baseline performance for the trading algorithm. To do so, complete the following steps.Open the Jupyter notebook. Restart the kernel, run the provided cells that correspond with the first three steps, and then proce... | # Import the OHLCV dataset into a Pandas Dataframe
ohlcv_df = pd.read_csv(
Path("./Resources/emerging_markets_ohlcv.csv"),
index_col='date',
infer_datetime_format=True,
parse_dates=True
)
# Review the DataFrame
ohlcv_df.head()
# Filter the date index and close columns
signals_df = ohlcv_df.loc[:, ["... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 2: Generate trading signals using short- and long-window SMA values. | # Set the short window and long window
short_window = 4
long_window = 100
# Generate the fast and slow simple moving averages (4 and 100 days, respectively)
signals_df['SMA_Fast'] = signals_df['close'].rolling(window=short_window).mean()
signals_df['SMA_Slow'] = signals_df['close'].rolling(window=long_window).mean()
... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 3: Split the data into training and testing datasets. | # Assign a copy of the sma_fast and sma_slow columns to a features DataFrame called X
X = signals_df[['SMA_Fast', 'SMA_Slow']].shift().dropna()
# Review the DataFrame
X.head()
# Create the target set selecting the Signal column and assiging it to y
y = signals_df['Signal']
# Review the value counts
y.value_counts()
#... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 4: Use the `SVC` classifier model from SKLearn's support vector machine (SVM) learning method to fit the training data and make predictions based on the testing data. Review the predictions. | # From SVM, instantiate SVC classifier model instance
svm_model = svm.SVC()
# Fit the model to the data using the training data
svm_model = svm_model.fit(X_train_scaled, y_train)
# Use the testing data to make the model predictions
svm_pred = svm_model.predict(X_test_scaled)
# Review the model's predicted values
s... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 5: Review the classification report associated with the `SVC` model predictions. | # Use a classification report to evaluate the model using the predictions and testing data
svm_testing_report = classification_report(y_test, svm_pred)
# Print the classification report
print(svm_testing_report) | precision recall f1-score support
-1.0 0.43 0.04 0.07 1804
1.0 0.56 0.96 0.71 2288
accuracy 0.55 4092
macro avg 0.49 0.50 0.39 4092
weighted avg 0.50 0.55 0.43 ... | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 6: Create a predictions DataFrame that contains columns for “Predicted” values, “Actual Returns”, and “Strategy Returns”. | # Create a new empty predictions DataFrame.
# Create a predictions DataFrame
predictions_df = pd.DataFrame(index=X_test.index)
# Add the SVM model predictions to the DataFrame
predictions_df['Predicted'] = svm_pred
# Add the actual returns to the DataFrame
predictions_df['Actual Returns'] = signals_df['Actual Return... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 7: Create a cumulative return plot that shows the actual returns vs. the strategy returns. Save a PNG image of this plot. This will serve as a baseline against which to compare the effects of tuning the trading algorithm. | # Plot the actual returns versus the strategy returns
baseline_actual_vs_stragegy_plot = (1 + predictions_df[['Actual Returns', 'Strategy Returns']]).cumprod().plot(title="Baseline")
baseline_actual_vs_stragegy_plot.get_figure().savefig('Baseline_actual_vs_strategy.png',bbox_inches='tight')
(1 + predictions_df[['Actual... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
--- Tune the Baseline Trading Algorithm Step 6: Use an Alternative ML Model and Evaluate Strategy Returns In this section, you’ll tune, or adjust, the model’s input features to find the parameters that result in the best trading outcomes. You’ll choose the best by comparing the cumulative products of the strategy retu... | # Initiate the model instance
abc = AdaBoostClassifier(n_estimators=50)
| _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 2: Using the original training data as the baseline model, fit another model with the new classifier. | # Fit the model using the training data
model = abc.fit(X_train_scaled, y_train)
# Use the testing dataset to generate the predictions for the new model
abc_pred = model.predict(X_test_scaled)
# Review the model's predicted values
abc_pred[:10]
| _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
Step 3: Backtest the new model to evaluate its performance. Save a PNG image of the cumulative product of the actual returns vs. the strategy returns for this updated trading algorithm, and write your conclusions in your `README.md` file. Answer the following questions: Did this new model perform better or worse than ... | print("Accuracy:",metrics.accuracy_score(y_test, abc_pred))
# Use a classification report to evaluate the model using the predictions and testing data
abc_testing_report = classification_report(y_test, abc_pred)
# Print the classification report
print(abc_testing_report)
# Create a new empty predictions DataFrame.
a... | _____no_output_____ | MIT | machine_learning_trading_bot.ipynb | djonathan/Algorithmic-Trading-ML |
You can build rlambda objects using any python arithmetic, comparision and bitwise operators. Here are some examples... | from rlambda.abc import x, y, z
print((x + 1) + (y - 1) / z)
print((x % 2) // y + z ** 2)
print((x + 1) ** 2 > (y * 2))
print(x != y)
print(x ** 2 == y)
print((x > y) & (y > z))
print((x < 0) | (y < 0))
print(~(x > 0) ^ ~(y > 0))
print((x << 1) + (y >> 1)) | x, y, z : (x > y) & (y > z)
x, y : (x < 0) | (y < 0)
x, y : ~(x > 0) ^ ~(y > 0)
x, y : (x << 1) + (y >> 1)
| MIT | docs/operations.ipynb | Vykstorm/rlambda |
You can use subscripting and indexing operations... | print(x[2:] + y[:2])
print(x[::2] + y[1::2])
print(x[1, 0:2])
f = x.imag ** 2 + x.real * 2
print(f)
f(complex(1, 2))
| _____no_output_____ | MIT | docs/operations.ipynb | Vykstorm/rlambda |
Getting started with the Google Genomics API In this notebook we'll cover how to make authenticated requests to the [Google Genomics API](https://cloud.google.com/genomics/reference/rest/).----NOTE:* If you're new to notebooks, or want to check out additional samples, check out the full [list](../) of general notebook... | !pip install --upgrade google-api-python-client | Requirement already up-to-date: google-api-python-client in /usr/local/lib/python2.7/dist-packages
Cleaning up...
| Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Create an Authenticated Client Next we construct a Python object that we can use it to make requests. The following snippet shows how we can authenticate using the service account on the Datalab host. For more detail about authentication from Python, see [Using OAuth 2.0 for Server to Server Applications](https://dev... | from httplib2 import Http
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
http = Http()
credentials.authorize(http)
| _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
And then we create a client for the Genomics API. | from apiclient.discovery import build
genomics = build('genomics', 'v1', http=http) | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Send a request to the Genomics API Now that we have a Python client for the Genomics API, we can access a variety of different resources. For details about each available resource, see the python client [API docs here](https://google-api-client-libraries.appspot.com/documentation/genomics/v1/python/latest/index.html).... | request = genomics.datasets().get(datasetId='10473108253681171589') | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Next, we'll send this request to the Genomics API by calling the `request.execute()` method. | response = request.execute() | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
You will need enable the Genomics API for your project if you have not done so previously. Click on [this link](https://console.developers.google.com/flows/enableapi?apiid=genomics) to enable the API in your project. The response object returned is simply a Python dictionary. Let's take a look at the properties return... | for entry in response.items():
print "%s => %s" % entry | projectId => genomics-public-data
id => 10473108253681171589
createTime => 1970-01-01T00:00:00.000Z
name => 1000 Genomes
| Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Success! We can see the name of the specified Dataset and a few other pieces of metadata.Accessing other Genomics API resources will follow this same set of steps. The full [list of available resources within the API is here](https://google-api-client-libraries.appspot.com/documentation/genomics/v1/python/latest/index.... | dataset_id = '10473108253681171589' # This is the 1000 Genomes dataset ID
sample = 'NA12872'
reference_name = '22'
reference_position = 51003835 | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Get read bases for a sample at specific a position First find the read group set ID for the sample. | request = genomics.readgroupsets().search(
body={'datasetIds': [dataset_id], 'name': sample},
fields='readGroupSets(id)')
read_group_sets = request.execute().get('readGroupSets', [])
if len(read_group_sets) != 1:
raise Exception('Searching for %s didn\'t return '
'the right number of read group ... | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Once we have the read group set ID, lookup the reads at the position in which we are interested. | request = genomics.reads().search(
body={'readGroupSetIds': [read_group_set_id],
'referenceName': reference_name,
'start': reference_position,
'end': reference_position + 1,
'pageSize': 1024},
fields='alignments(alignment,alignedSequence)')
reads = request.execute().get('alignments',... | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
And we print out the results. | # Note: This is simplistic - the cigar should be considered for real code
bases = [read['alignedSequence'][
reference_position - int(read['alignment']['position']['position'])]
for read in reads]
print '%s bases on %s at %d are' % (sample, reference_name, reference_position)
from collections impor... | NA12872 bases on 22 at 51003835 are
C: 1
G: 13
| Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Get variants for a sample at specific a position First find the call set ID for the sample. | request = genomics.callsets().search(
body={'variantSetIds': [dataset_id], 'name': sample},
fields='callSets(id)')
resp = request.execute()
call_sets = resp.get('callSets', [])
if len(call_sets) != 1:
raise Exception('Searching for %s didn\'t return '
'the right number of call sets' % sample)
c... | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Once we have the call set ID, lookup the variants that overlap the position in which we are interested. | request = genomics.variants().search(
body={'callSetIds': [call_set_id],
'referenceName': reference_name,
'start': reference_position,
'end': reference_position + 1},
fields='variants(names,referenceBases,alternateBases,calls(genotype))')
variant = request.execute().get('variants', [])[0] | _____no_output_____ | Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
And we print out the results. | variant_name = variant['names'][0]
genotype = [variant['referenceBases'] if g == 0
else variant['alternateBases'][g - 1]
for g in variant['calls'][0]['genotype']]
print 'the called genotype is %s for %s' % (','.join(genotype), variant_name) | the called genotype is G,G for rs131767
| Apache-2.0 | datalab/genomics/Getting started with the Genomics API.ipynb | googlegenomics/datalab-examples |
Question 4 | df = pd.read_csv('data-hw2.csv')
df
plt.figure(figsize=(8,8))
plt.scatter(df['LUNG'], df['CIG'])
plt.xlabel("LUNG DEATHS")
plt.ylabel("CIG SALES")
plt.title("Scatter plot of Lung Cancer Deaths vs. Cigarette Sales")
for i in range(len(df)):
plt.annotate(df.iloc[i]['STATE'], xy=(df.iloc[i]['LUNG'], df.iloc[i]['CIG'])... | _____no_output_____ | MIT | HW2/HW2.ipynb | kaahanmotwani/CS361 |
Question 5 | df_ko = pd.read_csv('KO.csv')
df_pep = pd.read_csv('PEP.csv')
del df_ko['Open'], df_ko['High'], df_ko['Low'], df_ko['Close'], df_ko['Volume']
del df_pep['Open'], df_pep['High'], df_pep['Low'], df_pep['Close'], df_pep['Volume']
df_comb = pd.DataFrame(columns=["Date", "KO Adj Close", "PEP Adj Close"])
df_comb["Date"] = d... | _____no_output_____ | MIT | HW2/HW2.ipynb | kaahanmotwani/CS361 |
Setup | from google.colab import drive
drive.mount('/content/drive')
!ls /content/drive/MyDrive/ColabNotebooks/Transformer
!nvcc --version
!pip3 install timm faiss tqdm numpy
!pip3 install torch==1.10.2+cu113 torchvision==0.11.3+cu113 torchaudio==0.10.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
!sudo a... | /content/drive/.shortcut-targets-by-id/19RweVltTTlScqIDv6lHIQzlQezjmyFBN/ColabNotebooks/Transformer/LA-Transformer
| MIT | Transformer/LA_Transformer_Oneshot_clean.ipynb | McStevenss/reid-keras-padel |
Testing | from __future__ import print_function
import os
import time
import glob
import random
import zipfile
from itertools import chain
import timm
import numpy as np
import pandas as pd
from PIL import Image
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
from collections import OrderedDict
from sklearn.mode... | torch.__version__ = 1.10.2+cu113
torch.cuda.is_available() = True
torch.cuda.current_device() = 0
torch.cuda.device(0) = <torch.cuda.device object at 0x00000256EC04E2C8>
torch.cuda.device_count() = 1
torch.cuda.get_device_name(0) = NVIDIA GeForce GTX 1080
| MIT | Transformer/LA_Transformer_Oneshot_clean.ipynb | McStevenss/reid-keras-padel |
Load Model | batch_size = 8
gamma = 0.7
seed = 42
# Load ViT
vit_base = timm.create_model('vit_base_patch16_224', pretrained=True, num_classes=50)
vit_base= vit_base.to(device)
# Create La-Transformer
osprey_model = LATransformerTest(vit_base, lmbd=8).to(device)
# Load LA-Transformer
# name = "la_with_lmbd_8"
# name = "la_with_l... | E:\Anaconda\envs\py37\lib\site-packages\torchvision\transforms\transforms.py:288: UserWarning: Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum.
"Argument interpolation should be of type InterpolationMode instead of int. "
| MIT | Transformer/LA_Transformer_Oneshot_clean.ipynb | McStevenss/reid-keras-padel |
Required functions |
# device = initilize_device("cpu")
# We had to recreate the get_id() func since they assume the pictures are named in a specific manner.
def get_id_padel(img_path):
labels = []
for path, v in img_path:
filename = os.path.basename(path)
label = filename.split('_')[0]
labels.append(int(label))
... | _____no_output_____ | MIT | Transformer/LA_Transformer_Oneshot_clean.ipynb | McStevenss/reid-keras-padel |
odoijadsoijas | #query_loader, gallery_loader, image_datasets = image_loader(data_dir_path="data/The_OspreyChallengerSet")
#load images from folder
query_loader, gallery_loader, image_datasets = image_loader(data_dir_path="data/bim_bam")
#extract features
query_feature, gallery_feature = feature_extraction(model=osprey_model, quer... | Correct: 1, Total: 1, Incorrect: 0
Correct: 2, Total: 2, Incorrect: 0
Rank1: 1.0, Rank5: 1.0, Rank10: 1.0, mAP: 0.6766666666666666
| MIT | Transformer/LA_Transformer_Oneshot_clean.ipynb | McStevenss/reid-keras-padel |
The Chain at a Fixed Time Let $X_0, X_1, X_2, \ldots $ be a Markov Chain with state space $S$. We will start by setting up notation that will help us express our calculations compactly.For $n \ge 0$, let $P_n$ be the distribution of $X_n$. That is,$$P_n(i) = P(X_n = i), ~~~~ i \in S$$Then the distribution of $X_0$ is ... | s = np.arange(1, 6)
p = [1, 0, 0, 0, 0]
initial = Table().states(s).probability(p)
initial | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
The transition probabilities are:- For $2 \le i \le 4$, $P(i, i) = 0.5$ and $P(i, i-1) = 0.25 = P(i, i+1)$. - $P(1, 1) = 0.5$ and $P(1, 5) = 0.25 = P(1, 2)$.- $P(5, 5) = 0.5$ and $P(5, 4) = 0.25 = P(5, 1)$.These probabilities are returned by the function `circle_walk_probs` that takes states $i$ and $j$ as its argument... | def circle_walk_probs(i, j):
if i-j == 0:
return 0.5
elif abs(i-j) == 1:
return 0.25
elif abs(i-j) == 4:
return 0.25
else:
return 0 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
All the transition probabilities can be captured in a table, in a process analogous to creating a joint distribution table. | trans_tbl = Table().states(s).transition_function(circle_walk_probs)
trans_tbl | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
Just as when we were constructing joint distribution tables, we can better visualize this as a $5 \times 5$ table: | circle_walk = trans_tbl.toMarkovChain()
circle_walk | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
This is called the *transition matrix* of the chain. - For each $i$ and $j$, the $(i, j)$ element of the transition matrix is the one-step transition probability $P(i, j)$.- For each $i$, the $i$th row of the transition matrix consists of the conditional distribution of $X_{n+1}$ given $X_n = i$. Probability of a Path... | circle_walk.prob_of_path(initial, [1, 1, 2, 1, 2]) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
Distribution of $X_n$ Remember that the chain starts at 1. So $P_0$, the distribution of $X_0$ is: | initial | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
We know that $P_1$ must place probability 0.5 at Point 1 and 0.25 each the points 2 and 5. This is confirmed by the `distribution` method that applies to a MarkovChain object. Its first argument is the initial distribution, and its second is the number of steps $n$. It returns a distribution object that is the distribu... | P_1 = circle_walk.distribution(initial, 1)
P_1 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
What's the probability that the chain is has value 3 at time 2? That's $P_2(3)$ which we can calculate by conditioning on $X_1$:$$P_2(3) = \sum_{i=1}^5 P_1(i)P(i, 3)$$The distribution of $X_1$ is $P_1$, given above. Here are those probabilities in an array: | P_1.column('Probability') | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
The `3` column of the transition matrix gives us, for each $i$, the chance of getting from $i$ to 3 in one step. | circle_walk.column('3') | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
So the probability that the chain has the value 3 at time 2 is $P_2(3)$ which is equal to: | sum(P_1.column('Probability')*circle_walk.column('3')) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
Similarly, $P_2(2)$ is equal to: | sum(P_1.column('Probability')*circle_walk.column('2')) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
And so on. The `distribution` method finds all these probabilities for us. | P_2 = circle_walk.distribution(initial, 2)
P_2 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
At time 3, the chain continues to be much more likely to be at 1, 2, or 5 compared to the other two states. That's because it started at Point 1 and is lazy. | P_3 = circle_walk.distribution(initial, 3)
P_3 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
But by time 10, something interesting starts to emerge. | P_10 = circle_walk.distribution(initial, 10)
P_10 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
The chain is almost equally likely to be at any of the five states. By time 50, it seems to have completely forgotten where it started, and is distributed uniformly on the state space. | P_50 = circle_walk.distribution(initial, 50)
P_50 | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
As time passes, this chain gets "all mixed up", regardless of where it started. That is perhaps not surprising as the transition probabilities are symmetric over the five states. Let's see what happens when we cut the circle between Points 1 and 5 and lay it out in a line. Reflecting Random Walk The state space and tr... | def ref_walk_probs(i, j):
if i-j == 0:
return 0.5
elif 2 <= i <= 4:
if abs(i-j) == 1:
return 0.25
else:
return 0
elif i == 1:
if j == 2:
return 0.5
else:
return 0
elif i == 5:
if j == 4:
return 0.... | Transition Matrix
| MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
Let the chain start at Point 1 as it did in the last example. That initial distribution was defined as `initial`. At time 1, therefore, the chain is either at 1 or 2, and at times 2 and 3 it is likely to still be around 1. | refl_walk.distribution(initial, 1)
refl_walk.distribution(initial, 3) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
But by time 20, the distribution is settling down: | refl_walk.distribution(initial, 20) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
And by time 100 it has settled into what is called its *steady state*. | refl_walk.distribution(initial, 100) | _____no_output_____ | MIT | miscellaneous_notebooks/Markov_Chains/Chain_at_a_Fixed_Time.ipynb | dcroce/jupyter-book |
Twitter Sentiment Analysis | import twitter
import pandas as pd
import numpy as np | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Source https://towardsdatascience.com/creating-the-twitter-sentiment-analysis-program-in-python-with-naive-bayes-classification-672e5589a7ed Authenticating Twitter API | # Authenticating our twitter API credentials
twitter_api = twitter.Api(consumer_key='f2ujCRaUnQJy4PoiZvhRQL4n4',
consumer_secret='EjBSQirf7i83T7CX90D5Qxgs9pTdpIGIsVAhHVs5uvd0iAcw5V',
access_token_key='1272989631404015616-5XMQkx65rKfQU87UWAh40cMf4aCzSq',
... | {"created_at": "Tue Jun 16 20:29:26 +0000 2020", "default_profile": true, "default_profile_image": true, "id": 1272989631404015616, "id_str": "1272989631404015616", "name": "Nicola Osrin", "profile_background_color": "F5F8FA", "profile_image_url": "http://abs.twimg.com/sticky/default_profile_images/default_profile_norm... | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Building the Test Set | #We first build the test set, consisting of only 100 tweets for simplicity.
#Note that we can only download 180 tweets every 15min.
def buildTestSet(search_keyword):
try:
tweets_fetched = twitter_api.GetSearch(search_keyword, count = 100)
print("Fetched " + str(len(tweets_fetched)) + " twe... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Building the Training Set We will be using a downloadable training set, consisting of 5,000 tweets. These tweets have already been labelled as positive/negative. We use this training set to calculate the posterior probabilities of each word appearing and its respective sentiment. | #As Twitter doesn't allow the storage of the tweets on personal drives, we have to create a function to download
#the relevant tweets that will be matched to the Tweet IDs and their labels, which we have.
def buildTrainingSet(corpusFile, tweetDataFile, size):
import csv
import time
count = 0
corpu... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Pre-processing Here we use the NLTK library to filter for keywords and remove irrelevant words in tweets. We also remove punctuation and things like images (emojis) as they cannot be classified using this model. | import re #a library that makes parsing strings and modifying them more efficient
from nltk.tokenize import word_tokenize
from string import punctuation
from nltk.corpus import stopwords
import nltk #Natural Processing Toolkit that takes care of any processing that we need to perform on text
#to change i... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Building the Naive Bayes Classifier We apply a classifier based on Bayes' Theorem, hence the name. It allows us to find the posterior probability of an event occuring (in this case that event being the sentiment- positive/neutral or negative) is reliant on another probabilistic background that we know. The posterior p... | #Here we attempt to build a vocabulary (a list of words) of all words present in the training set.
import nltk
def buildVocabulary(preprocessedTrainingData):
all_words = []
for (words, sentiment) in preprocessedTrainingData:
all_words.extend(words)
wordlist = nltk.FreqDist(all_words)
wo... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Matching tweets against our vocabulary Here we go through all the words in the training set (i.e. our word_features list), comparing every word against the tweet at hand, associating a number with the word following:label 1 (true): if word in vocabulary occurs in tweetlabel 0 (false): if word in vocabulary does not oc... | def extract_features(tweet):
tweet_words = set(tweet)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in tweet_words)
return features | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Building our feature vector | word_features = buildVocabulary(preprocessedTrainingSet)
trainingFeatures = nltk.classify.apply_features(extract_features, preprocessedTrainingSet) | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
This feature vector shows if a particular tweet contains a certain word out of all the words present in the corpus in the training data + label (positive, negative or neutral) of the tweet.We will input the feature vector in the Naive Bayes Classifier, which will calculate the posterior probability given the prior prob... | #This line trains our Bayes Classifier
NBayesClassifier = nltk.NaiveBayesClassifier.train(trainingFeatures)
| _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
Test Classifier | #We now run the classifier and test it on 100 tweets previously downloaded in the test set, on our specified keyword.
NBResultLabels = [NBayesClassifier.classify(extract_features(tweet[0])) for tweet in preprocessedTestSet]
# get the majority vote
if NBResultLabels.count('positive') > NBResultLabels.count('negative')... | _____no_output_____ | MIT | .ipynb_checkpoints/sentiment_analysis_twitter_comments-checkpoint.ipynb | adrientalbot/twitter-sentiment-training |
This script is to map 2012 galway traffic data (bridge 1) | #python list to store csv data as mapping suggest
#Site No Dataset Survey Company Client Project Reference Method of Survey Address Latitude Longtitude Easting Northing Date From Date To Time From Time To Observations Weather Junction Type Vehicle Type Direction Count
#Site No,Dataset,Survey Company,Client,Project Refe... | ['Date From', 'Time', 'Total', 'Bin 1', 'Bin 1', 'Bin 2', 'Bin 2', 'Bin 3', 'Bin 3', 'Bin 4', 'Bin 4', 'Bin 5', 'Bin 5', 'dir']
['12/11/12', 'Begin', 'Vol.', 'Motorcycles', '%', 'Cars', '%', 'LGV', '%', 'HGV', '%', 'Buses', '%', 'Eastbound']
['12/11/12', '00:00', '98', '1', '1.02', '92', '93.88', '3', '3.06', '2', '2.0... | MIT | yds_mapping_2012_ds.ipynb | mohadelrezk/open-gov-DataHandling-traffic |
Data Preperation for the first ModelWelcome to the first notebook. Here we'll process the data from downloading to what we will be using to train our first model - **'Wh’re Art Thee Min’ral?'**.The steps we'll be following here are:- Downloading the SARIG Geochem Data Package. **(~350 Mb)**- Understanding the data col... | # import the required package - Pandas
import pandas as pd | _____no_output_____ | MIT | models/Model1/Mod1_Data_Prep.ipynb | Xavian-Brooker/Gawler-Unearthed |
You can simply download the data by clicking the link [here](https://unearthed-exploresa.s3-ap-southeast-2.amazonaws.com/Unearthed_5_SARIG_Data_Package.zip). You can also download it by simply running the cell down below.We recommed you to use **Google Colab** and download it here itself if you have a poor internet con... | # You can simply download the data by running this cell
!wget https://unearthed-exploresa.s3-ap-southeast-2.amazonaws.com/Unearthed_5_SARIG_Data_Package.zip | --2020-07-26 10:57:12-- https://unearthed-exploresa.s3-ap-southeast-2.amazonaws.com/Unearthed_5_SARIG_Data_Package.zip
Resolving unearthed-exploresa.s3-ap-southeast-2.amazonaws.com (unearthed-exploresa.s3-ap-southeast-2.amazonaws.com)... 52.95.128.54
Connecting to unearthed-exploresa.s3-ap-southeast-2.amazonaws.com (u... | MIT | models/Model1/Mod1_Data_Prep.ipynb | Xavian-Brooker/Gawler-Unearthed |
Here for extracting, if you wish to use the download file for a later use, than you can first mount your google drive and then extracting the files there. You can read more about mounting Google Drive to colab [here](https://towardsdatascience.com/downloading-datasets-into-google-drive-via-google-colab-bcb1b30b0166).**... | # Let's first create a directory to extract the downloaded zip file.
!mkdir 'GeoChemData'
# Now let's unzip the files into the data directory that we created.
!unzip 'Unearthed_5_SARIG_Data_Package.zip' -d 'GeoChemData/'
# Read the df_details.csv
# We use unicode_escape as the encoding to avoid etf-8 error.
df_detail... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 321843 entries, 0 to 321842
Data columns (total 51 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 DRILLHOLE_NO 321843 non-null int64
1 DH_NAME 19... | MIT | models/Model1/Mod1_Data_Prep.ipynb | Xavian-Brooker/Gawler-Unearthed |
What columns do we need?We only need the following three columns from this dataframe ->- `LONGITUDE_GDA94`: This is the longitude of the mine/mineral location in **EPSG:4283** Co-ordinate Referencing System (CRS). - `LATITUDE_GDA94`: This is the latitude of the mine/mineral location in **EPSG:4283** Co-ordinate Refere... | # Here the only relevant data we need is the location and the Mineral Class (Yes/No)
df_final = df_details[['LONGITUDE_GDA94','LATITUDE_GDA94', 'MINERAL_CLASS']]
# Drop the rows with null values
df_final = df_final.dropna()
# Lets print out a few rows of the new dataframe.
df_final.head()
# Let's check the data point... | Number of rows with Mineral Class Yes is 147407
Number of rows with Mineral Class No is 174436
| MIT | models/Model1/Mod1_Data_Prep.ipynb | Xavian-Brooker/Gawler-Unearthed |
The Total Number of rows in the new dataset is **147407 (Y) + 174436 (N) = 321843** which is quite sufficient for training our models over it.Also the ratio of Class `'Y'` to Class `'N'` is 1 : 0.8 which is quite _**balanced**_. Now that we have our csv, let's g... | # Create a new directory to save the csv.
!mkdir 'GeoChemData/exported'
# Convert the dataframe into a new csv file.
df_final.to_csv('GeoChemData/mod1_unsampled.csv')
# Finally if you are on google colab, you can simply download using ->
from google.colab import files
files.download('GeoChemData/exported/mod1_vectors.... | _____no_output_____ | MIT | models/Model1/Mod1_Data_Prep.ipynb | Xavian-Brooker/Gawler-Unearthed |
Hyperopt Iris 数据集 在本节中,我们将介绍4个使用hyperopt在经典数据集 Iris 上调参的完整示例。我们将涵盖 K 近邻(KNN),支持向量机(SVM),决策树和随机森林。 对于这项任务,我们将使用经典的Iris数据集,并进行一些有监督的机器学习。数据集有有4个输入特征和3个输出类别。数据被标记为属于类别0,1或2,其映射到不同种类的鸢尾花。输入有4列:萼片长度,萼片宽度,花瓣长度和花瓣宽度。输入的单位是厘米。我们将使用这4个特征来学习模型,预测三种输出类别之一。因为数据由sklearn提供,它有一个很好的DESCR属性,可以提供有关数据集的详细信息。尝试以下代码以获得更多细节信息 | from sklearn import datasets
iris = datasets.load_iris()
print(iris.feature_names) # input names
print(iris.target_names) # output names
print(iris.DESCR) # everything else | ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
['setosa' 'versicolor' 'virginica']
.. _iris_dataset:
Iris plants dataset
--------------------
**Data Set Characteristics:**
:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive ... | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
K-means 我们现在将使用hyperopt来找到 K近邻(KNN)机器学习模型的最佳参数。KNN 模型是基于训练数据集中 k 个最近数据点的大多数类别对来自测试集的数据点进行分类。 | from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
import matplotlib.pyplot as plt
import numpy as np, pandas as pd
from math import *
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
# 数据集导入
iris = datasets.load_iris()
X = iris.data... | 100%|█| 100/100 [00:02<00:00, 34.95it/s, best loss: -0.98000000
best: {'n_neighbors': 11}
trials:
{'state': 2, 'tid': 0, 'spec': None, 'result': {'loss': -0.9666666666666668, 'status': 'ok'}, 'misc': {'tid': 0, 'cmd': ('domain_attachment', 'FMinIter_Domain'), 'workdir': None, 'idxs': {'n_neighbors': [0]}, 'vals': {'n_n... | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
现在让我们看看输出结果的图。y轴是交叉验证分数,x轴是 k 近邻个数。下面是代码和它的图像: | f, ax = plt.subplots(1) #, figsize=(10,10))
xs = [t['misc']['vals']['n_neighbors'] for t in trials.trials]
ys = [-t['result']['loss'] for t in trials.trials]
ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.5)
ax.set_title('Iris Dataset - KNN', fontsize=18)
ax.set_xlabel('n_neighbors', fontsize=12)
ax.set_ylabel('cross... | _____no_output_____ | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.