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 |
|---|---|---|---|---|---|
Enable GPU | import torch
device = torch.device('cuda:0' if torch.cuda.is_available else 'cpu') | _____no_output_____ | MIT | TD Actor Critic/TD_Actor_Critic_seperate_net.ipynb | gt-coar/BrianSURE2021 |
Actor and Critic Network | import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
class Actor_Net(nn.Module):
def __init__(self, input_dims, output_dims, num_neurons = 128):
super(Actor_Net, self).__init__()
self.fc1 = nn.Linear(input_dims, num_neurons)
self.actor = nn.Linear(num_neurons,... | _____no_output_____ | MIT | TD Actor Critic/TD_Actor_Critic_seperate_net.ipynb | gt-coar/BrianSURE2021 |
Without Wandb | import gym
import time
import pdb
env = gym.make('CartPole-v1')
env.seed(543)
torch.manual_seed(543)
state_dims = env.observation_space.shape[0]
action_dims = env.action_space.n
agent = Actor_Critic_Agent(input_dims= state_dims, output_dims = action_dims)
def train():
num_ep = 2000
print_every = 100
running_sc... | episode: 100, running score: 43.32507441570408, time elapsed: 4.842878341674805
episode: 200, running score: 129.30332722904944, time elapsed: 19.552313089370728
| MIT | TD Actor Critic/TD_Actor_Critic_seperate_net.ipynb | gt-coar/BrianSURE2021 |
Wtih wandb | !pip install wandb
!wandb login
import wandb
sweep_config = dict()
sweep_config['method'] = 'grid'
sweep_config['metric'] = {'name': 'running_score', 'goal': 'maximize'}
sweep_config['parameters'] = {'learning': {'value': 'learn_mean'}, 'actor_learning_rate': {'values' : [0.01, 0.001, 0.0001,0.0003,0.00001]}, 'critic_... | [34m[1mwandb[0m: Agent Starting Run: wivnmds7 with config:
[34m[1mwandb[0m: actor_learning_rate: 0.01
[34m[1mwandb[0m: critic_learning_rate: 0.01
[34m[1mwandb[0m: learning: learn_mean
[34m[1mwandb[0m: num_neurons: 128
[34m[1mwandb[0m: optimizer: RMSprop
[34m[1mwandb[0m: [33mWARNING[0m Ignore... | MIT | TD Actor Critic/TD_Actor_Critic_seperate_net.ipynb | gt-coar/BrianSURE2021 |
Import Necessary Packages | import numpy as np
import pandas as pd
import datetime
import os
np.random.seed(1337) # for reproducibility
from sklearn.model_selection import train_test_split
from sklearn.metrics.classification import accuracy_score
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.regression import r2_score, mea... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Define Model Settings | RBM_EPOCHS = 5
DBN_EPOCHS = 150
RBM_LEARNING_RATE = 0.01
DBN_LEARNING_RATE = 0.01
HIDDEN_LAYER_STRUCT = [20, 50, 100]
ACTIVE_FUNC = 'relu'
BATCH_SIZE = 28 | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Define Directory, Road, and Year | # Read the dataset
ROAD = "Vicente Cruz"
YEAR = "2015"
EXT = ".csv"
DATASET_DIVISION = "seasonWet"
DIR = "../../../datasets/Thesis Datasets/"
OUTPUT_DIR = "PM1/Rolling 3/"
MODEL_DIR = "PM1/Rolling 3/"
'''''''Training dataset'''''''
WP = False
WEEKDAY = False
CONNECTED_ROADS = False
CONNECTED_1 = ["Antipolo"]
trafficDT... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Preparing Traffic Dataset Importing Original Traffic (wo new features) | TRAFFIC_DIR = DIR + "mmda/"
TRAFFIC_FILENAME = "mmda_" + ROAD + "_" + YEAR + "_" + DATASET_DIVISION
orig_traffic = pd.read_csv(TRAFFIC_DIR + TRAFFIC_FILENAME + EXT, skipinitialspace=True)
orig_traffic = orig_traffic.fillna(0)
#Converting index to date and time, and removing 'dt' column
orig_traffic.index = pd.to_datet... | c:\users\ronnie nieva\anaconda3\envs\tensorflow\lib\site-packages\ipykernel_launcher.py:3: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead
This is separate from the ipykernel package so we can avoid doing imports until
| MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Merging datasets | if trafficDT == "orig_traffic":
arrDT = [orig_traffic]
if CONNECTED_ROADS:
for c in connected_roads:
arrDT.append(c)
elif trafficDT == "recon_traffic":
arrDT = [recon_traffic]
if CONNECTED_ROADS:
timeConnected = "today"
print("TimeConnected = " + timeCo... | Adding Feature Engineering
TimeConnected = today
| MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Adding Working / Peak Features | if WP:
merged_dataset = addWorkingPeakFeatures(merged_dataset)
print("Adding working / peak days") | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Preparing Training dataset Merge Original (and Rolling and Expanding) | # To-be Predicted variable
Y = merged_dataset.statusN
Y = Y.fillna(0)
# Training Data
X = merged_dataset
X = X.drop(X.columns[[0]], axis=1)
# Splitting data
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.67, shuffle=False)
X_train = np.array(X_train)
X_test = np.array(X_test)
Y_train = np.array... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Training Model | # Training
regressor = SupervisedDBNRegression(hidden_layers_structure=HIDDEN_LAYER_STRUCT,
learning_rate_rbm=RBM_LEARNING_RATE,
learning_rate=DBN_LEARNING_RATE,
n_epochs_rbm=RBM_EPOCHS,
... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Testing Model | # Test
min_max_scaler = MinMaxScaler()
X_test = min_max_scaler.fit_transform(X_test)
Y_pred = regressor.predict(X_test)
r2score = r2_score(Y_test, Y_pred)
rmse = np.sqrt(mean_squared_error(Y_test, Y_pred))
mae = mean_absolute_error(Y_test, Y_pred)
print('Done.\nR-squared: %.3f\nRMSE: %.3f \nMAE: %.3f' % (r2score, rmse... | Making Directory
| MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Results and Analysis below | import matplotlib.pyplot as plt | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Printing Predicted and Actual Results | startIndex = merged_dataset.shape[0] - Y_pred.shape[0]
dt = merged_dataset.index[startIndex:,]
temp = []
for i in range(len(Y_pred)):
temp.append(Y_pred[i][0])
d = {'Predicted': temp, 'Actual': Y_test, 'dt': dt}
df = pd.DataFrame(data=d)
df.head()
df.tail() | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Visualize Actual and Predicted Traffic | print(df.dt[0])
startIndex = 0
endIndex = 96
line1 = df.Actual.rdiv(1)
line2 = df.Predicted.rdiv(1)
x = range(0, RBM_EPOCHS * len(HIDDEN_LAYER_STRUCT))
plt.figure(figsize=(20, 4))
plt.plot(line1[startIndex:endIndex], c='red', label="Actual-Congestion")
plt.plot(line2[startIndex:endIndex], c='blue', label="Predicted-Con... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
Visualize trend of loss of RBM and DBN Training | line1 = rbm_error
line2 = dbn_error
x = range(0, RBM_EPOCHS * len(HIDDEN_LAYER_STRUCT))
plt.plot(range(0, RBM_EPOCHS * len(HIDDEN_LAYER_STRUCT)), line1, c='red')
plt.xticks(x)
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()
plt.plot(range(DBN_EPOCHS), line2, c='blue')
plt.xticks(x)
plt.xlabel("Iteration")
plt.... | _____no_output_____ | MIT | PREDICTION-MODEL-1.ipynb | fuouo/TrafficBato |
3D MapWhile representing the configuration space in 3 dimensions isn't entirely practical it's fun (and useful) to visualize things in 3D.In this exercise you'll finish the implementation of `create_grid` such that a 3D grid is returned where cells containing a voxel are set to `True`. We'll then plot the result! | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
plt.rcParams['figure.figsize'] = 16, 16
# This is the same obstacle data from the previous lesson.
filename = 'colliders.csv'
data = np.loadtxt(filename, delimiter=',', dtype='Float64', skiprows=2)
print(data... | _____no_output_____ | MIT | Course02/Voxel-Map.ipynb | thhuang/NOTES-FCND |
Create 3D grid. | voxel_size = 10
voxmap = create_voxmap(data, voxel_size)
print(voxmap.shape) | (81, 91, 21)
| MIT | Course02/Voxel-Map.ipynb | thhuang/NOTES-FCND |
Plot the 3D grid. | fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(voxmap, edgecolor='k')
ax.set_xlim(voxmap.shape[0], 0)
ax.set_ylim(0, voxmap.shape[1])
# add 100 to the height so the buildings aren't so tall
ax.set_zlim(0, voxmap.shape[2]+100//voxel_size)
plt.xlabel('North')
plt.ylabel('East')
plt.show() | _____no_output_____ | MIT | Course02/Voxel-Map.ipynb | thhuang/NOTES-FCND |
Prologue For this project we will use the logistic regression function to model the growth of confirmed Covid-19 case population growth in Bangladesh. The logistic regression function is commonly used in classification problems, and in this project we will be examining how it fares as a regression tool. Both cumulativ... | import pandas as pd
import numpy as np
from datetime import datetime,timedelta
from sklearn.metrics import mean_squared_error
from scipy.optimize import curve_fit
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Connect to Google Drive (where the data is kept) | from google.colab import drive
drive.mount('/content/drive') | Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
| Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Import data and format as needed | df = pd.read_csv('/content/drive/My Drive/Corona-Cases.n-1.csv')
df.tail() | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
As you can see, the format of the date is 'month-day-year'. Let's specify the date column is datetime type. Let's also specify the formatting as %m-%d-%Y. And then, let's find the day when the first confirmed cases of Covid-19 were reported in Bangladesh. | FMT = '%m-%d-%Y'
df['Date'] = pd.to_datetime(df['Date'], format=FMT) | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
We have to initialize the first date of confirmed Covid-19 cases as the datetime variable start_date because we would need it later to calculate the peak. | # Initialize the start date
start_date = datetime.date(df.loc[0, 'Date'])
print('Start date: ', start_date) | Start date: 2020-03-08
| Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Now, for the logistic regression function, we would need a timestep column instead of a date column in the dataframe. So we create a new dataframe called data where we drop the date column and use the index as the timestep column. | # drop date column
data = df['Total cases']
# reset index and create a timestep
data = data.reset_index(drop=False)
# rename columns
data.columns = ['Timestep', 'Total Cases']
# check
data.tail() | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Defining the logistic regression function | def logistic_model(x,a,b,c):
return c/(1+np.exp(-(x-b)/a)) | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
In this formula, we have the variable x that is the time and three parameters: a, b, c.* a is a metric for the speed of infections* b is the day with the estimated maximum growth rate of confirmed Covid-19 cases* c is the maximum number the cumulative confirmed cases will reach by the end of the first outbreak here in ... | # Initialize all the timesteps as x
x = list(data.iloc[:,0])
# Initialize all the Total Cases values as y
y = list(data.iloc[:,1])
# Fit the curve using sklearn's curve_fit method we initialize the parameter p0 with arbitrary values
fit = curve_fit(logistic_model,x,y,p0=[2,100,20000])
(a, b, c), cov = fit
# Print out... | Estimated time of peak between 2020-06-26 and 2020-06-27
Estimated total number of infections betweeen 263873.67841601453 and 266641.8726221719
| Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
To extrapolate the curve to the future, use the fsolve function from scipy. | # Extrapolate
sol = int(fsolve(lambda x : logistic_model(x,a,b,c) - int(c),b)) | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Plot the graph | pred_x = list(range(max(x),sol))
plt.rcParams['figure.figsize'] = [7, 7]
plt.rc('font', size=14)
# Real data
plt.scatter(x,y,label="Real data",color="red")
# Predicted logistic curve
plt.plot(x+pred_x, [logistic_model(i,fit[0][0],fit[0][1],fit[0][2]) for i in x+pred_x], label="Logistic model" )
plt.legend()
plt.xlabel(... | _____no_output_____ | Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
Evaluate the MSE error Evaluating the mean squared error (MSE) is not very meaningful on its own until we can compare it with another predictive method. We can compare MSE of our regression with MSE from another method to check if our logistic regression model works better than the other predictive model. The model wi... | y_pred_logistic = [logistic_model(i,fit[0][0],fit[0][1],fit[0][2])
for i in x]
print('Mean squared error: ', mean_squared_error(y,y_pred_logistic)) | Mean squared error: 3298197.2412489704
| Xnet | Projecting_Covid_19_Case_Growth_in_Bangladesh_Using_Logistic_Regression.ipynb | tanzimtaher/Modeling-Covid-19-Cumulative-Case-Growth-in-Bangladesh-with-Logistic-Regression |
FloPy Plotting SWR Process ResultsThis notebook demonstrates the use of the `SwrObs` and `SwrStage`, `SwrBudget`, `SwrFlow`, and `SwrExchange`, `SwrStructure`, classes to read binary SWR Process observation, stage, budget, reach to reach flows, reach-aquifer exchange, and structure files. It demonstrates these capabi... | %matplotlib inline
from IPython.display import Image
import os
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# run installed version of flopy or add local path
try:
import flopy
except:
fpth = os.path.abspath(os.path.join('..', '..'))
sys.path.append(fpth)
impor... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Load SWR Process observationsCreate an instance of the `SwrObs` class and load the observation data. | sobj = flopy.utils.SwrObs(os.path.join(datapth, files[0]))
ts = sobj.get_data() | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Plot the data from the binary SWR Process observation file | fig = plt.figure(figsize=(6, 12))
ax1 = fig.add_subplot(3, 1, 1)
ax1.semilogx(ts['totim']/3600., -ts['OBS1'], label='OBS1')
ax1.semilogx(ts['totim']/3600., -ts['OBS2'], label='OBS2')
ax1.semilogx(ts['totim']/3600., -ts['OBS9'], label='OBS3')
ax1.set_ylabel('Flow, in cubic meters per second')
ax1.legend()
ax = fig.add_... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Load the same data from the individual binary SWR Process filesLoad discharge data from the flow file. The flow file contains the simulated flow between connected reaches for each connection in the model. | sobj = flopy.utils.SwrFlow(os.path.join(datapth, files[1]))
times = np.array(sobj.get_times())/3600.
obs1 = sobj.get_ts(irec=1, iconn=0)
obs2 = sobj.get_ts(irec=14, iconn=13)
obs4 = sobj.get_ts(irec=4, iconn=3)
obs5 = sobj.get_ts(irec=5, iconn=4) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Load discharge data from the structure file. The structure file contains the simulated structure flow for each reach with a structure. | sobj = flopy.utils.SwrStructure(os.path.join(datapth, files[2]))
obs3 = sobj.get_ts(irec=17, istr=0) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Load stage data from the stage file. The flow file contains the simulated stage for each reach in the model. | sobj = flopy.utils.SwrStage(os.path.join(datapth, files[3]))
obs6 = sobj.get_ts(irec=13) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Load budget data from the budget file. The budget file contains the simulated budget for each reach group in the model. The budget file also contains the stage data for each reach group. In this case the number of reach groups equals the number of reaches in the model. | sobj = flopy.utils.SwrBudget(os.path.join(datapth, files[4]))
obs7 = sobj.get_ts(irec=17) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Plot the data loaded from the individual binary SWR Process files.Note that the plots are identical to the plots generated from the binary SWR observation data. | fig = plt.figure(figsize=(6, 12))
ax1 = fig.add_subplot(3, 1, 1)
ax1.semilogx(times, obs1['flow'], label='OBS1')
ax1.semilogx(times, obs2['flow'], label='OBS2')
ax1.semilogx(times, -obs3['strflow'], label='OBS3')
ax1.set_ylabel('Flow, in cubic meters per second')
ax1.legend()
ax = fig.add_subplot(3, 1, 2, sharex=ax1)
... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Plot simulated water surface profilesSimulated water surface profiles can be created using the `ModelCrossSection` class. Several things that we need in addition to the stage data include reach lengths and bottom elevations. We load these data from an existing file. | sd = np.genfromtxt(os.path.join(datapth, 'SWR004.dis.ref'), names=True) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
The contents of the file are shown in the cell below. | fc = open(os.path.join(datapth, 'SWR004.dis.ref')).readlines()
fc | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Create an instance of the `SwrStage` class for SWR Process stage data. | sobj = flopy.utils.SwrStage(os.path.join(datapth, files[3])) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Create a selection condition (`iprof`) that can be used to extract data for the reaches of interest (reaches 0, 1, and 8 through 17). Use this selection condition to extract reach lengths (from `sd['RLEN']`) and the bottom elevation (from `sd['BELEV']`) for the reaches of interest. The selection condition will also be... | iprof = sd['IRCH'] > 0
iprof[2:8] = False
dx = np.extract(iprof, sd['RLEN'])
belev = np.extract(iprof, sd['BELEV']) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Create a fake model instance so that the `ModelCrossSection` class can be used. | ml = flopy.modflow.Modflow()
dis = flopy.modflow.ModflowDis(ml, nrow=1, ncol=dx.shape[0], delr=dx, top=4.5, botm=belev.reshape(1,1,12)) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Create an array with the x position at the downstream end of each reach, which will be used to color the plots below each reach. | x = np.cumsum(dx) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
Plot simulated water surface profiles for 8 times. | fig = plt.figure(figsize=(12, 12))
for idx, v in enumerate([19, 29, 34, 39, 44, 49, 54, 59]):
ax = fig.add_subplot(4, 2, idx+1)
s = sobj.get_data(idx=v)
stage = np.extract(iprof, s['stage'])
xs = flopy.plot.ModelCrossSection(model=ml, line={'Row': 0})
xs.plot_fill_between(stage.reshape(1,1,12), colo... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb | gyanz/flopy |
[제가 미리 만들어놓은 이 링크](https://colab.research.google.com/github/heartcored98/Standalone-DeepLearning/blob/master/Lec4/Lab6_result_report.ipynb)를 통해 Colab에서 바로 작업하실 수 있습니다! 런타임 유형은 python3, GPU 가속 확인하기! | !mkdir results
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import argparse
import numpy as np
import time
from copy import deepcopy # Add Deepcopy for args | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
Data Preparation | transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainset, valset = torch.utils.data.random_split(train... | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
Model Architecture | class MLP(nn.Module):
def __init__(self, in_dim, out_dim, hid_dim, n_layer, act, dropout, use_bn, use_xavier):
super(MLP, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.hid_dim = hid_dim
self.n_layer = n_layer
self.act = act
self.dropout = d... | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
Train, Validate, Test and Experiment | def train(net, partition, optimizer, criterion, args):
trainloader = torch.utils.data.DataLoader(partition['train'],
batch_size=args.train_batch_size,
shuffle=True, num_workers=2)
net.train()
correct = 0
total... | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
Manage Experiment Result | import hashlib
import json
from os import listdir
from os.path import isfile, join
import pandas as pd
def save_exp_result(setting, result):
exp_name = setting['exp_name']
del setting['epoch']
del setting['test_batch_size']
hash_key = hashlib.sha1(str(setting).encode()).hexdigest()[:6]
filename = ... | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
Experiment | # ====== Random Seed Initialization ====== #
seed = 123
np.random.seed(seed)
torch.manual_seed(seed)
parser = argparse.ArgumentParser()
args = parser.parse_args("")
args.exp_name = "exp1_n_layer_hid_dim"
# ====== Model Capacity ====== #
args.in_dim = 3072
args.out_dim = 10
args.hid_dim = 100
args.act = 'relu'
# ====... | _____no_output_____ | MIT | Lec4/Lab6_result_report.ipynb | Cho-D-YoungRae/Standalone-DeepLearning |
1、可视化DataGeneratorHomographyNet模块都干了什么 | import glob
import os
import cv2
import numpy as np
from dataGenerator import DataGeneratorHomographyNet
img_dir = os.path.join(os.path.expanduser("~"), "/home/nvidia/test2017")
img_ext = ".jpg"
img_paths = glob.glob(os.path.join(img_dir, '*' + img_ext))
dg = DataGeneratorHomographyNet(img_paths, input_dim=(240, 240))
... | _____no_output_____ | MIT | Demo.ipynb | 4nthon/HomographyNet |
2、开始训练 | import os
import glob
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import keras
from keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
import tensorflow as tf
from homographyNet import HomographyNet
import dataGenerator as dg
keras.__version__
batch_size ... | Epoch 1/15
1373/20131 [=>............................] - ETA: 1:18:50 - loss: 1615938396204833.0000 - mean_squared_error: 1615938396204833.0000 | MIT | Demo.ipynb | 4nthon/HomographyNet |
#整个图看看
history_df = pd.DataFrame(history.history)
history_df.to_csv(os.path.join(model_dir, 'history.csv'))
history_df[['loss', 'val_loss']].plot()
history_df[['mean_squared_error', 'val_mean_squared_error']].plot()
plt.show() | _____no_output_____ | MIT | Demo.ipynb | 4nthon/HomographyNet | |
预测&评估 | TODO | _____no_output_____ | MIT | Demo.ipynb | 4nthon/HomographyNet |
Diamond Prices: Model Tuning and Improving Performance Importing libraries | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
pd.options.mode.chained_assignment = None
%matplotlib inline | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Loading the dataset | DATA_DIR = '../data'
FILE_NAME = 'diamonds.csv'
data_path = os.path.join(DATA_DIR, FILE_NAME)
diamonds = pd.read_csv(data_path) | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Preparing the dataset | ## Preparation done from Chapter 2
diamonds = diamonds.loc[(diamonds['x']>0) | (diamonds['y']>0)]
diamonds.loc[11182, 'x'] = diamonds['x'].median()
diamonds.loc[11182, 'z'] = diamonds['z'].median()
diamonds = diamonds.loc[~((diamonds['y'] > 30) | (diamonds['z'] > 30))]
diamonds = pd.concat([diamonds, pd.get_dummies(dia... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Train-test split | X = diamonds.drop(['cut','color','clarity','price'], axis=1)
y = diamonds['price']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=7) | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Standarization: centering and scaling | numerical_features = ['carat', 'depth', 'table', 'dim_index']
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train[numerical_features])
X_train.loc[:, numerical_features] = scaler.fit_transform(X_train[numerical_features])
X_test.loc[:, numerical_features] = scaler.transform(X_t... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Optimizing a single hyper-parameter | X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=13)
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_absolute_error
candidates = np.arange(4,16)
mae_metrics = []
for k in candidates:
model = KNeighborsRegressor(n_neighbors=k, weights... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Recalculating train-set split | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=7)
scaler = StandardScaler()
scaler.fit(X_train[numerical_features])
X_train.loc[:, numerical_features] = scaler.fit_transform(X_train[numerical_features])
X_test.loc[:, numerical_features] = scaler.transform(X_test[numerical_features... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Optimizing with cross-validation | from sklearn.model_selection import cross_val_score
candidates = np.arange(4,16)
mean_mae = []
std_mae = []
for k in candidates:
model = KNeighborsRegressor(n_neighbors=k, weights='distance', metric='minkowski', leaf_size=50, n_jobs=4)
cv_results = cross_val_score(model, X_train, y_train, scoring='neg_mean_abso... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Improving Performance Improving our diamond price predictions Fitting a neural network | from keras.models import Sequential
from keras.layers import Dense
n_input = X_train.shape[1]
n_hidden1 = 32
n_hidden2 = 16
n_hidden3 = 8
nn_reg = Sequential()
nn_reg.add(Dense(units=n_hidden1, activation='relu', input_shape=(n_input,)))
nn_reg.add(Dense(units=n_hidden2, activation='relu'))
nn_reg.add(Dense(units=n_h... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Transforming the target | diamonds['price'].hist(bins=25, ec='k', figsize=(8,5))
plt.title("Distribution of diamond prices", fontsize=16)
plt.grid(False);
y_train = np.log(y_train)
pd.Series(y_train).hist(bins=25, ec='k', figsize=(8,5))
plt.title("Distribution of log diamond prices", fontsize=16)
plt.grid(False);
nn_reg = Sequential()
nn_reg.ad... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Analyzing the results | fig, ax = plt.subplots(figsize=(8,5))
residuals = y_test - y_pred
ax.scatter(y_test, residuals, s=3)
ax.set_title('Residuals vs. Observed Prices', fontsize=16)
ax.set_xlabel('Observed prices', fontsize=14)
ax.set_ylabel('Residuals', fontsize=14)
ax.grid();
mask_7500 = y_test <=7500
mae_neural_less_7500 = mean_absolute_... | _____no_output_____ | MIT | Chapter08/.ipynb_checkpoints/ch8-diamond-prices-model-tuning-checkpoint.ipynb | arifmudi/Hands-On-Predictive-Analytics-with-Python |
Visualizing COVID-19 Hospital Dataset with Seaborn**Pre-Work:**1. Ensure that Jupyter Notebook, Python 3, and seaborn (which will also install dependency libraries if not already installed) are installed. (See resources below for installation instructions.) **Instructions:**1. Using Python, import main visualization l... | # import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# read JSON data in via healthdata.gov's API endpoint - https://healthdata.gov/resource/g62h-syeh.json?$limit=50000
# because the SODA API defaults to 1,000 rows, we're going to change that with the $limit pa... | _____no_output_____ | CC0-1.0 | materials/seaborn_data_viz_complete_with_outputs.ipynb | kthrog/dataviz_workshop |
F/9 WFS Camera dev | f9 = F9WFSCam()
f9.process_events()
v = f9.get_vector("SBIG CCD", "CCD_BINNING")
e = v.elements[0]
for e in v.elements:
print("%s %s" % (e.getName(), e.get_int()))
f9.connected
f9.process_events()
f9.wfs_config()
f9.default_config()
f9.binning
f9.process_events()
f = f9.expose(exptime=1.0, exptype="Light")
norm = v... | _____no_output_____ | BSD-3-Clause | notebooks/indi_dev.ipynb | tepickering/sbigclient |
Temporal-Difference MethodsIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.While we have provided some starter code, you are welcome to erase these hints and write your code from scratch.--- Part 0: Explore CliffWalkingEnvWe begin by importing the necessary packages. | import sys
import gym
import numpy as np
import random
import math
from collections import defaultdict, deque
import matplotlib.pyplot as plt
%matplotlib inline
import check_test
from plot_utils import plot_values | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Use the code cell below to create an instance of the [CliffWalking](https://github.com/openai/gym/blob/master/gym/envs/toy_text/cliffwalking.py) environment. | env = gym.make('CliffWalking-v0') | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
The agent moves through a $4\times 12$ gridworld, with states numbered as follows:```[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]```At the start of any episode, sta... | print(env.action_space)
print(env.observation_space) | Discrete(4)
Discrete(48)
| MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function._**Note**: You can safely ignore the values of the cli... | # define the optimal state-value function
V_opt = np.zeros((4,12))
V_opt[0][0:13] = -np.arange(3, 15)[::-1]
V_opt[1][0:13] = -np.arange(3, 15)[::-1] + 1
V_opt[2][0:13] = -np.arange(3, 15)[::-1] + 2
V_opt[3][0] = -13
plot_values(V_opt) | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Part 1: TD Control: SarsaIn this section, you will write your own implementation of the Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`... | def update_Q_sarsa(alpha, gamma, Q, state, action, reward, next_state=None, next_action=None):
"""Returns updated Q-value for the most recent experience."""
current = Q[state][action] # estimate in Q-table (for current state, action pair)
# get value of state, action pair at next time step
Qsa_next = Q... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsa = sarsa(env, 50000, .01)
# print the estimated optimal policy
policy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_check', policy_sarsa)
... | Episode 50000/50000 | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Part 2: TD Control: Q-learningIn this section, you will write your own implementation of the Q-learning control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction... | def update_Q_sarsamax(alpha, gamma, Q, state, action, reward, next_state=None):
"""Returns updated Q-value for the most recent experience."""
current = Q[state][action] # estimate in Q-table (for current state, action pair)
Qsa_next = np.max(Q[next_state]) if next_state is not None else 0 # value of next ... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd l... | # obtain the estimated optimal policy and corresponding action-value function
Q_sarsamax = q_learning(env, 5000, .01)
# print the estimated optimal policy
policy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))
check_test.run_check('td_control_chec... | Episode 5000/5000 | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Part 3: TD Control: Expected SarsaIn this section, you will write your own implementation of the Expected Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment int... | def update_Q_expsarsa(alpha, gamma, nA, eps, Q, state, action, reward, next_state=None):
"""Returns updated Q-value for the most recent experience."""
current = Q[state][action] # estimate in Q-table (for current state, action pair)
policy_s = np.ones(nA) * eps / nA # current policy (for next state... | _____no_output_____ | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ... | # obtain the estimated optimal policy and corresponding action-value function
Q_expsarsa = expected_sarsa(env, 50000, 1)
# print the estimated optimal policy
policy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12)
check_test.run_check('td_control_che... | Episode 50000/50000 | MIT | temporal-difference/Temporal_Difference_Solution.ipynb | JeroenSweerts/deep-reinforcement-learning |
Lists A list stores many values in a single structure. Use an item’s index to fetch it from a list. Lists’ values can be replaced by assigning to them. Appending items to a list lengthens it. Use `del` to remove items from a list entirely. The empty list contains no values. Lists may contain values of different... | %load ../exercises/lists-blanks.py
%load ../exercises/lists-string-conversion.py | _____no_output_____ | CC-BY-4.0 | files/notebooks/09-Lists.ipynb | mforneris/introduction_to_python_course |
Measure without a LoopIf you have a parameter that returns a whole array at once, often you want to measure it directly into a DataSet.This shows how that works in QCoDeS | %matplotlib nbagg
import qcodes as qc
import numpy as np
# import dummy driver for the tutorial
from qcodes.tests.instrument_mocks import DummyInstrument, DummyChannelInstrument
from qcodes.measure import Measure
from qcodes.actions import Task
dac1 = DummyInstrument(name="dac")
dac2 = DummyChannelInstrument(name="dac... | 2020-03-24 18:45:32,769 ¦ qcodes.instrument.base ¦ WARNING ¦ base ¦ snapshot_base ¦ 214 ¦ [dac2_ChanA(DummyChannel)] Snapshot: Could not update parameter: dummy_sp_axis
2020-03-24 18:45:32,798 ¦ qcodes.instrument.base ¦ WARNING ¦ base ¦ snapshot_base ¦ 214 ¦ [dac2_ChanB(DummyChannel)] Snapshot: Could not update paramet... | MIT | docs/examples/legacy/Measure without a Loop.ipynb | jakeogh/Qcodes |
Instantiates all the instruments needed for the demoFor this tutorial we're going to use the regular parameters (c0, c1, c2, vsd) and ArrayGetter, which is just a way to construct a parameter that returns a whole array at once out of simple parameters, as well as AverageAndRaw, which returns a scalar *and* an array to... | data = Measure(
Task(dac1.dac1.set, 0),
dac2.A.dummy_array_parameter,
Task(dac1.dac1.set, 2),
dac2.A.dummy_array_parameter,
).run() | DataSet:
location = 'data/2020-03-24/#013_{name}_18-45-41'
<Type> | <array_id> | <array.name> | <array.shape>
Measured | dac2_ChanA_dummy_array_parameter_1 | dummy_array_parameter | (5,)
Measured | dac2_ChanA_dummy_array_parameter_3 | dummy_array_parameter | (5,)
acquired ... | MIT | docs/examples/legacy/Measure without a Loop.ipynb | jakeogh/Qcodes |
Loads pre-trained model and get prediction on validation samples 1. InfoPlease provide path to the relevant config file | config_file_path = "../configs/pretrained/config_model1.json" | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
2. Importing required modules | import os
import cv2
import sys
import importlib
import torch
import torchvision
import numpy as np
sys.path.insert(0, "../")
# imports for displaying a video an IPython cell
import io
import base64
from IPython.display import HTML
from data_parser import WebmDataset
from data_loader_av import VideoFolder
from model... | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
3. Loading configuration file, model definition and its path | # Load config file
config = load_json_config(config_file_path)
# set column model
column_cnn_def = importlib.import_module("{}".format(config['conv_model']))
model_name = config["model_name"]
print("=> Name of the model -- {}".format(model_name))
# checkpoint path to a trained model
checkpoint_path = os.path.join("..... | => Name of the model -- model3D_1
=> Checkpoint path --> ../trained_models/pretrained/model3D_1/model_best.pth.tar
| Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
3. Load model _Note: without cuda() for ease_ | model = MultiColumn(config['num_classes'], column_cnn_def.Model, int(config["column_units"]))
model.eval();
print("=> loading checkpoint")
checkpoint = torch.load(checkpoint_path)
checkpoint['state_dict'] = remove_module_from_checkpoint_state_dict(
checkpoint['state_dict'])... | => loading checkpoint
=> loaded checkpoint '../trained_models/pretrained/model3D_1/model_best.pth.tar' (epoch 55)
| Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
4. Load data | # Center crop videos during evaluation
transform_eval_pre = ComposeMix([
[Scale(config['input_spatial_size']), "img"],
[torchvision.transforms.ToPILImage(), "img"],
[torchvision.transforms.CenterCrop(config['input_spatial_size']), "img"]
])
transform_post = ComposeMix([
[torchv... | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
5. Get predictions 5.1. Select random sample (or specify the index) | selected_indx = np.random.randint(len(val_data))
# selected_indx = 136 | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
5.2 Get data in required format | input_data, target, item_id = val_data[selected_indx]
input_data = input_data.unsqueeze(0)
print("Id of the video sample = {}".format(item_id))
print("True label --> {} ({})".format(target, dict_two_way[target]))
if config['nclips_val'] > 1:
input_var = list(input_data.split(config['clip_size'], 2))
for idx, in... | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
5.3 Compute output from the model | output = model(input_var).squeeze(0)
output = torch.nn.functional.softmax(output, dim=0)
# compute top5 predictions
pred_prob, pred_top5 = output.data.topk(5)
pred_prob = pred_prob.numpy()
pred_top5 = pred_top5.numpy() | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
5.4 Visualize predictions | print("Id of the video sample = {}".format(item_id))
print("True label --> {} ({})".format(target, dict_two_way[target]))
print("\nTop-5 Predictions:")
for i, pred in enumerate(pred_top5):
print("Top {} :== {}. Prob := {:.2f}%".format(i + 1, dict_two_way[pred], pred_prob[i] * 100))
path_to_vid = os.path.join(config... | _____no_output_____ | Apache-2.0 | notebooks/get_prediction_from_pre_trained_model.ipynb | raghavgoyal14/smth-smth-v2-baseline-with-models |
Bar chartsThis is 'abusing' the scatter object to create a 3d bar chart | import ipyvolume as ipv
import numpy as np
# set up data similar to animation notebook
u_scale = 10
Nx, Ny = 30, 15
u = np.linspace(-u_scale, u_scale, Nx)
v = np.linspace(-u_scale, u_scale, Ny)
x, y = np.meshgrid(u, v, indexing='ij')
r = np.sqrt(x**2+y**2)
x = x.flatten()
y = y.flatten()
r = r.flatten()
time = np.lin... | _____no_output_____ | MIT | docs/source/examples/bars.ipynb | rafique/ipyvolume |
We now make boxes, that fit exactly in the volume, by giving them a size of 1, in domain coordinates (so 1 unit as read of by the x-axis etc) | # make the size 1, in domain coordinates (so 1 unit as read of by the x-axis etc)
s.geo = 'box'
s.size = 1
s.size_x_scale = fig.scales['x']
s.size_y_scale = fig.scales['y']
s.size_z_scale = fig.scales['z']
s.shader_snippets = {'size':
'size_vector.y = SCALE_SIZE_Y(aux_current); '
}
| _____no_output_____ | MIT | docs/source/examples/bars.ipynb | rafique/ipyvolume |
Using a shader snippet (that runs on the GPU), we set the y size equal to the aux value. However, since the box has size 1 around the origin of (0,0,0), we need to translate it up in the y direction by 0.5. | s.shader_snippets = {'size':
'size_vector.y = SCALE_SIZE_Y(aux_current) - SCALE_SIZE_Y(0.0) ; '
}
s.geo_matrix = [dx, 0, 0, 0, 0, 1, 0, 0, 0, 0, dy, 0, 0.0, 0.5, 0, 1] | _____no_output_____ | MIT | docs/source/examples/bars.ipynb | rafique/ipyvolume |
Since we see the boxes with negative sizes inside out, we made the material double sided | # since we see the boxes with negative sizes inside out, we made the material double sided
s.material.side = "DoubleSide"
# Now also include, color, which containts rgb values
color = np.array([[np.cos(r + t), 1-np.abs(z[i]), 0.1+z[i]*0] for i, t in enumerate(time)])
color = np.transpose(color, (0, 2, 1)) # flip the la... | _____no_output_____ | MIT | docs/source/examples/bars.ipynb | rafique/ipyvolume |
Spherical bar charts | # Create spherical coordinates
u = np.linspace(0, 1, Nx)
v = np.linspace(0, 1, Ny)
u, v = np.meshgrid(u, v, indexing='ij')
phi = u * 2 * np.pi
theta = v * np.pi
radius = 1
xs = radius * np.cos(phi) * np.sin(theta)
ys = radius * np.sin(phi) * np.sin(theta)
zs = radius * np.cos(theta)
xs = xs.flatten()
ys = ys.flatten()
... | _____no_output_____ | MIT | docs/source/examples/bars.ipynb | rafique/ipyvolume |
ReinforcementLearning: a)UCB, b)ThompsonSampling**--------------------------------------------------------------------------------------------------------------------------****--------------------------------------------------------------------------------------------------------------------------****-----------------... | # Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import random
warnings.filterwarnings('ignore')
# Creating the dataset by generating random values(0 & 1) with different probabilities for each 'Adv'
# Len.Dataset=20000
np.random.seed... | _____no_output_____ | MIT | Reinforcement_Learning_UCB_ThompsonSampling.ipynb | tourloukisg/ReinforcementLearning_UCB_ThompsonSampling |
UCB | #Upper Confidence Bound Algorithm
def ucb_rewards(Users_Num):
#Total Number of Advertisements
Ad_Num=9
#List of advertisements that are selected by the algorithm based on the user clicks at each step (initially empty)
Ad_to_Display=[]
# Count how many times each advertisement is selected
Ad_Cnt_... | _____no_output_____ | MIT | Reinforcement_Learning_UCB_ThompsonSampling.ipynb | tourloukisg/ReinforcementLearning_UCB_ThompsonSampling |
Thompson Sampling | #Thompson Sampling Algorithm
def TSampling_rewards(Users_Num):
#Total Number of Advertisements
Ad_Num=9
#List of advertisements that are selected by the algorithm based on the user clicks at each step (initially empty)
Ad_to_Display=[]
# Count each time an advertisement gets reward=1
Ad_Count_Re... | UCB Total Rewards 2000 samples: 1082
UCB Total Rewards 5000 samples: 2738
UCB Total Rewards 10000 samples: 5588
UCB Total Rewards 20000 samples: 11402
TSampling Total Rewards 2000 samples: 1148
TSampling Total Rewards 5000 samples: 2937
TSampling Total Rewards 10000 samples: 5904
TSampling Total Rewards 20000 samples... | MIT | Reinforcement_Learning_UCB_ThompsonSampling.ipynb | tourloukisg/ReinforcementLearning_UCB_ThompsonSampling |
Compute a Galactic orbit for a star using Gaia dataAuthor(s): Adrian Price-Whelan Learning goalsIn this tutorial, we will retrieve the sky coordinates, astrometry, and radial velocity for a star — [Kepler-444](https://en.wikipedia.org/wiki/Kepler-444) — and compute its orbit in the default Milky Way mass model impleme... | import astropy.coordinates as coord
import astropy.units as u
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pyia import GaiaData
# Gala
import gala.dynamics as gd
import gala.potential as gp | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.