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 |
|---|---|---|---|---|---|
For N=20, it would appear that DAQ can capture a minimal example of input signal (just the peaks occuring at 1 Hz). Collecting data for N=20 over 10 seconds is equivalent to sampling at 20 samples/10 seconds = 2 Hz. This is called the Nyquist rate which is given as such$f_{Nyquist}=2f_{signal}$. (1)In Equation 1, the N... | N=11
t_collect=10 # time to collect data
t=np.linspace(0,t_collect,1000)
y=np.cos(2*pi*t)
tsample=np.linspace(0,10,N+1)
ysample=np.cos(2*pi*tsample)
plt.figure(20)
plt.plot(t,y,label='signal')
plt.plot(tsample,ysample,'o-',label='measure')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('time (... | _____no_output_____ | BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
Procedure The procedure and details of the experiment are included in a lab-handout [1].[ME3264_Lab_5_LVDT.pdf](https://drive.google.com/file/d/1FbykzotAE50SRTujNUjvF9vek97TlJXL/view?usp=sharing) | YouTubeVideo('FRWgpFApITo') | _____no_output_____ | BSD-3-Clause | lab_05/ME3264_Lab-05.ipynb | cooperrc/applied_measurements |
网络参数的初始化[](https://gitee.com/mindspore/docs/blob/master/docs/mindspore/programming_guide/source_zh_cn/initializer.ipynb) [](https://obs.dualstack.cn-n... | import numpy as np
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.common import set_seed
set_seed(1)
input_data = Tensor(np.ones([1, 3, 16, 50], dtype=np.float32))
net = nn.Conv2d(3, 64, 3, weight_init='Normal')
output = net(input_data)
print(output) | [[[[ 3.10382620e-02 4.38603461e-02 4.38603461e-02 ... 4.38603461e-02
4.38603461e-02 1.38719045e-02]
[ 3.26051228e-02 3.54298912e-02 3.54298912e-02 ... 3.54298912e-02
3.54298912e-02 -5.54019120e-03]
[ 3.26051228e-02 3.54298912e-02 3.54298912e-02 ... 3.54298912e-02
3.54298912e-02 -5.5401912... | Apache-2.0 | docs/mindspore/programming_guide/source_zh_cn/initializer.ipynb | bwcsswcx/docs |
Initializer子类 使用`Initializer`子类对网络参数进行初始化,与使用字符串对参数进行初始化的效果类似,不同的是使用字符串进行参数初始化是使用`Initializer`子类的默认参数,如要使用`Initializer`子类中的参数,就必须使用`Initializer`子类的方式对参数进行初始化,以`Normal(0.2)`为例,代码样例如下: | import numpy as np
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.common import set_seed
from mindspore.common.initializer import Normal
set_seed(1)
input_data = Tensor(np.ones([1, 3, 16, 50], dtype=np.float32))
net = nn.Conv2d(3, 64, 3, weight_init=Normal(0.2))
output = net(input_data)
print(o... | [[[[ 6.2076533e-01 8.7720710e-01 8.7720710e-01 ... 8.7720710e-01
8.7720710e-01 2.7743810e-01]
[ 6.5210247e-01 7.0859784e-01 7.0859784e-01 ... 7.0859784e-01
7.0859784e-01 -1.1080378e-01]
[ 6.5210247e-01 7.0859784e-01 7.0859784e-01 ... 7.0859784e-01
7.0859784e-01 -1.1080378e-01]
...
[... | Apache-2.0 | docs/mindspore/programming_guide/source_zh_cn/initializer.ipynb | bwcsswcx/docs |
自定义的Tensor 除上述两种初始化方法外,当网络要使用MindSpore中没有的数据类型对参数进行初始化,用户可以通过自定义`Tensor`的方式来对参数进行初始化,代码样例如下: | import numpy as np
import mindspore.nn as nn
from mindspore import Tensor
from mindspore import dtype as mstype
weight = Tensor(np.ones([64, 3, 3, 3]), dtype=mstype.float32)
input_data = Tensor(np.ones([1, 3, 16, 50], dtype=np.float32))
net = nn.Conv2d(3, 64, 3, weight_init=weight)
output = net(input_data)
print(outpu... | [[[[12. 18. 18. ... 18. 18. 12.]
[18. 27. 27. ... 27. 27. 18.]
[18. 27. 27. ... 27. 27. 18.]
...
[18. 27. 27. ... 27. 27. 18.]
[18. 27. 27. ... 27. 27. 18.]
[12. 18. 18. ... 18. 18. 12.]]
...
[[12. 18. 18. ... 18. 18. 12.]
[18. 27. 27. ... 27. 27. 18.]
[18. 27. 27. ... 27. 27. 18.]
...
... | Apache-2.0 | docs/mindspore/programming_guide/source_zh_cn/initializer.ipynb | bwcsswcx/docs |
使用initializer方法对参数初始化在上述代码样例中,给出了如何在网络中进行参数初始化的方法,如在网络中使用nn层封装`Conv2d`算子,参数`weight_init`作为要初始化的数据类型传入`Conv2d`算子,算子会在初始化时通过调用`Parameter`类,进而调用封装在`Parameter`类中的`initializer`方法来完成对参数的初始化。然而有一些算子并没有像`Conv2d`那样在内部对参数初始化的功能进行封装,如`Conv3d`算子的权重就是作为参数传入`Conv3d`算子,此时就需要手动的定义权重的初始化。当对参数进行初始化时,可以使用`initializer`方法调用`Initializer`子类... | import numpy as np
from mindspore import dtype as mstype
from mindspore.common import set_seed
from mindspore.ops import operations as ops
from mindspore import Tensor, Parameter, context
from mindspore.common.initializer import Normal, initializer
set_seed(1)
weight1 = Parameter(initializer('Normal', [5, 4], mstype.... | [[-0.3305102 1.0412874 2.0412874 3.0412874]
[ 4.0412874 4.9479127 5.9479127 6.9479127]
[ 7.947912 9.063009 10.063009 11.063009 ]
[12.063009 13.536987 14.536987 14.857441 ]
[15.751231 17.073082 17.808317 19.364822 ]]
| Apache-2.0 | docs/mindspore/programming_guide/source_zh_cn/initializer.ipynb | bwcsswcx/docs |
$\textbf{NOTE}$ Although it is not demonstrated in this section, you must ensure that any feature engineering or imputation that is carried out on the training data is also carried out on the test data. | df_titanic.shape
df_titanic.columns
df_titanic.info()
df_titanic.describe()
df_titanic.isnull().sum()
df_titanic.head()
print(df_titanic.index.name) | None
| MIT | Titanic.ipynb | sanchobuendia/Titanic |
To make the PassengerId attribute the index of the df_titanic dataframe, use the following snippet: | df_titanic.set_index("PassengerId", inplace=True)
print(df_titanic.index.name)
df_titanic.head()
# extract the target attribute into its own dataframe
df_titanic_target = df_titanic.loc[:,['Survived']]
# create a dataframe that contains the 10 feature variables
df_titanic_features = df_titanic.drop(['Survived'], axis... | _____no_output_____ | MIT | Titanic.ipynb | sanchobuendia/Titanic |
* titanic_features_train = df_titanic_features_numeric* titanic_features_test = df_titanic_test_features_numeric* titanic_target_train = df_titanic_test_target* titanic_target_test = df_titanic_target | df_titanic_test_features_numeric.shape
titanic_features_train = df_titanic_features_numeric
titanic_features_test = df_titanic_test_features_numeric
titanic_target_train = df_titanic_target
titanic_target_test = df_titanic_test_target
from sklearn.svm import SVC
svc_model = SVC(kernel='rbf', C=1, gamma='auto', probabi... | 0.9137373640537287 0.8673744926980475 0.8772728725274022
| MIT | Titanic.ipynb | sanchobuendia/Titanic |
The following code snippet uses the GridSearchCV class to try different hyperparameter combinations for a multi-class decision tree classifier on the Iris flowers dataset and returns the hyperparameters that result in the best precision score: | # use grid search to find the hyperparameters that result
# in the best accuracy score for a decision tree
# based classifier on the Iris Flowers dataset
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
grid_params = {
'criterion': ['gini', 'entropy'],
'splitter... | {'criterion': 'gini', 'max_depth': 12, 'max_features': 'auto', 'min_samples_split': 12, 'presort': False, 'splitter': 'best'}
0.8204381394764922
| MIT | Titanic.ipynb | sanchobuendia/Titanic |
The BioBB REST APIThe **[BioBB REST API](https://mmb.irbbarcelona.org/biobb-api)** allows the execution of the **[BioExcel Building Blocks](https://mmb.irbbarcelona.org/biobb/)** in a remote server. DocumentationFor an extense documentation section, please go to the **[BioBB REST API website help](https://mmb.irbbarce... | import requests
import json
apiURL = "https://mmb.irbbarcelona.org/biobb-api/rest/v1/" | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Tools information Definition of simple GET / POST request functions and a class Response: | # Class for returning response status and json content of a requested URL
class Response:
def __init__(self, status, json):
self.status = status
self.json = json
# Perform GET request
def get_data(url):
r = requests.get(url)
return Response(r.status_code, json.loads(r.text))
# Perform POST request
d... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
List of packagesFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/List%20of%20Services/getPckgList). Endpoint **GET** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/launch` Code | url = apiURL + 'launch'
response = get_data(url)
print(json.dumps(response.json, indent=2)) | {
"packages": [
{
"id": "biobb_analysis",
"tools": [
{
"id": "gmx_cluster",
"description": "Creates cluster structures from a given GROMACS compatible trajectory",
"arguments": [
{
"id": "config",
"required": false,
... | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
List of tools from a specific packageFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/List%20of%20Services/getToolsList). Endpoint **GET** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/launch/{package}` Code | package = 'biobb_analysis'
url = apiURL + 'launch/' + package
response = get_data(url)
print(json.dumps(response.json, indent=2)) | {
"id": "biobb_analysis",
"tools": [
{
"id": "gmx_cluster",
"description": "Creates cluster structures from a given GROMACS compatible trajectory",
"arguments": [
{
"id": "config",
"required": false,
"description": "Configuration file for the gmx_cluster t... | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Tool's propertiesFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/Launch%20Tool/getLaunchTool). Endpoint **GET** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/launch/{package}/{tool}` Code | package = 'biobb_analysis'
tool = 'cpptraj_average'
url = apiURL + 'launch/' + package + '/' + tool
response = get_data(url)
print(json.dumps(response.json, indent=2)) | {
"id": "cpptraj_average",
"description": "Calculates a structure average of a given cpptraj compatible trajectory.",
"arguments": [
{
"id": "config",
"required": false,
"description": "Configuration file for the cpptraj_average tool",
"filetype": "input",
"sample": "https://raw.... | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Launch toolFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/Launch%20Tool/postLaunchTool). The documentation for all the tools is available in the [BioBB REST API Tools Documentation section](https://mmb.irbbarcelona.org/biobb... | from io import BytesIO
from pathlib import Path
# Function used for encode python dictionary to JSON file
def encode_config(data):
jsonData = json.dumps(data)
binaryData = jsonData.encode()
return BytesIO(binaryData)
# Launch job
def launch_job(url, **kwargs):
data = {}
files = {}
# Fill data ... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Hereafter we will launch a job on *biobb_analysis.cpptraj_average* tool with the provided *files/* in the files folder of this same repository. The response is a JSON with the status code, the state of the job, a message and a token for checking the job status. Launch job with a YAML file config File config ```yaml pro... | # Launch BioBB on REST API with YAML config file
token = launch_job(url = apiURL + 'launch/biobb_analysis/cpptraj_average',
config = 'files/config.yml',
input_top_path = 'files/cpptraj.parm.top',
input_traj_path = 'files/cpptraj.traj.dcd',
ou... | {
"code": 303,
"state": "RUNNING",
"message": "The requested job has has been successfully launched, please go to /retrieve/status/{token} for checking job status.",
"token": "fe2805760eeeec0d5b8a34fbc40aa6c2a2d68c7ba1663cccb88659b1e149c898a414bbc04e37bb73efc725b7a29de2a93ffb55e6ef85cd6467f3d62a06ea5bfa"
}
| Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Launch job with a JSON file configFile config: ```json{ "in_parameters": { "start": 1, "end": -1, "step": 1, "mask": "c-alpha" }, "out_parameters": { "format": "pdb" }}``` Endpoint **POST** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/launch/{package}/{tool}` Code The function below sends POST data and files... | # Launch BioBB on REST API with JSON config file
token = launch_job(url = apiURL + 'launch/biobb_analysis/cpptraj_average',
config = 'files/config.json',
input_top_path = 'files/cpptraj.parm.top',
input_traj_path = 'files/cpptraj.traj.dcd',
o... | {
"code": 303,
"state": "RUNNING",
"message": "The requested job has has been successfully launched, please go to /retrieve/status/{token} for checking job status.",
"token": "84ab5ef63d82ab3fa4f120532949905d83f6aff65f101cb1ed5fdd5f05acb00421ddc4560098f877f26a96972a8ea8521ab222a0bb78a5ffa9d213c0ab2618c9"
}
| Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Launch job with a python dictionary config Endpoint **POST** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/launch/{package}/{tool}` Code The function below sends POST data and files to the *{package}/{tool}* endpoint. The config properties are sent as a python dictionary embedded in the code.The response is a JSON... | # Launch BioBB on REST API with JSON config file
prop = {
"in_parameters" : {
"start": 1,
"end": -1,
"step": 1,
"mask": "c-alpha"
},
"out_parameters" : {
"format": "pdb"
}
}
token = launch_job(url = apiURL + 'launch/biobb_analysis/cpptraj_average',
con... | {
"code": 303,
"state": "RUNNING",
"message": "The requested job has has been successfully launched, please go to /retrieve/status/{token} for checking job status.",
"token": "98013d74bef397d5498db3eb1008e5e136702d63903b6ea0cb5a2db44c4a4e0adbcd1ce9999915acd90c444f8749880c052185bbbfc747c1ebc7d67d6d2c84c8"
}
| Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Retrieve statusFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/Retrieve/getRetrieveStatus).Definition of functions needed for retrieve the status of a job: | import datetime
from time import sleep
# Checks status until a provided "ok" status is returned by the response
def check_status(url, ok, error):
counter = 0
while True:
if counter < 10: slp = 1
if counter >= 10 and counter < 60: slp = 10
if counter >= 60: slp = 60
counter = cou... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Endpoint **GET** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/retrieve/status/{token}` Code The function below checks the status of a job and awaits until the response status is `200`. The response is a JSON with the status code, the state of the job, a message, a list with all the generated output files and the d... | # Check job status
out_files = check_job(token, apiURL) | Total elapsed time: 0:00:20
REST API JSON response:
{
"code": 200,
"state": "FINISHED",
"message": "The requested job has finished successfully, please go to /retrieve/data/{id} for each output_files.",
"output_files": [
{
"id": "5e42837a40fe75.05757111",
"name": "output.... | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Retrieve dataFor more information about this endpoint, please visit the [BioBB REST API Documentation section](https://mmb.irbbarcelona.org/biobb-api/rest/Retrieve/getRetrieveData).Definition of functions needed for retrieve the output file(s) generated by a job: | # Downloads to disk a file from a given URL
def get_file(url, filename):
r = requests.get(url, allow_redirects=True)
file = open(filename,'wb')
file.write(r.content)
file.close()
# Retrieves all the files provided in the out_files list
def retrieve_data(out_files, apiURL):
if not out_files:
... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Endpoint **GET** `https://mmb.irbbarcelona.org/biobb-api/rest/v1/retrieve/data/{id}` Code The function below makes a single call to the *retrieve/data* endpoint for each output file got in the *retrieve/status* endpoint and save the generated file(s) to disk. | # Save generated file(s) to disk
retrieve_data(out_files, apiURL) | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Practical cases Now we will execute some Bioexcel Building Blocks through the BioBB REST API and with the results we will do some interactions with other python libraries such as [plotly](https://plot.ly/python/offline/) or [nglview](http://nglviewer.org/nglview). Example 1: download PDB file from RSCB database Launc... | # Downloading desired PDB file
# Create properties dict and inputs/outputs
downloaded_pdb = '3EBP.pdb'
prop = {
'pdb_code': '3EBP',
'filter': False
}
# Launch bb on REST API
token = launch_job(url = apiURL + 'launch/biobb_io/pdb',
config = prop,
output_pdb_path = downloa... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Visualize downloaded PDB in NGLView: | import nglview
# Show protein
view = nglview.show_structure_file(downloaded_pdb)
view.add_representation(repr_type='ball+stick', selection='het')
view._remote_call('setSize', target='Widget', args=['','600px'])
view
view.render_image()
view.download_image(filename='ngl1.png') | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Example 2: extract heteroatom from a given structure Launch the *biobb_structure_utils.extract_heteroatoms* job that extracts a heteroatom from a PDB file. | # Extracting heteroatom from a given structure
# Create properties dict and inputs/outputs
heteroatom = 'CPB.pdb'
prop = {
'heteroatoms': [{
'name': 'CPB'
}]
}
# Launch bb on REST API
token = launch_job(url = apiURL + 'launch/biobb_structure_utils/extract_heteroatoms',
config = pro... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Visualize generated extracted heteroatom in NGLView: | # Show protein
view = nglview.show_structure_file(heteroatom)
view.add_representation(repr_type='ball+stick', selection='het')
view._remote_call('setSize', target='Widget', args=['','600px'])
view
view.render_image()
view.download_image(filename='ngl2.png') | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Example 3: extract energy components from a given GROMACS energy file | # GMXEnergy: Getting system energy by time
# Create prop dict and inputs/outputs
output_min_ene_xvg ='file_min_ene.xvg'
output_min_edr = 'files/1AKI_min.edr'
prop = {
'terms': ["Potential"]
}
# Launch bb on REST API
token = launch_job(url = apiURL + 'launch/biobb_analysis/gmx_energy',
config ... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
Visualize generated energy file in plotly: | import plotly
import plotly.graph_objs as go
#Read data from file and filter energy values higher than 1000 Kj/mol^-1
with open(output_min_ene_xvg,'r') as energy_file:
x,y = map(
list,
zip(*[
(float(line.split()[0]),float(line.split()[1]))
for line in energy_file
... | _____no_output_____ | Apache-2.0 | biobb_REST_API_documentation/html/biobb_REST_API_documentation.web.ipynb | bioexcel/biobb_REST_API_documentation |
An illustration of the metric and non-metric MDS on generated noisy data.The reconstructed points using the metric MDS and non metric MDS are slightly shifted to avoid overlapping. New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the c... | import sklearn
sklearn.__version__ | _____no_output_____ | CC-BY-3.0 | _posts/scikit/multidimensional-scaling/Multi-Dimensional Scaling.ipynb | bmb804/documentation |
Imports | print(__doc__)
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
from sklearn import manifold
from sklearn.metrics import euclidean_distances
from sklearn.decomposition import PCA | Automatically created module for IPython interactive environment
| CC-BY-3.0 | _posts/scikit/multidimensional-scaling/Multi-Dimensional Scaling.ipynb | bmb804/documentation |
Calculations | n_samples = 20
seed = np.random.RandomState(seed=3)
X_true = seed.randint(0, 20, 2 * n_samples).astype(np.float)
X_true = X_true.reshape((n_samples, 2))
# Center the data
X_true -= X_true.mean()
similarities = euclidean_distances(X_true)
# Add noise to the similarities
noise = np.random.rand(n_samples, n_samples)
noi... | _____no_output_____ | CC-BY-3.0 | _posts/scikit/multidimensional-scaling/Multi-Dimensional Scaling.ipynb | bmb804/documentation |
Plot Results | data = []
p1 = go.Scatter(x=X_true[:, 0], y=X_true[:, 1],
mode='markers+lines',
marker=dict(color='navy', size=10),
line=dict(width=1),
name='True Position')
data.append(p1)
p2 = go.Scatter(x=pos[:, 0], y=pos[:, 1],
mode='markers+lines',
... | _____no_output_____ | CC-BY-3.0 | _posts/scikit/multidimensional-scaling/Multi-Dimensional Scaling.ipynb | bmb804/documentation |
License Author: Nelle Varoquaux License: BSD | from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-not... | _____no_output_____ | CC-BY-3.0 | _posts/scikit/multidimensional-scaling/Multi-Dimensional Scaling.ipynb | bmb804/documentation |
Web Coverage Service (WCS) Download Example IntroductionWe'll demonstrate how to download a GeoTIFF data file from a public WCS service using Python 3. WCS Data ServiceFor this demonstration we'll use Landfire (LF_1.4.0): https://www.landfire.gov/data_access.phpFor Landfire LF_1.4.0 we see that the base URL is https... | import requests
# base WCS server URL
wcs_base_url = "https://landfire.cr.usgs.gov/arcgis/services/Landfire/US_140/MapServer/WCSServer"
# add on to the base WCS server URL to define GetCapabilities URL
wcs_get_capabilities_url = wcs_base_url + "?REQUEST=GetCapabilities&SERVICE=WCS"
# perform an HTTP GET request with... | GetCapabilities Response:
<?xml version="1.0" encoding="UTF-8"?>
<Capabilities xmlns="http://www.opengis.net/wcs/1.1"
xmlns:ows="http://www.opengis.net/ows/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xlink="http://www.w3.org/1999/xlink"
xsi:schemaLocation="http://www.opengis.net/wcs/1.1 http://... | MIT | wcs-1.0.0-example.ipynb | ethanfahy/wcs-1.0.0-example-notebook |
GetCapabilities resultsThe GetCapabilities request returns a lot of information for us. We can see that the WCS server supports WCS version `1.0.0`, `1.1.0`, `1.1.1`, and `1.1.2` . For the purposes of this guide, we're going to stick to WCS 1.0.0.Within the contents section, we can see all of the available coverages... | import requests
# base WCS server URL
wcs_base_url = "https://landfire.cr.usgs.gov/arcgis/services/Landfire/US_140/MapServer/WCSServer"
# add on to the base WCS server URL to define DescribeCoverage URL
wcs_describe_coverage_url = wcs_base_url + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=DescribeCoverage&COVERAGE=US_VDIST20... | DescribeCoverage Response:
<?xml version="1.0" encoding="UTF-8"?>
<CoverageDescription xmlns="http://www.opengis.net/wcs"
xmlns:gml="http://www.opengis.net/gml"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/wcs http://sche... | MIT | wcs-1.0.0-example.ipynb | ethanfahy/wcs-1.0.0-example-notebook |
DescribeCoverage resultsFrom the DescribeCoverage response, we can see information about the available bounding box for the layer, the Coordinate Reference System (CRS), the download data types (e.g. GeoTiff), and more. We'll use this information to help formulate a successful WCS GetCoverage request to download some... | import requests
# base WCS server URL
wcs_base_url = "https://landfire.cr.usgs.gov/arcgis/services/Landfire/US_140/MapServer/WCSServer"
# add on to the base WCS server URL to define GetCoverage URL
wcs_get_coverage_url = wcs_base_url + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&FORMAT=GeoTIFF&COVERAGE=US_VDIST20... | _____no_output_____ | MIT | wcs-1.0.0-example.ipynb | ethanfahy/wcs-1.0.0-example-notebook |
Table of Contents1 Method I: For Loop2 Method II: List Comprehension3 Method III: Combining | import numpy as np
import os
import random
import matplotlib.pyplot as plt
arr=[1,2,3,4,5,6,6,7,7,7,7,8,5,3,2]
np_arr=np.array(arr)
np_arr | _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
Note: () for functions, [] for calling elements of a list or array. | def my_function(x):
return x**2
my_function(10) | _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
Method I: For Loop | arr1=[]
for i in range(100):
arr1.append(i**(1/2)+1+i**1.2)
| _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
plt.plot(Xvalues,Yvalues,....properties)plt.show() | plt.plot(range(100),arr1)
plt.show()
arr2=[]
for i in range(1000):
arr2.append(random.random())
plt.plot(range(1000),arr2)
plt.show() | _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
Method II: List Comprehension | arr3=[i**(1/2) for i in range(100)]
plt.plot(range(100),arr3)
arr4=[random.random() for i in range(100)]
arr4 | _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
Method III: Combining | len(arr3+arr4), len(arr3),len(arr4) | _____no_output_____ | MIT | Untitled.ipynb | williamcottrell72/williamcottrell72.github.io |
Python datetime moduleWe will look at an important standard library, the [datetime library][1] which contains many powerful functions to support date, time and datetime manipulation. Pandas does not rely on this object and instead creates its own, a `Timestamp`, discussed in other notebooks.The datetime library is par... | import datetime | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Create a date, a time and a datetimeThe datetime module provides three separate objects for dates, times, and datetimes. Let's use the `date` type to construct a date. It takes three integers, the year, month and day. Here we create the date April 11, 2016. | my_date = datetime.date(2016, 4, 11)
my_date
type(my_date) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Use the `time` type to construct a time. It takes 4 integers - hours, minutes, seconds, and microseconds (one millionth of a second). Here we create the time 10:54:32.034512 | my_time = datetime.time(10, 54, 32, 34512)
my_time
type(my_time) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Only the hour component is mandatory. For instance, we can create the time 5:44 with this: | datetime.time(5, 44) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Or you can specify just a particular component of time. | datetime.time(second=34) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Finally, we can construct a datetime with the `datetime` type, which takes up to 7 parameters - three for the date, and four for the time. | my_datetime = datetime.datetime(2016, 4, 11, 10, 54, 32, 34512)
my_datetime
type(my_datetime) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Format changes when printed to the screenPrinting the objects from above to the screen provides a more readable view. | print(my_date)
print(my_time)
print(my_datetime) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Attributes of date, time, and datetimesEach individual component of the date, time, and datetime is available as an attribute. | my_date.year
my_date.month
my_date.day
my_time.hour
my_time.minute
my_time.second
my_datetime.day
my_datetime.microsecond
my_date.weekday() | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Methods of date, time, and datetimesSeveral methods exist for each of these objects. The methods that begin with ISO represent the [International Standards Organization][1] formatting rules for dates, times, and datetimes. The particular standard here is [ISO 8601][2]. Python will return according to this standard.[1]... | my_date.weekday()
my_date.isoformat()
my_date.isocalendar()
my_time.isoformat()
my_datetime.isoformat()
# get the date from a datetime
my_datetime.date()
# get the time from a datetime
my_datetime.time() | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Alternate ConstructorsYou can create dates and datetimes from a single integer which represents the number of seconds since the Unix epoch, January 1, 1970 UTC. UTC is the timezone, [Coordinated Universal Time][1] and is 0 degrees longitude or 5 hours ahead of Easter Standard Time.Passing the integer 0 to the `fromtim... | datetime.datetime.fromtimestamp(0)
# 1 billion seconds from the unix epoch
datetime.datetime.fromtimestamp(10 ** 9) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
The date type also has this constructor, but not time. | # also works for date
datetime.date.fromtimestamp(10 ** 9) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Can get todays date or datetime: | datetime.date.today()
datetime.datetime.now() | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Constructing from stringsThe `strptime` alternate datetime constructor has the ability to convert a string into a datetime. In addition to the string, you must pass it a specific **format** to alert the constructor which part of the string corresponds to which component of the datetime. There are special character cod... | s = '2016-10-22'
fmt = '%Y-%m-%d'
datetime.datetime.strptime(s, fmt)
s = '2016/1/22 5:32:44'
fmt = '%Y/%m/%d %H:%M:%S'
datetime.datetime.strptime(s, fmt)
s = 'January 23, 2019 5:22 PM'
fmt = '%B %d, %Y %H:%M %p'
datetime.datetime.strptime(s, fmt)
s = 'On January the 23rd 2019 at 5:22 PM'
fmt = 'On %B the %drd %Y at %H:... | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Converting datetimes to stringThe **strftime** method converts a date, time, or datetime to a string. It stands for **string format time**. Begin with a date, time, or datetime and use a string with directives to make the conversion. | # Convert directly into a string of your choice. Lookup directives online
my_date.strftime("%Y-%m-%d")
# Another more involved directive
my_date.strftime("Remembering back to %A, %B %d, %Y.... What a fantastic day that was.") | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Date and Datetime additionIt's possible to add an amount of time to a date or datetime object using the timedelta function. timedelta simply produces some amount of time measured in days, seconds and microseconds. You can then use this object to add to date or datetime objects.**`timedelta`** objects are constructed w... | my_timedelta = datetime.timedelta(seconds=5000)
my_timedelta
type(my_timedelta)
# add to datetime
my_datetime + my_timedelta
# original
my_datetime
# add to date
my_date + my_timedelta
# original date. Nothing changed since 5000 seconds wasn't long enough to make an extra day
my_date
# now there is a change
my_date + ... | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Third-Party library `dateutil`For improved datetime handling, you can use [dateutil][1], a more advanced third-party library. Pandas actually uses this library to for its complex date handling. Two of it's most useful features are string parsing and datetime addition. Advanced string handlingThe `parse` function handl... | from dateutil.parser import parse
parse('Jan 3, 2003 and 5:22') | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Pandas uses this under the hood. | import pandas as pd
pd.Timestamp('Jan 3, 2003 and 5:22') | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Advanced datetime additionAn upgrade to the **`timedelta`** class exists with the **`relativedelta`** class. Check [this stackoverflow][1] post for more detail or see the [documentation for examples][2].[1]: http://stackoverflow.com/questions/12433233/what-is-the-difference-between-datetime-timedelta-and-dateutil-rela... | from dateutil.relativedelta import relativedelta | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
There are two ways to use it. First, you can pass it two datetimes to find the difference between the two. | dt1 = datetime.datetime(2016, 1, 20, 5, 33)
dt2 = datetime.datetime(2018, 3, 20, 6, 22)
relativedelta(dt1, dt2) | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
Second, create an amount of time with the parameters years, months, weeks, days, etc... and then add that to a datetime. | rd = relativedelta(months=3)
dt1 + rd | _____no_output_____ | MIT | jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb | manual123/Nacho-Jupyter-Notebooks |
VacationPy---- Note* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps... | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import gmaps
import os
# Import API key
from api_keys import g_key | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | jfaccioli/python-api-challenge |
Store Part I results into DataFrame* Load the csv exported in Part I to a DataFrame | # Import World Happiness Report Data 2021
city_data = pd.read_csv("../WeatherPy/city_data.csv")
city_data
| _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | jfaccioli/python-api-challenge |
Humidity Heatmap* Configure gmaps.* Use the Lat and Lng as locations and Humidity as the weight.* Add Heatmap layer to map. | # Configure gmaps
gmaps.configure(api_key=g_key)
# Store 'Lat' and 'Lng' into locations
locations = city_data[["Lat", "Lng"]].astype(float)
humidity = city_data['Humidity']
# Create a Humidity Heatmap
fig = gmaps.figure(center=(0, 0), zoom_level=2)
humidity_heatmap = gmaps.heatmap_layer(locations, weights=humidity... | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | jfaccioli/python-api-challenge |
Create new DataFrame fitting weather criteria* Narrow down the cities to fit weather conditions.* Drop any rows will null values. | # Dropna in city_data
city_data_narrowed = city_data.dropna()
# Narrow down the cities to fit weather conditions
city_data_narrowed = city_data_narrowed[(city_data_narrowed['Max Temp'] > 70) & (city_data_narrowed['Max Temp'] < 80)]
city_data_narrowed = city_data_narrowed[city_data_narrowed['Wind Speed'] <= 10]
city_da... | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | jfaccioli/python-api-challenge |
Hotel Map* Store into variable named `hotel_df`.* Add a "Hotel Name" column to the DataFrame.* Set parameters to search for hotels with 5000 meters.* Hit the Google Places API for each city's coordinates.* Store the first Hotel result into the DataFrame.* Plot markers on top of the heatmap. | # Store into variable named hotel_df
hotel_df = city_data_narrowed
# Add "Hotel Name" column
hotel_df['Hotel Name'] = ""
hotel_df
# Set parameters to search for hotels with 5000 meters
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
params = {"type" : "hotel",
"keyword" : "hotel"... | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | jfaccioli/python-api-challenge |
Hybrid Recommendations with the Movie Lens Dataset __Note:__ It is recommended that you complete the companion __als_bqml.ipynb__ notebook before continuing with this __als_bqml_hybrid.ipynb__ notebook. This is, however, not a requirement for this lab as you have the option to bring over the dataset + trained model. I... | import os
import tensorflow as tf
PROJECT = "qwiklabs-gcp-04-8722038efd75" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["TFVERSION"] = '2.1' | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Import the dataset and trained modelIn the previous notebook, you imported 20 million movie recommendations and trained an ALS model with BigQuery MLTo save you the steps of having to do so again (if this is a new environment) you can run the below commands to copy over the clean data and trained model. First create t... | !bq mk movielens
%%bigquery
CREATE OR REPLACE TABLE movielens.ratings AS
SELECT * FROM `cloud-training-demos`.movielens.ratings;
CREATE OR REPLACE TABLE movielens.movies AS
SELECT * FROM `cloud-training-demos`.movielens.movies; | Executing query with job ID: 5796f872-80ab-436a-9761-47a4960e7621
Query executing: 0.33s | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Next, copy over the trained recommendation model. Note that if you're project is in the EU you will need to change the location from US to EU below. Note that as of the time of writing you cannot copy models across regions with `bq cp`. | %%bash
bq --location=US cp \
cloud-training-demos:movielens.recommender_16 \
movielens.recommender_16 | Table 'cloud-training-demos:movielens.recommender_16' successfully copied to 'qwiklabs-gcp-04-8722038efd75:movielens.recommender_16'
| Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Next, ensure the model still works by invoking predictions for movie recommendations: | %%bigquery --project $PROJECT
SELECT * FROM
ML.PREDICT(MODEL `movielens.recommender_16`, (
SELECT
movieId, title, 903 AS userId
FROM movielens.movies, UNNEST(genres) g
WHERE g = 'Comedy'
))
ORDER BY predicted_rating DESC
LIMIT 5 | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Incorporating user and movie information The matrix factorization approach does not use any information about users or movies beyond what is available from the ratings matrix. However, we will often have user information (such as the city they live, their annual income, their annual expenditure, etc.) and we will almo... | %%bigquery --project $PROJECT
SELECT
processed_input,
feature,
TO_JSON_STRING(factor_weights),
intercept
FROM ML.WEIGHTS(MODEL movielens.recommender_16)
WHERE
(processed_input = 'movieId' AND feature = '96481')
OR (processed_input = 'userId' AND feature = '54192') | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Multiplying these weights and adding the intercept is how we get the predicted rating for this combination of movieId and userId in the matrix factorization approach.These weights also serve as a low-dimensional representation of the movie and user behavior. We can create a regression model to predict the rating given ... | %%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.users AS
SELECT
userId,
RAND() * COUNT(rating) AS loyalty,
CONCAT(SUBSTR(CAST(userId AS STRING), 0, 2)) AS postcode
FROM
movielens.ratings
GROUP BY userId | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Input features about users can be obtained by joining the user table with the ML weights and selecting all the user information and the user factors from the weights array. | %%bigquery --project $PROJECT
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights)) AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'userId' AND feature = CAST(u.userId AS STRING)
)
SELECT * FROM userFe... | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Similarly, we can get product features for the movies data, except that we have to decide how to handle the genre since a movie could have more than one genre. If we decide to create a separate training row for each genre, then we can construct the product features using. | %%bigquery --project $PROJECT
WITH productFeatures AS (
SELECT
p.* EXCEPT(genres),
g, (SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights))
AS product_factors
FROM movielens.movies p, UNNEST(genres) g
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
ON processed_input = 'movieId' AND ... | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Combining these two WITH clauses and pulling in the rating corresponding the movieId-userId combination (if it exists in the ratings table), we can create the training dataset.**TODO 1**: Combine the above two queries to get the user factors and product factor for each rating. | %%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.hybrid_dataset AS
WITH userFeatures AS (
SELECT
u.*,
(SELECT ARRAY_AGG(weight) FROM UNNEST(factor_weights)) AS user_factors
FROM movielens.users u
JOIN ML.WEIGHTS(MODEL movielens.recommender_16) w
... | Executing query with job ID: 5fa26fe2-8850-4f84-813e-753541f2c6f4
Query executing: 72.47s | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
One of the rows of this table looks like this: | %%bigquery --project $PROJECT
SELECT *
FROM movielens.hybrid_dataset
LIMIT 1 | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Essentially, we have a couple of attributes about the movie, the product factors array corresponding to the movie, a couple of attributes about the user, and the user factors array corresponding to the user. These form the inputs to our “hybrid” recommendations model that builds off the matrix factorization model and a... | %%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_users(u ARRAY<FLOAT64>)
RETURNS
STRUCT<
u1 FLOAT64,
u2 FLOAT64,
u3 FLOAT64,
u4 FLOAT64,
u5 FLOAT64,
u6 FLOAT64,
u7 FLOAT64,
u8 FLOAT64,
u9 FLOAT64,
u10 ... | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
which gives: | %%bigquery --project $PROJECT
SELECT movielens.arr_to_input_16_users(u).*
FROM (SELECT
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.] AS u) | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
We can create a similar function named movielens.arr_to_input_16_products to convert the product factor array into named columns.**TODO 2**: Create a function that returns named columns from a size 16 product factor array. | %%bigquery --project $PROJECT
CREATE OR REPLACE FUNCTION movielens.arr_to_input_16_products(p ARRAY<FLOAT64>)
RETURNS
STRUCT<
p1 FLOAT64,
p2 FLOAT64,
p3 FLOAT64,
p4 FLOAT64,
p5 FLOAT64,
p6 FLOAT64,
p7 FLOAT64,
p8 FLOAT64,
p9 FLOAT64,
p... | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Then, we can tie together metadata about users and products with the user factors and product factors obtained from the matrix factorization approach to create a regression model to predict the rating: | %%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender_hybrid
OPTIONS(model_type='linear_reg', input_label_cols=['rating'])
AS
SELECT
* EXCEPT(user_factors, product_factors),
movielens.arr_to_input_16_users(user_factors).*,
movielens.arr_to_input_16_products(product_factors).*
FROM
mo... | _____no_output_____ | Apache-2.0 | notebooks/recommendation_systems/labs/3_als_bqml_hybrid.ipynb | jfesteban/Google-ASL |
Introduction to XGBoost-Spark Cross Validation with GPUThe goal of this notebook is to show you how to levarage GPU to accelerate XGBoost spark cross validatoin for hyperparameter tuning. The best model for the given hyperparameters will be returned.Here takes the application 'Mortgage' as an example.A few libraries a... | from ml.dmlc.xgboost4j.scala.spark import XGBoostClassificationModel, XGBoostClassifier
from ml.dmlc.xgboost4j.scala.spark.rapids import CrossValidator
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml.tuning import ParamGridBuilder
from pyspark.sql import SparkSession
from pyspark.sql... | _____no_output_____ | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
As shown above, here `CrossValidator` is imported from package `ml.dmlc.xgboost4j.scala.spark.rapids`, not the spark's `tuning.CrossValidator`. Create a Spark Session | spark = SparkSession.builder.appName("mortgage-cv-gpu-python").getOrCreate() | _____no_output_____ | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Specify the Data Schema and Load the Data | label = 'delinquency_12'
schema = StructType([
StructField('orig_channel', FloatType()),
StructField('first_home_buyer', FloatType()),
StructField('loan_purpose', FloatType()),
StructField('property_type', FloatType()),
StructField('occupancy_status', FloatType()),
StructField('property_state', ... | _____no_output_____ | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Build a XGBoost-Spark CrossValidator | # First build a classifier of GPU version using *setFeaturesCols* to set feature columns
params = {
'eta': 0.1,
'gamma': 0.1,
'missing': 0.0,
'treeMethod': 'gpu_hist',
'maxDepth': 10,
'maxLeaves': 256,
'growPolicy': 'depthwise',
'objective': 'binary:logistic',
'minChildWeight': 30.... | _____no_output_____ | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Start Cross Validation by Fitting Data to CrossValidator | def with_benchmark(phrase, action):
start = time()
result = action()
end = time()
print('{} takes {} seconds'.format(phrase, round(end - start, 2)))
return result
model = with_benchmark('Cross-Validation', lambda: cross_validator.fit(train_data)).bestModel | Cross-Validation takes 88.53 seconds
| Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Transform On the Best Model | def transform():
result = model.transform(trans_data).cache()
result.foreachPartition(lambda _: None)
return result
result = with_benchmark('Transforming', transform)
result.select(label, 'rawPrediction', 'probability', 'prediction').show(5) | Transforming takes 3.13 seconds
+--------------+--------------------+--------------------+----------+
|delinquency_12| rawPrediction| probability|prediction|
+--------------+--------------------+--------------------+----------+
| 0|[2.57163572311401...|[0.92901364713907...| 0.0|
| ... | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Evaluation | accuracy = with_benchmark(
'Evaluation',
lambda: MulticlassClassificationEvaluator().setLabelCol(label).evaluate(result))
print('Accuracy is ' + str(accuracy))
spark.stop() | _____no_output_____ | Apache-2.0 | examples/mortgage/notebooks/python/cv-mortgage-gpu.ipynb | wbo4958/spark-rapids-examples |
Quantitative Immuno-Subtraction Project--- | # %matplotlib notebook
import sys as sys
import pandas as pd #import pandas for file reading
import matplotlib as mpl #import matplotlib for graphing
import matplotlib.pyplot as plt #import plot module
import numpy as np ... | Using Pandas to import data version: 1.1.5
Using numpy version: 1.19.5
| RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Ryan's Curve Fit Playground---Begin by defining the relevant functions for non-linear least-squared curve fitting using the Newton-Gauss Method. Defining the Partial Differential Equations1. Normal / Gaussian distribution ($\rho$):$$ \rho = \frac{\alpha e^{\frac{-(x-\mu)^2}{2\sigma^2}}}{\sqrt{2\pi}\sigma} \ \text{... | # param[0] = AMPLITUDE
# param[1] = MEAN
# param[2] = STANDARD DEVIATION
def conv_norm_dist(x,p):
result = [0] * len(x)
for p_ in p:
result += p_[0]*np.exp(-pow((x-p_[1]),2)/(2*pow(p_[2],2))) / (np.sqrt(2*np.pi)*p_[2])
return result
def norm_dist(x, p):
result = []
for p_ in p:
result.append(p_[0]*np.... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Class Declarations---The following code incapsulates the above functions in an object-oriented manner to provide greater ease of use. | class curve:
amp = 1.0
mean = 1.0
sd = 1.0
def __init__(self, init_amp, init_mean, init_sd):
self.amp = init_amp
self.mean = init_mean
self.sd = init_sd
# Generate a normal distribution using the curves parameters
def normal_dist(self, x):
return self.amp*np.exp(-pow((x-self.mean),2)/(2*... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Below, a QC test to ensure the proper functioning of the above defined partial differential equations | fig, ax = plt.subplots();
# styles = ['-','--','-.']
ax.plot(x, y, '-');
for d_amp in dy_da:
ax.plot(x,d_amp,'-', label='$\partial\ rho / \partial\ amp$', color = 'green');
for d_mean in dy_dm:
ax.plot(x,d_mean,'-', label='$\partial\ rho / \partial\ mean$', color = 'red');
for d_sd in dy_ds:
ax.plot(x,d_sd,'-', l... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Initial Estimates and Peak FindingRoot finding methods require initial estimates in most instances. The role of the **peakFinder** class described below is to identify inflection points using the second derivative of the trace. | class peakFinder:
class peak:
index = 0
estimate = 1.0
def __init__(self, _index_, _estimate_):
self.index = _index_
self.estimate = _estimate_
peaks = []
inflections = []
def find_peaks (self, x):
index = 0
d_x = x[1:len(x-1)]
d_x2 = d_x[1:len(x-1)]
... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Defining the JacobianThe Jacobian matrix is defined as follows:$$ J = \left[\begin{aligned}&\frac{\partial r_0}{\partial \alpha_1},\frac{\partial r_1}{\partial \alpha_1},\frac{\partial r_2}{\partial \alpha_1},\dots,&\frac{\partial r_N}{\partial \alpha_1} \\&\frac{\partial r_0}{\partial \mu_1},\frac{\partial r_1}{\part... | # residuals(y,x,(param_est[0][0],param_est[0][1],param_est[0][2]))
np.sum(CL.get_residuals())
fig, ax = plt.subplots(CL.n_curves);
ax[0].set_title("Numerical Jacobians for "+str(len(CL.curves))+" Curves");
ax[CL.n_curves-1].set_xlabel("x")
# J = CL.get_jacobian()
J = CL.get_nJacobian(1.0)
for index in range(0,CL.n_curv... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
The Newton Gauss Method iteratively finds the root of the derivative of the error ($\ ^{dr}/_{d\rho} = 0$) by estimating the change needed in the gaussian ($\Delta\rho$), which in and of itself is a function of $\Delta\alpha$, $\Delta\mu$, and $\Delta\sigma$. The Jacobian is convolved with its transpose ($J^TJ$) to aco... | import time
r = CL.get_residuals()
error = [np.sum(r)];
mu = error[0]
step = 1.0
# Figure preparation
fig, ax = plt.subplots();
_disp = dsp.display("", display_id=True)
ax.plot(x, y, '-k');
comb = [0]*len(x)
for C in CL:
comb += C.normal_dist(x)
ax.plot(x, C.normal_dist(x),'--', label = 'Curve Fit');
ax.p... | _____no_output_____ | RSA-MD | QuantImmunoSubtraction.ipynb | ryanlandvater/qIS |
Homework 5 - Visit the Wikipedia hyperlinks graph! Maria Luisa Croci, Livia Lilli, Pavan Kumar Alikana RQ1 | import pandas as pd
import json
import pickle
from tqdm import tqdm
from collections import defaultdict
from heapq import *
import numpy as np
import collections
import networkx as nx | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
For our first requests, we can use 2 different approaches:* We can start from the file building a dictionary that describe our graph; we do it because we will need this dictionary for the request 2;* Or, better, we can use an easy command nx.info, to get all the informations we need.So let's see! Approach 1 Let's star... | F = open('wiki-topcats-reduced.txt','r')
all_rows = F.read().split('\n')
graph = {}
for row in all_rows:
row = row.split("\t")
if row[0] not in graph:
try:
graph[row[0]] = [row[1]]
except:
pass
else:
graph[row[0]].append(row[1])
lista = []
for l in... | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
So, what can we say?* We are in a case of page ranking. So for definition we have nodes representing sources and destinations, with edges with a particular direction. In other words, our graph has a set of edges which are ordered pairs of nodes, and for the graph theory we have a directed graph.* The number of nodes is... | V = list(graph.keys())
n_nodes = len(V)
n_nodes | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Number of edges | n_edges = 0
for l in graph.values():
n_edges += len(l)
n_edges | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.