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
Getting the cost pr. worker pr. support center
appendix_2["Cost_per_FTE"]=np.round(appendix_2["Total cost"]/appendix_2["Average FTE"]) appendix_2
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
Because of trouble with merge, the values are tranferred manually to the new DataFrame
def regional_center(var): """ Quick function that gives the location of support center""" if var in ['Europe']: return 'Ukraine' if var in ['Americas']: return 'USA' if var in ['Asia']: return 'China' New_regions["Support Center"]=New_regions["Region"].apply(regional_center) New_...
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
Altering the order of the columns to a more intiutive layout
print(list(New_regions.columns.values)) # New_regions=New_regions[['Support Center','Region', 'Licenses','Revenue','Employ_needed','Cost per FTE','Total cost']] New_regions
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
Calculation cost and balance values
New_regions['Total cost']=New_regions['Employ_needed']*New_regions['Cost per FTE'] New_regions New_regions=New_regions.assign(Balance=New_regions['Revenue'] - New_regions['Total cost']) New_regions
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
Making a new DataFrame for the whole project
Whole_project=pd.DataFrame() Whole_project['Licenses']=[New_regions['Licenses'].sum(axis=0)] Whole_project['Revenue']=[New_regions['Revenue'].sum(axis=0)] Whole_project['Employ_needed']=[New_regions['Employ_needed'].sum(axis=0)] Whole_project['Total cost']=[New_regions['Total cost'].sum(axis=0)] Whole_project['Balance'...
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
Looking at the 3-year forecast with different adoption ratesFirst off is 10% adoption rate, then 50%, and finally 100%
def adoption(df_out_name,df_in_name,adoption_rate): """ A function that takes an adoption rate as input, and calculates usefull parameters (licenses, revenue, employees needed, cost and balance) after 3 years. An annual growth rate of 10% is given """ df_in_name[f'{adoption_rate} adoption, l...
_____no_output_____
MIT
teaching_material/session_6/gruppe_8/3shape_final.ipynb
tlh957/DO2021
ADN Implemente un programa que identifique a una persona en función de su ADN, según se indica a continuación. $ python dna.py databases/large.csv sequences/5.txtLavender Empezando - Dentro de la carpeta data/adn se encuentra la información necesaria para resolver este ejercicio la cual incluye un archivo de base de ...
# Importando librerias import csv import re #Declarando funciones def conteomaxstr(patron, texto): maxrep = 0 count = 0 fin = 0 while True: encontrado = re.search(patron, texto) if encontrado: inicio = encontrado.start() end = encontrado.end() if...
Introduce el nombre del archivo CSV que contiene los recuentos de STR para la lista de individuos: small.csv Introduce el nombre del archivo de texto que contiene la secuencia ADN a indentificar: 1.txt
Apache-2.0
Modulo4/Ejercicios/Problema1.ipynb
francisrichard/CursoPythonD
drop the dependent columns to train and test X
X=df12.drop(['price'],axis='columns') X.head() y=df12.price y.head() from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=10) from sklearn.linear_model import LinearRegression lr_reg=LinearRegression() lr_reg.fit(X_train,y_train) lr_reg.score...
_____no_output_____
MIT
Machine learning Project.ipynb
NEHASHARMA1234/ML_Project
Use K Fold cross validation to measure accuracy of our LinearRegression model
from sklearn.model_selection import ShuffleSplit from sklearn.model_selection import cross_val_score cv=ShuffleSplit(n_splits=5, test_size=0.2, random_state=0) cross_val_score(LinearRegression(),X,y,cv=cv)
_____no_output_____
MIT
Machine learning Project.ipynb
NEHASHARMA1234/ML_Project
Find best model using GridSearchCV
from sklearn.model_selection import GridSearchCV from sklearn.linear_model import Lasso from sklearn.tree import DecisionTreeRegressor def find_best_model_using_gridsearchcv(X,y): algos = { 'linear_regression' : { 'model': LinearRegression(), 'params': { 'normalize'...
_____no_output_____
MIT
Machine learning Project.ipynb
NEHASHARMA1234/ML_Project
Export the tested model to a pickle file
import pickle with open('banglore_home_prices_model.pickle','wb') as f: pickle.dump(lr_reg,f)
_____no_output_____
MIT
Machine learning Project.ipynb
NEHASHARMA1234/ML_Project
Export location and column information to a file that will be useful later on in our prediction application
import json columns={ 'data_columns':[col.lower() for col in X.columns] } with open("columns.json","w") as f: f.write(json.dumps(columns))
_____no_output_____
MIT
Machine learning Project.ipynb
NEHASHARMA1234/ML_Project
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
How to train Boosted Trees models in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub This tutorial is an end-to-end walkthrough of training a Gradient Boosting model using decision trees with the `tf.estimator` API. Boosted Trees models are among the most popular and e...
from __future__ import absolute_import, division, print_function, unicode_literals from matplotlib import pyplot as plt import numpy as np import pandas as pd import tensorflow as tf tf.enable_eager_execution() tf.logging.set_verbosity(tf.logging.ERROR) tf.set_random_seed(123) # Load dataset. dftrain = pd.read_csv...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
The dataset consists of a training set and an evaluation set:* `dftrain` and `y_train` are the *training set*—the data the model uses to learn.* The model is tested against the *eval set*, `dfeval`, and `y_eval`.For training you will use the following features: Feature Name Description sex Gender of p...
dftrain.head() dftrain.describe()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
There are 627 and 264 examples in the training and evaluation sets, respectively.
dftrain.shape[0], dfeval.shape[0]
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
The majority of passengers are in their 20's and 30's.
dftrain.age.hist(bins=20) plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
There are approximately twice as male passengers as female passengers aboard.
dftrain.sex.value_counts().plot(kind='barh') plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
The majority of passengers were in the "third" class.
(dftrain['class'] .value_counts() .plot(kind='barh')) plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Most passengers embarked from Southampton.
(dftrain['embark_town'] .value_counts() .plot(kind='barh')) plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Females have a much higher chance of surviving vs. males. This will clearly be a predictive feature for the model.
ax = (pd.concat([dftrain, y_train], axis=1)\ .groupby('sex') .survived .mean() .plot(kind='barh')) ax.set_xlabel('% survive') plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Create feature columns and input functionsThe Gradient Boosting estimator can utilize both numeric and categorical features. Feature columns work with all TensorFlow estimators and their purpose is to define the features used for modeling. Additionally they provide some feature engineering capabilities like one-hot-en...
fc = tf.feature_column CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck', 'embark_town', 'alone'] NUMERIC_COLUMNS = ['age', 'fare'] def one_hot_cat_column(feature_name, vocab): return fc.indicator_column( fc.categorical_column_with_vocabulary_list(feature_name,...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
You can view the transformation that a feature column produces. For example, here is the output when using the `indicator_column` on a single example:
example = dftrain.head(1) class_fc = one_hot_cat_column('class', ('First', 'Second', 'Third')) print('Feature value: "{}"'.format(example['class'].iloc[0])) print('One-hot encoded: ', fc.input_layer(dict(example), [class_fc]).numpy())
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Additionally, you can view all of the feature column transformations together:
fc.input_layer(dict(example), feature_columns).numpy()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Next you need to create the input functions. These will specify how data will be read into our model for both training and inference. You will use the `from_tensor_slices` method in the [`tf.data`](https://www.tensorflow.org/api_docs/python/tf/data) API to read in data directly from Pandas. This is suitable for smaller...
# Use entire batch since this is such a small dataset. NUM_EXAMPLES = len(y_train) def make_input_fn(X, y, n_epochs=None, shuffle=True): y = np.expand_dims(y, axis=1) def input_fn(): dataset = tf.data.Dataset.from_tensor_slices((dict(X), y)) if shuffle: dataset = dataset.shuffle(NUM_EXAMPLES) # F...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Train and evaluate the modelBelow you will do the following steps:1. Initialize the model, specifying the features and hyperparameters.2. Feed the training data to the model using the `train_input_fn` and train the model using the `train` function.3. You will assess model performance using the evaluation set—in this e...
linear_est = tf.estimator.LinearClassifier(feature_columns) # Train model. linear_est.train(train_input_fn, max_steps=100) # Evaluation. results = linear_est.evaluate(eval_input_fn) print('Accuracy : ', results['accuracy']) print('Dummy model: ', results['accuracy_baseline'])
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Next let's train a Boosted Trees model. For boosted trees, regression (`BoostedTreesRegressor`) and classification (`BoostedTreesClassifier`) are supported, along with using any twice differentiable custom loss (`BoostedTreesEstimator`). Since the goal is to predict a class - survive or not survive, you will use the `B...
# Since data fits into memory, use entire dataset per layer. It will be faster. # Above one batch is defined as the entire dataset. n_batches = 1 est = tf.estimator.BoostedTreesClassifier(feature_columns, n_batches_per_layer=n_batches) # The model will stop training once the s...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
For performance reasons, when your data fits in memory, it is recommended to use the `boosted_trees_classifier_train_in_memory` function. However if training time is not of a concern or if you have a very large dataset and want to do distributed training, use the `tf.estimator.BoostedTrees` API shown above.When using t...
def make_inmemory_train_input_fn(X, y): y = np.expand_dims(y, axis=1) def input_fn(): return dict(X), y return input_fn train_input_fn = make_inmemory_train_input_fn(dftrain, y_train) eval_input_fn = make_input_fn(dfeval, y_eval, shuffle=False, n_epochs=1) est = tf.contrib.estimator.boosted_trees_classifier...
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Now you can use the train model to make predictions on a passenger from the evaluation set. TensorFlow models are optimized to make predictions on a batch, or collection, of examples at once. Earlier, the `eval_input_fn` is defined using the entire evaluation set.
pred_dicts = list(est.predict(eval_input_fn)) probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts]) probs.plot(kind='hist', bins=20, title='predicted probabilities') plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Finally you can also look at the receiver operating characteristic (ROC) of the results, which will give us a better idea of the tradeoff between the true positive rate and false positive rate.
from sklearn.metrics import roc_curve fpr, tpr, _ = roc_curve(y_eval, probs) plt.plot(fpr, tpr) plt.title('ROC curve') plt.xlabel('false positive rate') plt.ylabel('true positive rate') plt.xlim(0,) plt.ylim(0,) plt.show()
_____no_output_____
Apache-2.0
site/en/tutorials/estimators/boosted_trees.ipynb
abviv/docs
Implementing the Gradient Descent AlgorithmIn this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data.
import matplotlib.pyplot as plt import numpy as np import pandas as pd # Some helper functions for plotting and drawing lines def plot_points(X, y): admitted = X[np.argwhere(y==1)] rejected = X[np.argwhere(y==0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color = 'blue',...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
tobias-fyi/deep-learning-v2-pytorch
Reading and plotting the data
data = pd.read_csv('data.csv', header=None) X = np.array(data[[0,1]]) y = np.array(data[2]) plot_points(X,y) plt.show()
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
tobias-fyi/deep-learning-v2-pytorch
TODO: Implementing the basic functionsHere is your turn to shine. Implement the following formulas, as explained in the text.- Sigmoid activation function$$\sigma(x) = \frac{1}{1+e^{-x}}$$- Output (prediction) formula$$\hat{y} = \sigma(w_1 x_1 + w_2 x_2 + b)$$- Error function$$Error(y, \hat{y}) = - y \log(\hat{y}) - (...
# Implement the following functions # Activation (sigmoid) function def sigmoid(x): return 1 / (1 + np.exp(-x)) # Output (prediction) formula def output_formula(features, weights, bias): return sigmoid(np.dot(features, weights) + bias) # Error (log-loss) formula def error_formula(y, output): return -(y *...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
tobias-fyi/deep-learning-v2-pytorch
Training functionThis function will help us iterate the gradient descent algorithm through all the data, for a number of epochs. It will also plot the data, and some of the boundary lines obtained as we run the algorithm.
np.random.seed(44) epochs = 100 learnrate = 0.01 def train(features, targets, epochs, learnrate, graph_lines=False): errors = [] n_records, n_features = features.shape last_loss = None weights = np.random.normal(scale=1 / n_features**.5, size=n_features) bias = 0 for e in range(epochs): ...
_____no_output_____
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
tobias-fyi/deep-learning-v2-pytorch
Time to train the algorithm!When we run the function, we'll obtain the following:- 10 updates with the current training loss and accuracy- A plot of the data and some of the boundary lines obtained. The final one is in black. Notice how the lines get closer and closer to the best fit, as we go through more epochs.- A ...
train(X, y, epochs, learnrate, True)
========== Epoch 0 ========== Train loss: 0.7135845195381634 Accuracy: 0.4 ========== Epoch 10 ========== Train loss: 0.6225835210454962 Accuracy: 0.59 ========== Epoch 20 ========== Train loss: 0.5548744083669508 Accuracy: 0.74 ========== Epoch 30 ========== Train loss: 0.501606141872473 Accuracy: 0.84 ==...
MIT
intro-neural-networks/gradient-descent/GradientDescent.ipynb
tobias-fyi/deep-learning-v2-pytorch
View source on GitHub Notebook Viewer Run in Google Colab ImageCollection OverviewAn `ImageCollection` is a stack or time series of images. In addition to loading an `ImageCollection` using an Earth Engine collection ID, Earth Engine has methods to create image collections. The constructor `ee.ImageCollect...
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import gee...
_____no_output_____
MIT
tutorials/ImageCollection/01_image_collection_overview.ipynb
Yisheng-Li/geemap
Create an interactive map The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.pyL13) can be added using the `Map.add_basemap()` function.
Map = emap.Map(center=[40,-100], zoom=4) Map.add_basemap('ROADMAP') # Add Google Map Map
_____no_output_____
MIT
tutorials/ImageCollection/01_image_collection_overview.ipynb
Yisheng-Li/geemap
Add Earth Engine Python script
# Create arbitrary constant images. constant1 = ee.Image(1) constant2 = ee.Image(2) # Create a collection by giving a list to the constructor. collectionFromConstructor = ee.ImageCollection([constant1, constant2]) print('collectionFromConstructor: ', collectionFromConstructor.getInfo()) # Create a collection with from...
_____no_output_____
MIT
tutorials/ImageCollection/01_image_collection_overview.ipynb
Yisheng-Li/geemap
Display Earth Engine data layers
Map.addLayerControl() Map
_____no_output_____
MIT
tutorials/ImageCollection/01_image_collection_overview.ipynb
Yisheng-Li/geemap
Regarding this NotebookThis is a replication of the original analysis performed in the paper by [Waade & Enevoldsen 2020](missing). This replication script will not be updated as it is intended for reproducibility. Any deviations from the paper is marked with bold for transparency.Footnotes and internal documentation ...
# assuming you are in the github folder change the path - not relevant if tomsup is installed via. pip import os os.chdir("..") # go out of the tutorials folder
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
Both approaches will also install the required dependencies. Now tomsup can be imported into Python following the lines;
import tomsup as ts
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
We will also set a arbitrary seed for to ensure reproducibility;
import random import numpy as np np.random.seed(1995) random.seed(1995) # The year of birth of the first author
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
First we need to set up the Matching Pennies game. As different games are defined by different payoff matrices, we set up the game by creating the appropriate payoff matrix using the ```PayoffMatrix``` class.
# initiate the competitive matching pennies game penny = ts.PayoffMatrix(name="penny_competitive") # print the payoff matrix print(penny)
<Class PayoffMatrix, Name = penny_competitive> The payoff matrix of agent 0 | Choice agent 1 | | 0 | 1 | | ------------ | Choice | 0 | -1 | 1 | agent 0| 1 | 1 | -1 | The payoff matrix of agent 1 | Choice agent 1 | | 0 | 1 | | ------------ | Choice | 0 | 1 |...
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
The Matching Pennies game is a zero sum game, meaning that for one agent to get a reward, the opponent has to lose. Agents have thus to predict their opponents' behavior, which is ideal for investigating \gls{tom}. Note that to explore other payoff matrices included in the package, or to learn how to specify a custom p...
# define the random bias agent, which chooses 1 70 percent of the time, and call the agent "jung" jung = ts.RB(bias=0.7) # Examine Agent print(f"jung is a class of type: {type(jung)}") if isinstance(jung, ts.Agent): print(f"but jung is also an instance of the parent class ts.Agent") # let us have Jung make a choi...
jung is a class of type: <class 'tomsup.agent.RB'> but jung is also an instance of the parent class ts.Agent jung chose 1 and his probability for choosing 1 was 0.7.
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
Note that it is possible to create one or more agents simultaneously using the convenient `create\_agents()` and passing any starting parameters to it in the form of a dictionary.
# create a reinforcement learning agent skinner = ts.create_agents(agents="QL", start_params={"save_history": True})
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
Now that both agents are created, we have them play against each other.
# have the agents compete for 30 rounds results = ts.compete(jung, skinner, p_matrix=penny, n_rounds=30) # examine results print(results.head()) # inspect the first 5 rows of the dataframe
round choice_agent0 choice_agent1 payoff_agent0 payoff_agent1 0 0 1 0 1 -1 1 1 1 1 -1 1 2 2 0 1 1 -1 3 3 1 1 ...
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
** Note: you can remove the print() to get a nicer printout of the dataframe **
results.head() # inspect the first 5 rows of the dataframe
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
The data frame stores the choice of each agent as well as their resulting payoff. Simply summing the payoff columns would determine the winner. k-ToMHere we will present some simple examples of the k-ToM agent. For a more in-depth description we recommend checking the expanded introduction on the [Github repository](ht...
# Creating a simple 1-ToM with default parameters tom_1 = ts.TOM(level=1, dilution=None, save_history=True) # Extract the parameters tom_1.print_parameters()
volatility (log scale): -2 b_temp (log odds): -1 bias: 0
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
Note that k-ToM agents as default uses agnostic starting beliefs. These can be shown in detail and specified as desired, as shown in **appendix in the paper**.To increase the agent's tendency to choose one we could simply increase its bias. Similarly, if we want the agent to behave in a more more deterministic fashion ...
tom_2 = ts.TOM( level=2, volatility=-2, b_temp=-2, # more deterministic bias=0, dilution=None, save_history=True, ) choice = tom_2.compete(p_matrix=penny, agent=0, op_choice=None) print("tom_2 chose:", choice)
tom_2 choose: 0
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
The user is recommended to have the 1-ToM and the 2-ToM agents compete using the previously presented `ts.compete()` function for simplicity. However, to make the process more transparent for the user in the following we create a simple for-loop:
tom_2.reset() # reset before start prev_choice_1tom = None prev_choice_2tom = None for trial in range(1, 4): # note that op_choice is choice on previous turn # and that agent is the agent you respond to in the payoff matrix choice_1 = tom_1.compete(p_matrix=penny, agent=0, op_choice=prev_choice_1tom) ...
Round 1 1-ToM choose 0 2-ToM choose 0 Round 2 1-ToM choose 1 2-ToM choose 1 Round 3 1-ToM choose 1 2-ToM choose 0
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
A for loop like this can be used to implement k-ToM in an experimental setting by replacing the agent with the behavior of a participant. Examples of such implementations (interfacing with PsychoPy are available in the [documentation](https://github.com/KennethEnevoldsen/tomsup/tree/master/tutorials/psychopy_experiment...
tom_2.print_internal( keys=["p_k", "p_op"], level=[0, 1] # print these two states ) # for the agent simulated opponents 0-ToM and 1-ToM
opponent_states | 0-ToM | | opponent_states | | own_states | 1-ToM | | opponent_states | | | 0-ToM | | | | opponent_states | | | | own_states | | own_states | | | p_k (probability): [1.0] own_states | p_k (probability): [0.4828785372717201, 0.5...
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
For instance, we can note that the estimate of the opponent's sophistication level (\texttt{p\_k}) slightly favors a 1-ToM as opposed to a 0-ToM and that the average probability of the opponent choosing one (`p_op`) slightly favors 1 (which was indeed the option the opponent chose). These estimates are quite uncertain ...
# Create a list of agents agents = ["RB", "QL", "WSLS", "1-TOM", "2-TOM"] # And set their starting parameters. An empty dictionary denotes default values start_params = [{"bias": 0.7}, {"learning_rate": 0.5}, {}, {}, {}] group = ts.create_agents(agents, start_params) # create a group of agents # Specify the environm...
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
Following the simulation, a data frame can be extracted as before, with additional columns reporting simulation number, competing agent pair (`agent0` and `agent1`) and if `save_history=True` it will also add two columns denoting the internal states of each agent, e.g. estimates and expectations at each trial.
res = group.get_results() print(res.head(1)) # print the first row
n_sim round choice_agent0 choice_agent1 payoff_agent0 payoff_agent1 \ 0 0 0 1 1 -1 1 history_agent0 history_agent1 agent0 \ 0 {'choice': 1} {'choice': 1, 'expected_value0': 0.5, 'expecte... RB ag...
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
**Again, removing the print statement gives you a more readable output**
res.head(1)
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
** to allow other authors to examine these results we have also saved the results to a new lines delimited .ndjson**
res.to_json("tutorials/paper.ndjson", orient="records", lines=True)
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
The package also provides convenient functions for plotting the agent's choices and performance. > for nicer plots we will increase the figure size using the following code. This is excluded from the paper for simplicity
import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [10, 10] # plot a heatmap of the rewards for all agent in the tournament group.plot_heatmap(cmap="RdBu_r") plt.rcParams["figure.figsize"] = [5, 5] # plot the choices of the 1-ToM agent when competing against the WSLS agent group.plot_...
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
As seen in the heatmap we see that the k-ToM model compares favorably against simpler agentssuch as the QL. Furthermore notice that the 1-ToM and 2-ToM compares especially favorablyagainst the WSLS agent as this agent act as a deterministic 0-ToM. Similarly, we see that the2-ToM agent incurs a cost for being more compl...
# plot 2-ToM estimate of its opponent sophistication level group.plot_p_k(agent0="1-TOM", agent1="2-TOM", agent=1, level=0) group.plot_p_k(agent0="1-TOM", agent1="2-TOM", agent=1, level=1)
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
It is also easy to plot k-ToM's estimates of its opponent's model parameters. As an example, the following code plots the 2-ToM's estimate of 1-ToM's volatility and bias. We see that the ToM agent approaches a correct estimate of the default volatility of -2 as well as correctly estimated its opponent as having no inhe...
# plot 2-ToM estimate of its opponent's volatility while believing the opponent to be level 1. group.plot_tom_op_estimate( agent0="1-TOM", agent1="2-TOM", agent=1, estimate="volatility", level=1, plot="mean" ) # plot 2-ToM estimate of its opponent's bias while believing the opponent to be level 1. group.plot_tom_o...
_____no_output_____
Apache-2.0
tutorials/paper_implementation.ipynb
KennethEnevoldsen/siptom
import pandas as pd import matplotlib.pyplot as plt import numpy as np import math import sklearn axes = [-2.5, 2.5, -3.5, 3.5]
_____no_output_____
MIT
Roberto_Zerbini's_Blog_Polynomial_Regression.ipynb
robertozerbini/blog
Get Data
#generate data def get_data(m): np.random.seed(3) X = np.random.randn(m, 1) y = np.sin(3 * X) + np.random.randn(m, 1) *.5 return X,y X,y = get_data(500) fig, ax = plt.subplots() plt.title('Raw Data') ax.plot(X, y, "b.") ax.axis(axes) ax.set_xlabel("X") ax.set_ylabel("y") plt.show()
_____no_output_____
MIT
Roberto_Zerbini's_Blog_Polynomial_Regression.ipynb
robertozerbini/blog
Train Linear Model
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42) from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X_train, y_train) from sklearn.metrics import mean_squared_error y_test_predicti...
_____no_output_____
MIT
Roberto_Zerbini's_Blog_Polynomial_Regression.ipynb
robertozerbini/blog
Train Polynomial Model
from sklearn.preprocessing import PolynomialFeatures degree = 8 pl = PolynomialFeatures(degree = degree) X_train_p = pl.fit_transform(X_train) X_test_p = pl.fit_transform(X_test) print('Number of features X = {} Number of features X_poly = {}'.format(X_train.shape[1], X_train_p.shape[1])) poly_reg = LinearRegression(...
_____no_output_____
MIT
Roberto_Zerbini's_Blog_Polynomial_Regression.ipynb
robertozerbini/blog
Variance Analysis
percent_diff = [] mse_train = [] mse_test = [] iter = 17 for d in range(iter): pl = PolynomialFeatures(degree = d) X_train_p = pl.fit_transform(X_train) X_test_p = pl.fit_transform(X_test) lin_reg = LinearRegression() lin_reg.fit(X_train_p, y_train) y_prediction_p = lin_reg.predict(X_train_p) lin_mse...
_____no_output_____
MIT
Roberto_Zerbini's_Blog_Polynomial_Regression.ipynb
robertozerbini/blog
Abstract In this experiment, I have tried to implement results Deep Q-network as a part of Udacity navigation project. Based on the episodic iteration I try to analyse the performance. Overview For this project, you will train an agent to navigate (and collect bananas!) in a large, square world.A reward of +1 is prov...
from IPython.display import Image from IPython.core.display import HTML Image(filename = "img.png")
_____no_output_____
MIT
report.ipynb
sajjad-ahmed/Udacity-DeepRL-Project-1-navigation
Matrix Factorisation
def get_matrix_factorisation(): movie_input = keras.layers.Input(shape=[1],name='Item') movie_embedding = keras.layers.Embedding(n_bill + 1, n_latent_factors, name='Movie-Embedding')(movie_input) movie_vec = keras.layers.Flatten(name='FlattenMovies')(movie_embedding) user_input = keras.layers.Input(sha...
movie_embedding_learnt.shape (4062, 50) user_embedding_learnt.shape (1118, 50)
Apache-2.0
neural_collaborative_filtering/embedding.ipynb
sadrayan/vote-roll-call
SHARED MODEL Non-negative Matrix factorisation (NNMF) in Keras
from keras.constraints import non_neg def get_NNMF(): movie_input = keras.layers.Input(shape=[1],name='Item') movie_embedding = keras.layers.Embedding(n_bill + 1, n_latent_factors, name='NonNegMovie-Embedding', embeddings_constraint=non_neg())(movie_input) movi...
_____no_output_____
Apache-2.0
neural_collaborative_filtering/embedding.ipynb
sadrayan/vote-roll-call
Neural networks for recommendation
n_latent_factors_user = 5 n_latent_factors_movie = 50 def get_nueral_net(): movie_input = keras.layers.Input(shape=[1],name='Item') movie_embedding = keras.layers.Embedding(n_bill + 1, n_latent_factors_movie, name='Movie-Embedding')(movie_input) movie_vec = keras.layers.Flatten(name='FlattenMovies')(movie_...
_____no_output_____
Apache-2.0
neural_collaborative_filtering/embedding.ipynb
sadrayan/vote-roll-call
Building the dataset In this notebook, I'm going to be working with three datasets to create the dataset that the chatbot will be trained on.
import pandas as pd files_path = 'D:/Sarcastic Chatbot/Input/'
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
First dataset**The Wordball Joke Dataset**, [link](https://www.kaggle.com/bfinan/jokes-question-and-answer/).This dataset consists of three files, namely:1. qajokes1.1.2.csv: with 75,114 pairs.2. t_lightbulbs.csv: with 2,640 pairs.3. t_nosubject.csv: with 32,120 pairs.However, I'm not going to incorporate t_lightbulbs...
wordball_qajokes = pd.read_csv(files_path + 'qajokes1.1.2.csv', usecols=['Question', 'Answer']) wordball_nosubj = pd.read_csv(files_path + 't_nosubject.csv', usecols=['Question', 'Answer']) print(len(wordball_qajokes)) print(len(wordball_nosubj)) wordball_qajokes.head() wordball_nosubj.head()
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Concatenate both dataframes into one:
wordball = pd.concat([wordball_qajokes, wordball_nosubj], ignore_index=True) wordball.head() print(f"Number of question-answer pairs in the Wordball dataset: {len(wordball)}")
Number of question-answer pairs in the Wordball dataset: 107234
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Text Preprocessing It turns out that not all cells are of type string. So, we can just apply the *str* function to make sure that all of them are of the same desired type.
wordball = wordball.applymap(str)
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's look at the characters used in this dataset:
def distinct_chars(data, cols): """ This method takes in a pandas dataframe and prints all distinct characters. data: a pandas dataframe. cols: a Python list, representing names of columns for questions and answers. First item of the list should be the name of the questions column and the second it...
Number of distinct characters used in the dataset: 120 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Alphabets: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
The following function replaces some characters with others, removes unwanted characters and gets rid of extra whitespaces from the data.
def clean_text(text): """ This method takes a string, applies different text preprocessing (characters replacement, removal of unwanted characters, removal of extra whitespaces) operations and returns a string. text: a string. """ import re text = str(text) # REPLACEMENT #...
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's try it out:
clean_text("A nice quote I read today: “Everything that you are going through is preparing you for what you asked for”. @hi % & =+-*/")
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
The following method prints a question-answer pair from the dataset, it will be helpful to give us a sense of what the *clean_text* function results in:
def print_question_answer(df, index, cols): print(f"Question: ({index})") print(df.loc[index][cols[0]]) print(f"Answer: ({index})") print(df.loc[index][cols[1]]) print("Before applying text preprocessing:") print_question_answer(wordball, 102, ['Question', 'Answer']) print_question_answer(wordball, 200,...
Before applying text preprocessing: Question: (102) What's 11 & 2? Answer: (102) The Cowboys Question: (200) What did the girlfriend say to her boyfriend that was bitten by a zombie? Answer: (200) You're dead to me" Question: (88376) I think my husband is psychic! "Honey, what do you think of this outfit Answer: (88376...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Apply text preprocessing (characters replacement, removal of unwanted characters, removal of extra whitespaces):
wordball = wordball.applymap(clean_text) print("After applying text preprocessing:") print_question_answer(wordball, 102, ['Question', 'Answer']) print_question_answer(wordball, 200, ['Question', 'Answer']) print_question_answer(wordball, 88376, ['Question', 'Answer']) print_question_answer(wordball, 94351, ['Question'...
After applying text preprocessing: Question: (102) what ' s 11 & 2 ? Answer: (102) the cowboys Question: (200) what did the girlfriend say to her boyfriend that was bitten by a zombie ? Answer: (200) you ' re dead to me ' Question: (88376) i think my husband is psychic ! ' honey , what do you think of this outfit Answe...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
The following function applies some preprocessing operations on the data, concretely:1. Drops unecessary duplicate pairs (rows) but keep only one instance of all duplicates. *(For example, if the dataset contains three duplicates of the same question-answer pair, then two of them would be removed and one kept.)*2. Drop...
def preprocess_data(data, cols): """ This method preprocess data and does the following: 1. drops unecessary duplicate pairs. 2. drops rows with empty strings. 3. drops rows with more than 30 words in either the question or the answer, or if the an answer has less than two characters. Argum...
# of question-answer pairs we have left in the Wordball dataset: 101712
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's look at the characters after cleaning the data:
distinct_chars(wordball, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 56 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Alphabets: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Special characters: [' ', '!', '$', '%', '&', "'", '(', ')', '*',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Second Dataset**reddit /r/Jokes**, [here](https://www.kaggle.com/cuddlefish/reddit-rjokesjokes_score_name_clean.csv).This dataset consists of two files, namely:1. jokes_score_name_clean.csv: with 133,992 pairs.2. all_jokes.csvHowever, I'm not going to incorporate all_jokes.csv in the dataset because it's so messy.
reddit_jokes = pd.read_csv(files_path + 'jokes_score_name_clean.csv', usecols=['q', 'a'])
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's rename the columns to have them aligned with the previous dataset:
reddit_jokes.rename(columns={'q':'Question', 'a':'Answer'}, inplace=True) reddit_jokes.head() print(len(reddit_jokes)) distinct_chars(reddit_jokes, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 567 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '²', '³', '¹', '₂', '₄'] Alphabets: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Text Preprocessing
reddit_jokes = reddit_jokes.applymap(str)
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Reddit data has some special tags like [removed] or [deleted] (these two mean that the comment has been removed/deleted). Also, they're written in an inconsistent way, i.e. you may find the tag [removed] capitalized or lowercased.The next function will address reddit tags as follows:1. Drops rows with deleted, removed ...
def clean_reddit_tags(data, cols): """ This function removes reddit-related tags from the data and does the following: 1. drops rows with deleted, removed or censored tags. 2. replaces other tags found in text with a whitespace. Arguments: data: a pandas dataframe. cols: a Python li...
Before addressing tags: Question: (1825) How do you piss off an entire community with one word? Answer: (1825) [Deleted] Question: (52906) [Corny] What does a highlighter say when it answers the phone? Answer: (52906) Yello? Question: (59924) How do you disappoint a redditor? Answer: (59924) [removed] Question: (1489) ...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
**Note:** the following cell may take multiple seconds to finish.
reddit_jokes = clean_reddit_tags(reddit_jokes, ['Question', 'Answer']) reddit_jokes print("After addressing tags:") # because rows with [removed], [deleted] and [censored] tags have been dropped # we're not going to print the rows (index=1825, index=59924) since they contain # those tags, or we're going to have a KeyE...
After addressing tags: Question: (52906) What does a highlighter say when it answers the phone? Answer: (52906) Yello? Question: (1489) Everything men know about women Answer: (1489)
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
**Note:** notice the question whose index is 52906, has some leading whitespaces. That's because it had the [Corny] tag and the function replaced it with whitespaces. Also, the question whose index is 1489 has an empty answer and that's because of the fact that the original answer just square brackets with some whitesp...
reddit_jokes = reddit_jokes.applymap(clean_text) print_question_answer(reddit_jokes, 52906, ['Question', 'Answer']) print_question_answer(reddit_jokes, 1489, ['Question', 'Answer'])
Question: (52906) what does a highlighter say when it answers the phone ? Answer: (52906) yello ? Question: (1489) everything men know about women Answer: (1489)
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Everything looks good!Now, let's apply the *preprocess_data* function on the data.**Remember:** the *preprocess_data* function applies the following preprocessing operations:1. Drops unecessary duplicate pairs (rows) but keep only one instance of all duplicates. *(For example, if the dataset contains three duplicates o...
reddit_jokes = preprocess_data(reddit_jokes, ['Question', 'Answer']) print(f"Number of question answer pairs in the reddit /r/Jokes dataset: {len(reddit_jokes)}") distinct_chars(reddit_jokes, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 56 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Alphabets: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Special characters: [' ', '!', '$', '%', '&', "'", '(', ')', '*',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Third Dataset**Question-Answer Jokes**, [here](https://www.kaggle.com/jiriroz/qa-jokes).This dataset consists of one file, namely:* jokes_score_name_clean.csv: with 38,269 pairs.
qa_jokes = pd.read_csv(files_path + 'jokes.csv', usecols=['Question', 'Answer']) qa_jokes print(len(qa_jokes)) distinct_chars(qa_jokes, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 237 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '³', '౪', '₄'] Alphabets: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Text Preprocessing If you look at some examples in the dataset, you notice that some examples has 'Q:' at beginning of the question and 'A:' at the beginning of the answer, so we need to get rid of these prefixes because they don't convey useful information.You also notice some examples where both 'Q:' and 'A:' are fo...
def clean_qa_prefixes(data, cols): """ This function removes special prefixes ('Q:' and 'A:') found in the data. i.e. input="Q: how's your day?" --> output=" how's your day?" Arguments: data: a pandas dataframe. cols: a Python list, representing names of columns for questions and answers...
After removing unnecessary prefixes: Question: (44) What did the left leg say to the right leg? Answer: (44) That one in the middle thinks he's hard. Question: (22) Why does Santa have three gardens? Answer: (22) So he can "hoe, hoe, hoe." Question: (31867) What is your favorite joke about women? Answer: (31867) Q: W...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Notice that the third example both 'Q:' and 'A:' are part of the answer and conveys information. Now, let's apply the *clean_text* function on the Question-Answer Jokes data.**Remember:** the *clean_text* function replaces some characters with others, removes unwanted characters and gets rid of extra whitespaces from t...
qa_jokes = qa_jokes.applymap(clean_text)
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Now, let's apply the *preprocess_data* function on the data.**Remember:** the *preprocess_data* function applies the following preprocessing operations:1. Drops unnecessary duplicate pairs (rows) but keep only one instance of all duplicates. *(For example, if the dataset contains three duplicates of the same question-a...
qa_jokes = preprocess_data(qa_jokes, ['Question', 'Answer']) print(f"Number of question-answer pairs in the Question-Answer Jokes dataset: {len(qa_jokes)}") distinct_chars(qa_jokes, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 56 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Alphabets: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Special characters: [' ', '!', '$', '%', '&', "'", '(', ')', '*',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Putting it togetherLet's concatenate all the data we have to create our final dataset.
dataset = pd.concat([wordball, reddit_jokes, qa_jokes], ignore_index=True) dataset.head() print(f"Number of question-answer pairs in the dataset: {len(dataset)}")
Number of question-answer pairs in the dataset: 227799
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
There may be duplicate examples in the data so let's drop them:
data_len_before = len(dataset) # len of data before removing duplicates print(f"# of examples before removing duplicates: {data_len_before}") # drop duplicates dataset = dataset.drop_duplicates(keep='first') data_len_after = len(dataset) # len of data after removing duplicates print(f"# of examples after removing dupli...
# of examples before removing duplicates: 227799 # of examples after removing duplicates: 175671 # of removed duplicates: 52128
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's drop rows with NaN values if there's any:
dataset.dropna(inplace=True) dataset
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Let's make sure that all our cells are of the same type:
dataset = dataset.applymap(str) print(f"Number of question-answer pairs in the dataset: {len(dataset)}") distinct_chars(dataset, ['Question', 'Answer'])
Number of distinct characters used in the dataset: 56 Digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Alphabets: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Special characters: [' ', '!', '$', '%', '&', "'", '(', ')', '*',...
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
Finally, let's save the dataset:
dataset.to_csv(files_path + '/dataset.csv')
_____no_output_____
Apache-2.0
Sarcastic Chatbot - Build The Dataset.ipynb
MohamedAliHabib/Sarcastic-Chatbot
선형연립방정식 사례: 간단한 트러스Example of Systems of Linear Equations : Simple Truss
# 그래프, 수학 기능 추가 # Add graph and math features import pylab as py import numpy as np import numpy.linalg as nl # 기호 연산 기능 추가 # Add symbolic operation capability import sympy as sy
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
화살표를 그리는 함수Function to draw an arrow
def draw_2dvec(x, y, x0=0, y0=0, color='k', name=None): py.quiver(x0, y0, x, y, color=color, angles='xy', scale_units='xy', scale=1) if name is not None: if not name.startswith('$'): vec_str = '$\\vec{%s}$' % name else: vec_str = name py.text(0.5 * x + x0, 0.5 * y...
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
정삼각형을 그리는 함수Function to draw an equilateral triangle
def triangle_support(x, y, length): # https://matplotlib.org/gallery/lines_bars_and_markers/fill.html height = py.cos(py.radians(30)) * length py.fill((x, x + length*0.5, x + length*-0.5), (y, y - height, y - height))
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
4 절점 트러스A Four Node Truss 다음과 같은 트러스를 생각해 보자.Let's think about a truss as follows.(ref: "[Application of system of linear equations](https://www.chegg.com/homework-help/questions-and-answers/application-system-linear-equations-sure-work-matlab-problem-figure-1-shows-mechanical-str-q22676917)", Chegg Study)
# 마디점 좌표 nodal point coordinates xy_list = [(0, 0), (1, 1), (1, 0), (2, 0)] # 각 부재의 양 끝 점 end points of each member connectivity_list = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)] for k, i_j in enumerate(connectivity_list): i, j = i_j py.plot( (xy_list[i][0], xy_list[j][0]), (xy_list[i][1], xy_l...
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
모든 각은 45도 이다.All angles are 45 degrees. $$\alpha = sin\left(\frac{\pi}{4}\right) = cos\left(\frac{\pi}{4}\right)$$ 각 마디에서의 힘의 평형은 다음과 같다. $f_i$ 는 $i$번째 부재의 장력이다.Force equilibrium equations at respective nodes are as follows. $f_i$ is the tensile force of $i$th member. $$\begin{align} R_{1x} + \alpha \cdot f_{1}+...
alpha = py.sin(py.radians(45)) matrix = py.matrix([ [1, 0, alpha, 1, 0, 0, 0, 0], [0, 1, alpha, 0, 0, 0, 0, 0], [0, 0, -alpha, 0, 0, alpha, 0, 0], [0, 0, -alpha, 0, -1, -alpha, 0, 0], [0, 0, 0, -1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, ...
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
행렬의 계수를 계산해 보자.Let's check the rank of the matrix.
nl.matrix_rank(matrix)
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp