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 |
|---|---|---|---|---|---|
In the Cartpole environment:- `observation` is an array of 4 floats: - the position and velocity of the cart - the angular position and velocity of the pole - `reward` is a scalar float value- `action` is a scalar integer with only two possible values: - `0` — "move left" - `1` — "move right" | time_step = env.reset()
print('Time step:')
print(time_step)
action = np.array(1, dtype=np.int32)
next_time_step = env.step(action)
print('Next time step:')
print(next_time_step) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Usually two environments are instantiated: one for training and one for evaluation. | train_py_env = suite_gym.load(env_name)
eval_py_env = suite_gym.load(env_name) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
The Cartpole environment, like most environments, is written in pure Python. This is converted to TensorFlow using the `TFPyEnvironment` wrapper.The original environment's API uses Numpy arrays. The `TFPyEnvironment` converts these to `Tensors` to make it compatible with Tensorflow agents and policies. | train_env = tf_py_environment.TFPyEnvironment(train_py_env)
eval_env = tf_py_environment.TFPyEnvironment(eval_py_env) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
AgentThe algorithm used to solve an RL problem is represented by an `Agent`. TF-Agents provides standard implementations of a variety of `Agents`, including:- [DQN](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf) (used in this tutorial)- [REINFORCE](http://www-anw.cs.umass.edu/~barto/courses/... | fc_layer_params = (100,)
q_net = q_network.QNetwork(
train_env.observation_spec(),
train_env.action_spec(),
fc_layer_params=fc_layer_params) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Now use `tf_agents.agents.dqn.dqn_agent` to instantiate a `DqnAgent`. In addition to the `time_step_spec`, `action_spec` and the QNetwork, the agent constructor also requires an optimizer (in this case, `AdamOptimizer`), a loss function, and an integer step counter. | optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)
train_step_counter = tf.Variable(0)
agent = dqn_agent.DqnAgent(
train_env.time_step_spec(),
train_env.action_spec(),
q_network=q_net,
optimizer=optimizer,
td_errors_loss_fn=common.element_wise_squared_loss,
train_step_co... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
PoliciesA policy defines the way an agent acts in an environment. Typically, the goal of reinforcement learning is to train the underlying model until the policy produces the desired outcome.In this tutorial:- The desired outcome is keeping the pole balanced upright over the cart.- The policy returns an action (le... | eval_policy = agent.policy
collect_policy = agent.collect_policy | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Policies can be created independently of agents. For example, use `tf_agents.policies.random_tf_policy` to create a policy which will randomly select an action for each `time_step`. | random_policy = random_tf_policy.RandomTFPolicy(train_env.time_step_spec(),
train_env.action_spec()) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
To get an action from a policy, call the `policy.action(time_step)` method. The `time_step` contains the observation from the environment. This method returns a `PolicyStep`, which is a named tuple with three components:- `action` — the action to be taken (in this case, `0` or `1`)- `state` — used for stateful (tha... | example_environment = tf_py_environment.TFPyEnvironment(
suite_gym.load('CartPole-v0'))
time_step = example_environment.reset()
random_policy.action(time_step) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Metrics and EvaluationThe most common metric used to evaluate a policy is the average return. The return is the sum of rewards obtained while running a policy in an environment for an episode. Several episodes are run, creating an average return.The following function computes the average return of a policy, given the... | #@test {"skip": true}
def compute_avg_return(environment, policy, num_episodes=10):
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(acti... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Running this computation on the `random_policy` shows a baseline performance in the environment. | compute_avg_return(eval_env, random_policy, num_eval_episodes) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Replay BufferThe replay buffer keeps track of data collected from the environment. This tutorial uses `tf_agents.replay_buffers.tf_uniform_replay_buffer.TFUniformReplayBuffer`, as it is the most common. The constructor requires the specs for the data it will be collecting. This is available from the agent using the `c... | replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(
data_spec=agent.collect_data_spec,
batch_size=train_env.batch_size,
max_length=replay_buffer_max_length) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
For most agents, `collect_data_spec` is a named tuple called `Trajectory`, containing the specs for observations, actions, rewards, and other items. | agent.collect_data_spec
agent.collect_data_spec._fields | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Data CollectionNow execute the random policy in the environment for a few steps, recording the data in the replay buffer. | #@test {"skip": true}
def collect_step(environment, policy, buffer):
time_step = environment.current_time_step()
action_step = policy.action(time_step)
next_time_step = environment.step(action_step.action)
traj = trajectory.from_transition(time_step, action_step, next_time_step)
# Add trajectory to the repla... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
The replay buffer is now a collection of Trajectories. | # For the curious:
# Uncomment to peel one of these off and inspect it.
# iter(replay_buffer.as_dataset()).next() | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
The agent needs access to the replay buffer. This is provided by creating an iterable `tf.data.Dataset` pipeline which will feed data to the agent.Each row of the replay buffer only stores a single observation step. But since the DQN Agent needs both the current and next observation to compute the loss, the dataset pip... | # Dataset generates trajectories with shape [Bx2x...]
dataset = replay_buffer.as_dataset(
num_parallel_calls=3,
sample_batch_size=batch_size,
num_steps=2).prefetch(3)
dataset
iterator = iter(dataset)
print(iterator)
# For the curious:
# Uncomment to see what the dataset iterator is feeding to the agen... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Training the agentTwo things must happen during the training loop:- collect data from the environment- use that data to train the agent's neural network(s)This example also periodicially evaluates the policy and prints the current score.The following will take ~5 minutes to run. | #@test {"skip": true}
try:
%%time
except:
pass
# (Optional) Optimize by wrapping some of the code in a graph using TF function.
agent.train = common.function(agent.train)
# Reset the train step
agent.train_step_counter.assign(0)
# Evaluate the agent's policy once before training.
avg_return = compute_avg_return(... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Visualization PlotsUse `matplotlib.pyplot` to chart how the policy improved during training.One iteration of `Cartpole-v0` consists of 200 time steps. The environment gives a reward of `+1` for each step the pole stays up, so the maximum return for one episode is 200. The charts shows the return increasing towards th... | #@test {"skip": true}
iterations = range(0, num_iterations + 1, eval_interval)
plt.plot(iterations, returns)
plt.ylabel('Average Return')
plt.xlabel('Iterations')
plt.ylim(top=250) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Videos Charts are nice. But more exciting is seeing an agent actually performing a task in an environment. First, create a function to embed videos in the notebook. | def embed_mp4(filename):
"""Embeds an mp4 file in the notebook."""
video = open(filename,'rb').read()
b64 = base64.b64encode(video)
tag = '''
<video width="640" height="480" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>'''.for... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Now iterate through a few episodes of the Cartpole game with the agent. The underlying Python environment (the one "inside" the TensorFlow environment wrapper) provides a `render()` method, which outputs an image of the environment state. These can be collected into a video. | def create_policy_eval_video(policy, filename, num_episodes=5, fps=30):
filename = filename + ".mp4"
with imageio.get_writer(filename, fps=fps) as video:
for _ in range(num_episodes):
time_step = eval_env.reset()
video.append_data(eval_py_env.render())
while not time_step.is_last():
ac... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
For fun, compare the trained agent (above) to an agent moving randomly. (It does not do as well.) | create_policy_eval_video(random_policy, "random-agent") | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
CB LAD matchWe geocode CrunchBase with Local Authority District data. 0. Preamble | %run ../notebook_preamble.ipy
import geopandas as gp
from shapely.geometry import Point | _____no_output_____ | MIT | notebooks/dev/04_jmg_cb_lad_merge.ipynb | Juan-Mateos/cb_processing |
Load CB data | cb = pd.read_csv('../../data/processed/18_9_2019_cb_sector_labelled.csv')
shapes = gp.read_file('../../data/external/lad_shape/Local_Authority_Districts_December_2018_Boundaries_GB_BFC.shp')
#Create geodataframe
cb_uk = cb.loc[cb['country_alpha_2']=='GB']
cb_uk_geo = gp.GeoDataFrame(cb_uk, geometry=[Point(x, y) for x,... | _____no_output_____ | MIT | notebooks/dev/04_jmg_cb_lad_merge.ipynb | Juan-Mateos/cb_processing |
Names to keep | keep_cols = list(cb.columns) + ['lad18nm','lad18cd']
cb_joined_keep = cb_joined[keep_cols]
#Concatenate cb with the names above
cb_all = pd.concat([cb.loc[cb['country_alpha_2']!='GB'],cb_joined_keep],axis=0)[keep_cols]
cb_all.to_csv('../../data/processed/18_9_2019_cb_sector_labelled_geo.csv')
#from data_getters.labs.co... | _____no_output_____ | MIT | notebooks/dev/04_jmg_cb_lad_merge.ipynb | Juan-Mateos/cb_processing |
**Riego de Dios, Celyssa Chryse** **Question 1.** Create a Python code that displays a square matrix whose length is 5 (10 points) | import numpy as np #Import library
A = np.array([[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]]) #SET OF 5X5 MATRIX
print("Square Matrix whose length is 5")
print(A) | Square Matrix whose length is 5
[[1 2 3 4 5]
[2 3 4 5 1]
[3 4 5 1 2]
[4 5 1 2 3]
[5 1 2 3 4]]
| Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
**Question 2.** Create a Python code that displays a square matrix whose elements below the principal diagonal are zero (10 points) | import numpy as np
B = np.triu([[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]])
print("Square Matrix whose elements below the principal diagonal are zero")
print(B) | Square Matrix whose elements below the principal diagonal are zero
[[1 2 3 4 5]
[0 3 4 5 1]
[0 0 5 1 2]
[0 0 0 2 3]
[0 0 0 0 4]]
| Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
**Question 3.** Create a Python code that displays a square matrix which is symmetrical (10 points) | import numpy as np
F = np.array([[1,2,3],[2,3,3],[3,4,-2]])
print("Symmetric form of Matrix")
print(F)
G = np.transpose(F)
print("Transpose of the Matrix")
print(G) | Symmetric form of Matrix
[[ 1 2 3]
[ 2 3 3]
[ 3 4 -2]]
Transpose of the Matrix
[[ 1 2 3]
[ 2 3 4]
[ 3 3 -2]]
| Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
**Question 4.** What is the inverse of matrix C? Show your solution by python coding. (20 points) | #Python Program to Inverse a 3x3 Matrix C = ([[1,2,3],[2,3,3],[3,4,-2]])
C = np.array([[1,2,3],[2,3,3],[3,4,-2]])
print(C,"\n")
D = np.linalg.inv(C)
print(D) | [[ 1 2 3]
[ 2 3 3]
[ 3 4 -2]]
[[-3.6 3.2 -0.6]
[ 2.6 -2.2 0.6]
[-0.2 0.4 -0.2]]
| Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
**Question 5.** What is the determinant of the given matrix in Question 4? Show your solution by python coding. (20 points) | import numpy as np
C = np.array([[1,2,3],[2,3,3],[3,4,-2]])
print(C,"\n")
H = np.linalg.det(C)
print(round(H)) | [[ 1 2 3]
[ 2 3 3]
[ 3 4 -2]]
5
| Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
**Question 6.** Find the roots of the linear equations by showing its python codes (30 points) | import numpy as np
A = np.array([[5,4,1],[10,9,4],[10,13,15]])
print(A,"\n")
A_ = np.linalg.inv(A)
print(A_,"\n")
B = np.array([[3.4],[8.8],[19.2]])
print(B,"\n")
AA_ = np.dot(A,A_)
print(AA_,"\n")
BA_ = np.dot(A_,B)
print(BA_) | [[ 5 4 1]
[10 9 4]
[10 13 15]]
[[ 5.53333333 -3.13333333 0.46666667]
[-7.33333333 4.33333333 -0.66666667]
[ 2.66666667 -1.66666667 0.33333333]]
[[ 3.4]
[ 8.8]
[19.2]]
[[ 1.00000000e+00 -4.44089210e-16 -1.66533454e-16]
[-1.77635684e-15 1.00000000e+00 -2.22044605e-16]
[-2.22044605e-15 -1.33226763e-1... | Apache-2.0 | Midterm_Exam.ipynb | itsmecelyssa/Linear-Algebra-58020 |
Race classification Sarah Santiago and Carlos Ortiz initially wrote this notebook. Jae Yeon Kim reviwed the notebook, edited the markdown, and commented on the code.Racial demographic dialect predictions were made by the model developed by [Blodgett, S. L., Green, L., & O'Connor, B. (2016)](https://arxiv.org/pdf/1608.... | # Import libraries
import pandas as pd
import numpy as np
import re
import seaborn as sns
import matplotlib.pyplot as plt
## Language-demography model
import predict | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Import Tweets |
# Import file
tweets = pd.read_csv("tweet.csv").drop(['Unnamed: 0'], axis=1)
# Index variable
tweets.index.name = 'ID'
# First five rows
tweets.head() | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Clean Tweets | url_re = r'http\S+'
at_re = r'@[\w]*'
rt_re = r'^[rt]{2}'
punct_re = r'[^\w\s]'
tweets_clean = tweets.copy()
tweets_clean['Tweet'] = tweets_clean['Tweet'].str.lower() # Lower Case
tweets_clean['Tweet'] = tweets_clean['Tweet'].str.replace(url_re, '') # Remove Links/URL
tweets_clean['Tweet'] = tweets_clean['Tweet'].str.... | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Apply Predictions | predict.load_model()
def prediction(string):
return predict.predict(string.split())
predictions = tweets_clean['Tweet'].apply(prediction)
tweets_clean['Predictions'] = predictions
# Fill tweets that have no predictions with None
tweets_clean = tweets_clean.fillna("NA")
tweets_clean.head()
def first_last(item):... | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Tweets with Predictions Based on Racial Demographics (AAE, WAE) | final_tweets = tweets_clean.drop(columns=["Predictions", "Predictions_AAE_W"])
final_tweets['Tweet'] = tweets['Tweet']
final_tweets.head() | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Export Tweets to CSV | final_tweets.to_csv('r_d_tweets_3.csv') | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Analysis | sns.countplot(x=final_tweets['Racial Demographic (Two)'])
plt.title("Racial Demographic (Two)")
sns.countplot(x=final_tweets['Racial Demographic (All)'])
plt.title("Racial Demographic (All)")
aae = final_tweets[final_tweets['Racial Demographic (All)'] == 0]
aae.head()
counts = aae.groupby("Type").count()
counts = count... | _____no_output_____ | MIT | code/.ipynb_checkpoints/Racial Demographic Predictions on Tweets, Santiago and Ortiz-checkpoint.ipynb | rjvkothari/race-classification |
Semen want to rent a flat. You're given 3 equivalent params: distance to subway (minutes), number of subway station to get to work, rent price (thousands rubles). Way from flat to subway should not exceed 20 minutes. Importing data | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_excel("../data/flat_rent_info.xlsx", 5, index_col="ID")
data | _____no_output_____ | MIT | AnimatedVisualizationAndFlatRent/notebooks/FlatOptionsAnalyzing.ipynb | SmirnovAlexander/InformationAnalysis |
Analyzing data Normalizing data. | normalized_data = (data - data.min())/(data.max() - data.min())
normalized_data | _____no_output_____ | MIT | AnimatedVisualizationAndFlatRent/notebooks/FlatOptionsAnalyzing.ipynb | SmirnovAlexander/InformationAnalysis |
As it told that params are equivalent, we should find top 3 minimum sums of params. | normalized_data.plot(stacked=True, kind='bar', colormap = 'Set2', figsize=(10, 8), fontsize=12)
plt.xticks(rotation = 0)
plt.show() | _____no_output_____ | MIT | AnimatedVisualizationAndFlatRent/notebooks/FlatOptionsAnalyzing.ipynb | SmirnovAlexander/InformationAnalysis |
Data analysis and visualization of knowledge graph for star war movies👉👉[**You can have a look at this Project first**](http://starwar-visualization.s3-website-us-west-1.amazonaws.com) 👈👈This project collected data from online database [**SWAPI**](https://swapi.co), which is the world's first quantified and progra... | import warnings
warnings.simplefilter('ignore')
import urllib
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
%matplotlib inline
matplotlib.style.use('ggplot')
films = []
for x in range(1,8):
films.append('httP://swapi.co/api/films/' + str(x) + '/')
headers ... | https://swapi.co/api/people/1/
https://swapi.co/api/people/2/
https://swapi.co/api/people/3/
https://swapi.co/api/people/4/
https://swapi.co/api/people/5/
https://swapi.co/api/people/6/
https://swapi.co/api/people/7/
https://swapi.co/api/people/8/
https://swapi.co/api/people/9/
https://swapi.co/api/people/10/
https://s... | MIT-0 | Notebooks/star_war.ipynb | vertigo-yl/Projects |
2. Basic analysis | fr = open('../csv/films.txt','r')
fw = open('../csv/stat_basic.csv','w')
fw.write('title,key,value\n')
for line in fr:
tmp = json.loads(line.strip('\n'))
fw.write(tmp['title'] + ',' + 'characters,' + str(len(tmp['characters'])) + '\n')
fw.write(tmp['title'] + ',' + 'planets,' + str(len(tmp['planets'])) + '... | _____no_output_____ | MIT-0 | Notebooks/star_war.ipynb | vertigo-yl/Projects |
"Attack of the Clones" has most characters | fr = open('../csv/characters.txt','r')
fw = open('../csv/stat_characters.csv','w')
fw.write('name,height,mass,gender,homeworld\n')
for line in fr:
tmp = json.loads(line.strip('\n'))
if tmp['height'] == 'unknown':
tmp['height'] = '-1'
if tmp['mass'] == 'unknown':
tmp['mass'] = '-1'
if tmp... | _____no_output_____ | MIT-0 | Notebooks/star_war.ipynb | vertigo-yl/Projects |
_____no_output_____ | MIT | tfkt_vis.ipynb | kghite/tfkt | ||
Inspired by: http://blog.varunajayasiri.com/numpy_lstm.html Imports | import numpy as np
from numpy import ndarray
from typing import Dict, List, Tuple
import matplotlib.pyplot as plt
from IPython import display
plt.style.use('seaborn-white')
%matplotlib inline
from copy import deepcopy
from collections import deque
from lincoln.utils.np_utils import assert_same_shape
from scipy.special... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
Activations | def sigmoid(x: ndarray):
return 1 / (1 + np.exp(-x))
def dsigmoid(x: ndarray):
return sigmoid(x) * (1 - sigmoid(x))
def tanh(x: ndarray):
return np.tanh(x)
def dtanh(x: ndarray):
return 1 - np.tanh(x) * np.tanh(x)
def softmax(x, axis=None):
return np.exp(x - logsumexp(x, axis=axis, keepdims=... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`RNNOptimizer` | class RNNOptimizer(object):
def __init__(self,
lr: float = 0.01,
gradient_clipping: bool = True) -> None:
self.lr = lr
self.gradient_clipping = gradient_clipping
self.first = True
def step(self) -> None:
for layer in self.model.layers:
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`SGD` and `AdaGrad` | class SGD(RNNOptimizer):
def __init__(self,
lr: float = 0.01,
gradient_clipping: bool = True) -> None:
super().__init__(lr, gradient_clipping)
def _update_rule(self, **kwargs) -> None:
update = self.lr*kwargs['grad']
kwargs['param'] -= update
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`Loss`es | class Loss(object):
def __init__(self):
pass
def forward(self,
prediction: ndarray,
target: ndarray) -> float:
assert_same_shape(prediction, target)
self.prediction = prediction
self.target = target
self.output = self._output()
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
RNNs `RNNNode` | class RNNNode(object):
def __init__(self):
pass
def forward(self,
x_in: ndarray,
H_in: ndarray,
params_dict: Dict[str, Dict[str, ndarray]]
) -> Tuple[ndarray]:
'''
param x: numpy array of shape (batch_size, vocab_size)
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`RNNLayer` | class RNNLayer(object):
def __init__(self,
hidden_size: int,
output_size: int,
weight_scale: float = None):
'''
param sequence_length: int - length of sequence being passed through the network
param vocab_size: int - the number of character... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`RNNModel` | class RNNModel(object):
'''
The Model class that takes in inputs and targets and actually trains the network and calculates the loss.
'''
def __init__(self,
layers: List[RNNLayer],
sequence_length: int,
vocab_size: int,
loss: Loss):
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`RNNTrainer` | class RNNTrainer:
'''
Takes in a text file and a model, and starts generating characters.
'''
def __init__(self,
text_file: str,
model: RNNModel,
optim: RNNOptimizer,
batch_size: int = 32):
self.data = open(text_file, 'r').rea... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
With RNN cells, this gets stuck in a local max. Let's try `LSTM`s. LSTMs `LSTMNode` | class LSTMNode:
def __init__(self):
'''
param hidden_size: int - the number of "hidden neurons" in the LSTM_Layer of which this node is a part.
param vocab_size: int - the number of characters in the vocabulary of which we are predicting the next
character.
'''
pass
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`LSTMLayer` | class LSTMLayer:
def __init__(self,
hidden_size: int,
output_size: int,
weight_scale: float = 0.01):
'''
param sequence_length: int - length of sequence being passed through the network
param vocab_size: int - the number of characters in th... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`LSTMModel` | class LSTMModel(object):
'''
The Model class that takes in inputs and targets and actually trains the network and calculates the loss.
'''
def __init__(self,
layers: List[LSTMLayer],
sequence_length: int,
vocab_size: int,
hidden_size... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
GRUs `GRUNode` | class GRUNode(object):
def __init__(self):
'''
param hidden_size: int - the number of "hidden neurons" in the LSTM_Layer of which this node is a part.
param vocab_size: int - the number of characters in the vocabulary of which we are predicting the next
character.
'''
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
`GRULayer` | class GRULayer(object):
def __init__(self,
hidden_size: int,
output_size: int,
weight_scale: float = 0.01):
'''
param sequence_length: int - length of sequence being passed through the network
param vocab_size: int - the number of character... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
Experiments Single LSTM layer | layers1 = [LSTMLayer(hidden_size=256, output_size=62, weight_scale=0.01)]
mod = RNNModel(layers=layers1,
vocab_size=62, sequence_length=25,
loss=SoftmaxCrossEntropy())
optim = AdaGrad(lr=0.01, gradient_clipping=True)
trainer = RNNTrainer('input.txt', mod, optim, batch_size=3)
trainer.train... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
Three variants of multiple layers: | layers2 = [RNNLayer(hidden_size=256, output_size=128, weight_scale=0.1),
LSTMLayer(hidden_size=256, output_size=62, weight_scale=0.01)]
mod = RNNModel(layers=layers2,
vocab_size=62, sequence_length=25,
loss=SoftmaxCrossEntropy())
optim = AdaGrad(lr=0.01, gradient_clipping=True)
... | _____no_output_____ | MIT | 06_rnns/RNN_DLFS.ipynb | tianminzheng/DLFS_code |
Live demo: Processing gravity data with Fatiando a Terra Import packages | import pygmt
import pyproj
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import pooch
import verde as vd
import boule as bl
import harmonica as hm | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Load Bushveld Igneous Complex gravity data (South Africa) and a DEM | url = "https://github.com/fatiando/2021-gsh/main/raw/notebook/data/bushveld_gravity.csv"
md5_hash = "md5:45539f7945794911c6b5a2eb43391051"
data = pd.read_csv(fname)
data
# Obtain the region to plot using Verde ([W, E, S, N])
region_deg = vd.get_region((data.longitude, data.latitude))
fig = pygmt.Figure()
fig.basemap(p... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Let's download a DEM for the same area: | url = "https://github.com/fatiando/transform21/raw/main/data/bushveld_topography.nc"
md5_hash = "md5:62daf6a114dda89530e88942aa3b8c41"
fname = pooch.retrieve(url, known_hash=md5_hash, fname="bushveld_topography.nc")
fname | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
And use Xarray to load the netCDF file: | topography = xr.load_dataarray(fname)
topography
# Plot topography using pygmt
topo_region = vd.get_region((topography.longitude.values, topography.latitude.values))
fig = pygmt.Figure()
topo_region = vd.get_region((topography.longitude.values, topography.latitude.values))
fig.basemap(projection="M15c", region=topo_re... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Compute gravity disturbance | data["disturbance"] = data.gravity - normal_gravity
data
fig = pygmt.Figure()
fig.basemap(projection="M15c", region=region_deg, frame=True)
maxabs = vd.maxabs(data.disturbance)
pygmt.makecpt(cmap="polar", series=[-maxabs, maxabs])
fig.plot(
x=data.longitude,
y=data.latitude,
color=data.disturbance,
cma... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Remove terrain correction Project the data to plain coordinates | projection = pyproj.Proj(proj="merc", lat_ts=data.latitude.mean())
data["easting"] = easting
data["northing"] = northing
data | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Project the topography to plain coordinates Compute gravitational effect of the layer of prisms Create a model of the terrain with prisms Calculate the gravitational effect of the terrain Calculate the Bouguer disturbance | data["bouguer"] = data.disturbance - terrain_effect
data
fig = pygmt.Figure()
fig.basemap(projection="M15c", region=region_deg, frame=True)
maxabs = vd.maxabs(data.bouguer)
pygmt.makecpt(cmap="polar", series=[-maxabs, maxabs])
fig.plot(
x=data.longitude,
y=data.latitude,
color=data.bouguer,
cmap=True,
... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Calculate residualsWe can use [Verde](https://www.fatiando.org/verde) to remove a second degree trend from the Bouguer disturbance | data["residuals"] = residuals
data
fig = pygmt.Figure()
fig.basemap(projection="M15c", region=region_deg, frame=True)
maxabs = np.quantile(np.abs(data.residuals), 0.99)
pygmt.makecpt(cmap="polar", series=[-maxabs, maxabs])
fig.plot(
x=data.longitude,
y=data.latitude,
color=data.residuals,
cmap=True,
... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Grid the residuals with Equivalent SourcesWe can use [Harmonica](https://www.fatiando.org/harmonica) to grid the residuals though the equivalent sources technique | fig = pygmt.Figure()
fig.basemap(projection="M15c", region=region_deg, frame=True)
scale = np.quantile(np.abs(grid.residuals), 0.995)
pygmt.makecpt(cmap="polar", series=[-scale, scale], no_bg=True)
fig.grdimage(
grid.residuals,
shading="+a45+nt0.15",
cmap=True,
)
fig.colorbar(frame='af+l"Residuals [mGal]"'... | _____no_output_____ | CC-BY-4.0 | live.ipynb | fatiando/2021-gsh |
Title Graph Element Dependencies Matplotlib Backends Matplotlib Bokeh | import numpy as np
import pandas as pd
import holoviews as hv
from bokeh.sampledata.les_mis import data
hv.extension('matplotlib')
%output size=200 fig='svg' | _____no_output_____ | BSD-3-Clause | examples/reference/elements/matplotlib/Chord.ipynb | scaine1/holoviews |
The ``Chord`` element allows representing the inter-relationships between data points in a graph. The nodes are arranged radially around a circle with the relationships between the data points drawn as arcs (or chords) connecting the nodes. The number of chords is scaled by a weight declared as a value dimension on the... | links = pd.DataFrame(data['links'])
print(links.head(3)) | _____no_output_____ | BSD-3-Clause | examples/reference/elements/matplotlib/Chord.ipynb | scaine1/holoviews |
In the simplest case we can construct the ``Chord`` by passing it just the edges: | hv.Chord(links) | _____no_output_____ | BSD-3-Clause | examples/reference/elements/matplotlib/Chord.ipynb | scaine1/holoviews |
To add node labels and other information we can construct a ``Dataset`` with a key dimension of node indices. | nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
nodes.data.head() | _____no_output_____ | BSD-3-Clause | examples/reference/elements/matplotlib/Chord.ipynb | scaine1/holoviews |
Additionally we can now color the nodes and edges by their index and add some labels. The ``label_index``, ``color_index`` and ``edge_color_index`` allow specifying columns to color by. | %%opts Chord [label_index='name' color_index='index' edge_color_index='source']
%%opts Chord (cmap='Category20' edge_cmap='Category20')
hv.Chord((links, nodes)).select(value=(5, None)) | _____no_output_____ | BSD-3-Clause | examples/reference/elements/matplotlib/Chord.ipynb | scaine1/holoviews |
Gram-Schmidt and Modified Gram-Schmidt | import numpy as np
import numpy.linalg as la
A = np.random.randn(3, 3)
def test_orthogonality(Q):
print("Q:")
print(Q)
print("Q^T Q:")
QtQ = np.dot(Q.T, Q)
QtQ[np.abs(QtQ) < 1e-15] = 0
print(QtQ)
Q = np.zeros(A.shape) | _____no_output_____ | Unlicense | cleared-demos/linear_least_squares/Gram-Schmidt and Modified Gram-Schmidt.ipynb | xywei/numerics-notes |
Now let us generalize the process we used for three vectors earlier: This procedure is called [Gram-Schmidt Orthonormalization](https://en.wikipedia.org/wiki/Gram–Schmidt_process). | test_orthogonality(Q) | _____no_output_____ | Unlicense | cleared-demos/linear_least_squares/Gram-Schmidt and Modified Gram-Schmidt.ipynb | xywei/numerics-notes |
Now let us try a different example ([Source](http://fgiesen.wordpress.com/2013/06/02/modified-gram-schmidt-orthogonalization/)): |
np.set_printoptions(precision=13)
eps = 1e-8
A = np.array([
[1, 1, 1],
[eps,eps,0],
[eps,0, eps]
])
A
Q = np.zeros(A.shape)
for k in range(A.shape[1]):
avec = A[:, k]
q = avec
for j in range(k):
print(q)
q = q - np.dot(avec, Q[:,j])*Q[:,j]
print(q)
q = q/l... | _____no_output_____ | Unlicense | cleared-demos/linear_least_squares/Gram-Schmidt and Modified Gram-Schmidt.ipynb | xywei/numerics-notes |
Questions:* What happened?* How do we fix it? | Q = np.zeros(A.shape)
test_orthogonality(Q) | _____no_output_____ | Unlicense | cleared-demos/linear_least_squares/Gram-Schmidt and Modified Gram-Schmidt.ipynb | xywei/numerics-notes |
導入葡萄酒數據集(只考慮前兩個特徵) | from sklearn.datasets import load_wine
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
wine = load_wine()
#選取前兩個特徵
X = wine.data[:, :2]
y = wine.target
print('Class labels:', np.unique(y))
sc = StandardScaler()
sc.fit(X)
X_std = sc.transform(X)
... | _____no_output_____ | MIT | svm wine.data - using sklearn.ipynb | yunglinchang/machinelearning_coursework |
訓練「線性核函數」模型 | from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.svm import SVC
svmlin = SVC(kernel='linear', C=1.0, random_state=1)
svmlin.fit(X_train, y_train)
y_train_pred = svmlin.predict(X_train)
y_test_pred = svmlin.predict(X_t... | _____no_output_____ | MIT | svm wine.data - using sklearn.ipynb | yunglinchang/machinelearning_coursework |
訓練「⾼斯核函數」模型 | svmrbf = SVC(kernel='rbf', gamma=0.7, C=1.0)
svmrbf.fit(X_train, y_train)
y_train_pred = svmrbf.predict(X_train)
y_test_pred = svmrbf.predict(X_test)
svmrbf_train = accuracy_score(y_train, y_train_pred)
svmrbf_test = accuracy_score(y_test, y_test_pred)
print('SVM with RBF kernal train/test accuracies %.3f/%.3f'
... | _____no_output_____ | MIT | svm wine.data - using sklearn.ipynb | yunglinchang/machinelearning_coursework |
⾼斯核函數參數的影響 | C=1.0
models = (SVC(kernel='rbf', gamma=0.1, C=C),
SVC(kernel='rbf', gamma=1, C=C),
SVC(kernel='rbf', gamma=10, C=C))
models = (clf.fit(X_train, y_train) for clf in models)
svmrbf_train = accuracy_score(y_train, y_train_pred)
svmrbf_test = accuracy_score(y_test, y_test_pred)
titles = ('g... | SVM with RBF kernal train/test accuracies 0.887/0.833
| MIT | svm wine.data - using sklearn.ipynb | yunglinchang/machinelearning_coursework |
Feature Selection* tf-idf* chi-square* likelihood* PMI* EMI=> build dictionary in 500 words LLR | dict_df = pd.read_csv('data/dictionary.txt',header=None,index_col=None,sep=' ')
terms = dict_df[1].tolist() #all terms
with open('data/training.txt','r') as f:
train_id = f.read().splitlines()
train_dict = {}
for trainid in train_id:
trainid = trainid.split(' ')
trainid = list(filter(None, trainid))
tra... | _____no_output_____ | MIT | NB_clf/Multinomial-NB_clf.ipynb | tychen5/IR_TextMining |
select top 500* 取各col的mean+1.45*std* 再去做投票,超過兩票的流下來看剩下哪幾個 | dict_df3 = pd.read_csv('output/feature_selection_df_rev.csv',index_col=None)
threshold_tfidf = np.mean(dict_df3['avg_tfidf'])+2.5*np.std(dict_df3['avg_tfidf']) #1.45=>502 數字大嚴格
threshold_chi = np.mean(dict_df3['score_chi'])+2.5*np.std(dict_df3['score_chi']) #1=>350
threshold_llr = np.mean(dict_df3['score_llr'])+2.5*np.... | _____no_output_____ | MIT | NB_clf/Multinomial-NB_clf.ipynb | tychen5/IR_TextMining |
Classifier* 7-fold* MNB* BNB* self-train / co-train* ens voting (BNB lower weight)* auto-skleran / auto-kerasREF: http://kenzotakahashi.github.io/naive-bayes-from-scratch-in-python.html | df_vote = pd.read_csv('output/500terms_df_rev5.csv',index_col=False)
terms_li = list(set(df_vote.term.tolist()))
train_X = []
train_Y = []
len(terms_li)
with open('data/training.txt','r') as f:
train_id = f.read().splitlines()
train_dict = {}
for trainid in train_id:
trainid = trainid.split(' ')
trainid =... | [array([-9.07658038, -9.07658038, -9.70406053, -8.90668135]), array([-9.48204549, -9.48204549, -9.70406053, -8.78889831]), array([-6.8793558 , -6.8793558 , -6.93147181, -5.89852655]), array([-5.08759634, -5.78074352, -6.23832463, -6.59167373]), array([-5.78074352, -5.08759634, -6.23832463, -6.59167373]), array([-4.6821... | MIT | NB_clf/Multinomial-NB_clf.ipynb | tychen5/IR_TextMining |
Prediction | df_vote = pd.read_csv('output/500terms_df_rev5.csv',index_col=False)
terms_li = list(set(df_vote.term.tolist()))
len(terms_li)
with open('data/training.txt','r') as f:
train_id = f.read().splitlines()
train_dict = {}
test_id = []
train_ids=[]
for trainid in train_id:
trainid = trainid.split(' ')
trainid = l... | 100%|██████████| 900/900 [00:20<00:00, 43.87it/s]
| MIT | NB_clf/Multinomial-NB_clf.ipynb | tychen5/IR_TextMining |
combine all prediction df | import os
in_dir = './output/'
prefixed = [filename for filename in os.listdir('./output/') if filename.endswith("_sk.csv")]
df_from_each_file = [pd.read_csv(in_dir+f) for f in prefixed]
prefixed
merged_df = functools.reduce(lambda left,right: pd.merge(left,right,on='id'), df_from_each_file)
merged_df.columns = ['id',0... | _____no_output_____ | MIT | NB_clf/Multinomial-NB_clf.ipynb | tychen5/IR_TextMining |
Stock Statistics Statistics is a branch of applied mathematics concerned with collecting, organizing, and interpreting data. Statistics is also the mathematical study of the likelihood and probability of events occurring based on known quantitative data or a collection of data.http://www.icoachmath.com/math_dictionary... | import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
# yfinance is used to fetch data
import yfinance as yf
yf.pdr_override()
# input
symbol = 'AAPL'
start = '2014-01-01'
end = '2019-01-01'
# Read data
df = yf.download(... | _____no_output_____ | MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Mean is the average number, sum of the values divided by the number of values. Median is the middle value in the list of numbers. Mode is the value that occurs often. | import statistics as st
print('Mean of returns:', st.mean(returns))
print('Median of returns:', st.median(returns))
print('Median Low of returns:', st.median_low(returns))
print('Median High of returns:', st.median_high(returns))
print('Median Grouped of returns:', st.median_grouped(returns))
print('Mode of returns:',... | Mode of returns: 0.0
Mode of bins: [(-0.0070681808335254365, 0.0010272794824504605)]
| MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Arithmetic Average Returns is average return on the the stock or investment | print('Arithmetic average of returns:\n')
print(returns.mean()) | Arithmetic average of returns:
0.0007357373017012073
| MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Geometric mean is the average of a set of products, the calculation of which is commonly used to determine the performance results of an investment or portfolio. It is technically defined as "the nth root product of n numbers." The geometric mean must be used when working with percentages, which are derived from value... | # Geometric mean
from scipy.stats.mstats import gmean
print('Geometric mean of stock:', gmean(returns))
ratios = returns + np.ones(len(returns))
R_G = gmean(ratios) - 1
print('Geometric mean of returns:', R_G) | Geometric mean of returns: 0.000622187293129
| MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Standard deviation of returns is the risk of returns | print('Standard deviation of returns')
print(returns.std())
T = len(returns)
init_price = df['Adj Close'][0]
final_price = df['Adj Close'][T]
print('Initial price:', init_price)
print('Final price:', final_price)
print('Final price as computed with R_G:', init_price*(1 + R_G)**T) | Initial price: 71.591667
Final price: 156.463837
Final price as computed with R_G: 156.463837
| MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Harmonic Mean is numerical average. Formula: A set of n numbers, add the reciprocals of the numbers in the set, divide the sum by n, then take the reciprocal of the result. | # Harmonic mean
print('Harmonic mean of returns:', len(returns)/np.sum(1.0/returns))
print('Skew:', stats.skew(returns))
print('Mean:', np.mean(returns))
print('Median:', np.median(returns))
plt.hist(returns, 30);
# Plot some example distributions stock's returns
xs = np.linspace(-6,6, 1257)
normal = stats.norm.pdf(... | The returns are likely not normal.
| MIT | Python_Stock/Stock_Statistics.ipynb | eu90h/Stock_Analysis_For_Quant |
Zero-Shot Image ClassificationThis example shows how [SentenceTransformers](https://www.sbert.net) can be used to map images and texts to the same vector space. We can use this to perform **zero-shot image classification** by providing the names for the labels.As model, we use the [OpenAI CLIP Model](https://github.co... | from sentence_transformers import SentenceTransformer, util
from PIL import Image
import glob
import torch
import pickle
import zipfile
from IPython.display import display
from IPython.display import Image as IPImage
import os
from tqdm.autonotebook import tqdm
import torch
# We use the original CLIP model for computi... | _____no_output_____ | Apache-2.0 | examples/applications/image-search/Image_Classification.ipynb | danielperezr88/sentence-transformers |
Zero-Shot Image ClassificationThe original CLIP Model only works for English, hence, we used [Multilingual Knowlegde Distillation](https://arxiv.org/abs/2004.09813) to make this model work with 50+ languages.For this, we msut load the *clip-ViT-B-32-multilingual-v1* model to encode our labels.We can define our labels ... | multi_model = SentenceTransformer('clip-ViT-B-32-multilingual-v1')
# Then, we define our labels as text. Here, we use 4 labels
labels = ['Hund', # German: dog
'gato', # Spanish: cat
'巴黎晚上', # Chinese: Paris at night
'Париж' # Russian: Paris
]
# And compute the text... | _____no_output_____ | Apache-2.0 | examples/applications/image-search/Image_Classification.ipynb | danielperezr88/sentence-transformers |
Coding AssignmentQ: Write a python class with different function to fit LDA model, evaluate optimal number of topics based on best coherence scores and predict new instances based on best LDA model with optimal number of topics based on best coherence score. Function should take 2darray of embeddings as input and retu... | """
author: Parikshit Saikia
email: pariksihtsaikia1619@gmail.com
github: https://github.com/parikshitsaikia1619
date: 20-08-2021
""" | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 1: Import neccessary Libraries | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
import spacy
from tqdm.notebook import tqdm
#spacy download en_core_web_sm
import nltk
nltk.download('stopwords')
fr... | [nltk_data] Downloading package stopwords to C:\Users\Parikshit
[nltk_data] Saikia\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!
| MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 2: Load the datasetThis dataset contains a set of research articles related to computer science, mathematics, physics and statistics. Each article is tagged into major and minor topics in the form one hot encoding.But for our task (topic modeling) we don't need the tags, we just need the articles text.From the da... | data = pd.read_csv('./data/research_articles/Train.csv/Processed_train.csv')
data.head()
articles_data = data.ABSTRACT.values.tolist() | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 3: Creating a Data Preprocessing PipelineThis is the most important step in this entire code . We cannot expect good results from a model trained on a uncleaned data.As the famous quote goes "garbage in,garbage out"We want our corpus consisting a list of representative words capturing the essence of each article,... | def convert_lowercase(string_list):
"""
Convert the list of strings to lowercase and returns the list
"""
pbar = tqdm(total = len(string_list),desc='lowercase conversion progress')
for i in range(len(string_list)):
string_list[i] = string_list[i].lower()
pbar.update(1)
pbar.close... | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 4: Finalizing the input dataIn this step we will form our the inputs of model, which are:* **Corpus**: A 2D embedded array of tuples, where each tuple is in the form of (token id, frequency of token in that document).* **dictionary**: A dictionary storing the mapping from token to id. | new_corpus,id_word = corpus_embeddings(processed_data)
new_corpus
id_word[0]
word_freq = [[(id_word[id], freq) for id, freq in cp] for cp in new_corpus[:1]]
word_freq # A more human reable form of our corpus | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Step 5: Modeling and EvaluationIn this part we will fit our data to our the LDA model , some hyper parameter tuning , evaluate the results and select the optimal setting for our model. | class LDA_model:
"""
A LDA Class consist functions to fit the model, calculating coherence values
and finding the optimal no. of topic
input:
corpus : a 2D array of embedded tokens
dictionary: A dictionary with id to token mapping
"""
def __init__(self, corpus,dictionary):
... | _____no_output_____ | MIT | LDA_New.ipynb | parikshitsaikia1619/LDA_modeing_IQVIA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.