repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
yangliuy/bert_hae
[ "5c8eeed4cd7be6b11c42a743fddc461f69011469" ]
[ "hae.py" ]
[ "\n# coding: utf-8\n\n# In[1]:\n\n\n# A BERT model with history answer embedding (HAE)\n\n\n# In[2]:\n\n\n# import os\n# os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"3\"\n\n\n# In[3]:\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport math\nimport os\nimport modeling\nimport optimization\nimport tokenization\nimport six\nimport tensorflow as tf\nimport numpy as np\nfrom copy import deepcopy\nimport pickle\nimport itertools\nfrom time import time\n\nfrom cqa_supports import *\nfrom cqa_flags import FLAGS\nfrom cqa_model import *\nfrom cqa_gen_batches import *\n\nfrom scorer import external_call # quac official evaluation script\n\n\n# In[4]:\n\n\nfor key in FLAGS:\n print(key, ':', FLAGS[key].value)\n\ntf.set_random_seed(0)\ntf.logging.set_verbosity(tf.logging.INFO)\nbert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\nif FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\ntf.gfile.MakeDirs(FLAGS.output_dir)\ntf.gfile.MakeDirs(FLAGS.output_dir + '/summaries/train/')\ntf.gfile.MakeDirs(FLAGS.output_dir + '/summaries/val/')\ntf.gfile.MakeDirs(FLAGS.output_dir + '/summaries/rl/')\n\ntokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\nif FLAGS.do_train:\n # read in training data, generate training features, and generate training batches\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n train_file = FLAGS.quac_train_file\n train_examples = read_quac_examples(input_file=train_file, is_training=True)\n \n \n # we attempt to read features from cache\n features_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/train_features_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n example_tracker_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/example_tracker_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n variation_tracker_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/variation_tracker_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n example_features_nums_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/example_features_nums_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n \n try:\n print('attempting to load train features from cache')\n with open(features_fname, 'rb') as handle:\n train_features = pickle.load(handle)\n with open(example_tracker_fname, 'rb') as handle:\n example_tracker = pickle.load(handle)\n with open(variation_tracker_fname, 'rb') as handle:\n variation_tracker = pickle.load(handle)\n with open(example_features_nums_fname, 'rb') as handle:\n example_features_nums = pickle.load(handle)\n except:\n print('train feature cache does not exist, generating')\n train_features, example_tracker, variation_tracker, example_features_nums = convert_examples_to_variations_and_then_features(\n examples=train_examples, tokenizer=tokenizer, \n max_seq_length=FLAGS.max_seq_length, doc_stride=FLAGS.doc_stride, \n max_query_length=FLAGS.max_query_length, \n max_considered_history_turns=FLAGS.max_considered_history_turns, \n is_training=True)\n with open(features_fname, 'wb') as handle:\n pickle.dump(train_features, handle)\n with open(example_tracker_fname, 'wb') as handle:\n pickle.dump(example_tracker, handle)\n with open(variation_tracker_fname, 'wb') as handle:\n pickle.dump(variation_tracker, handle) \n with open(example_features_nums_fname, 'wb') as handle:\n pickle.dump(example_features_nums, handle) \n print('train features generated')\n \n train_batches = cqa_gen_example_aware_batches(train_features, example_tracker, variation_tracker, \n example_features_nums, FLAGS.train_batch_size, \n FLAGS.num_train_epochs, shuffle=False)\n \n num_train_steps = FLAGS.train_steps\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\nif FLAGS.do_predict:\n # read in validation data, generate val features\n val_file = FLAGS.quac_predict_file\n val_examples = read_quac_examples(input_file=val_file, is_training=False)\n \n # we read in the val file in json for the external_call function in the validation step\n val_file_json = json.load(open(val_file, 'r'))['data']\n \n # we attempt to read features from cache\n features_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/val_features_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n example_tracker_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/val_example_tracker_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n variation_tracker_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/val_variation_tracker_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n example_features_nums_fname = FLAGS.cache_dir + FLAGS.dataset.lower() + '/val_example_features_nums_{}_{}.pkl'.format(FLAGS.load_small_portion, FLAGS.max_considered_history_turns)\n \n try:\n print('attempting to load val features from cache')\n with open(features_fname, 'rb') as handle:\n val_features = pickle.load(handle)\n with open(example_tracker_fname, 'rb') as handle:\n val_example_tracker = pickle.load(handle)\n with open(variation_tracker_fname, 'rb') as handle:\n val_variation_tracker = pickle.load(handle)\n with open(example_features_nums_fname, 'rb') as handle:\n val_example_features_nums = pickle.load(handle)\n except:\n print('val feature cache does not exist, generating')\n val_features, val_example_tracker, val_variation_tracker, val_example_features_nums = convert_examples_to_variations_and_then_features(\n examples=val_examples, tokenizer=tokenizer, \n max_seq_length=FLAGS.max_seq_length, doc_stride=FLAGS.doc_stride, \n max_query_length=FLAGS.max_query_length, \n max_considered_history_turns=FLAGS.max_considered_history_turns, \n is_training=False)\n with open(features_fname, 'wb') as handle:\n pickle.dump(val_features, handle)\n with open(example_tracker_fname, 'wb') as handle:\n pickle.dump(val_example_tracker, handle)\n with open(variation_tracker_fname, 'wb') as handle:\n pickle.dump(val_variation_tracker, handle) \n with open(example_features_nums_fname, 'wb') as handle:\n pickle.dump(val_example_features_nums, handle)\n print('val features generated')\n \n \n num_val_examples = len(val_examples)\n \n\n# tf Graph input\nunique_ids = tf.placeholder(tf.int32, shape=[None], name='unique_ids')\ninput_ids = tf.placeholder(tf.int32, shape=[None, FLAGS.max_seq_length], name='input_ids')\ninput_mask = tf.placeholder(tf.int32, shape=[None, FLAGS.max_seq_length], name='input_mask')\nsegment_ids = tf.placeholder(tf.int32, shape=[None, FLAGS.max_seq_length], name='segment_ids')\nstart_positions = tf.placeholder(tf.int32, shape=[None], name='start_positions')\nend_positions = tf.placeholder(tf.int32, shape=[None], name='end_positions')\nhistory_answer_marker = tf.placeholder(tf.int32, shape=[None, FLAGS.max_seq_length], name='history_answer_marker')\ntraining = tf.placeholder(tf.bool, name='training')\nget_segment_rep = tf.placeholder(tf.bool, name='get_segment_rep')\n\n\nbert_representation = bert_rep(\n bert_config=bert_config,\n is_training=training,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n history_answer_marker=history_answer_marker,\n use_one_hot_embeddings=False\n )\n \n(start_logits, end_logits) = cqa_model(bert_representation)\n\n\ntvars = tf.trainable_variables()\n\ninitialized_variable_names = {}\nif FLAGS.init_checkpoint:\n (assignment_map, initialized_variable_names) = modeling.get_assigment_map_from_checkpoint(tvars, \n FLAGS.init_checkpoint)\n tf.train.init_from_checkpoint(FLAGS.init_checkpoint, assignment_map)\n\n# compute loss\nseq_length = modeling.get_shape_list(input_ids)[1]\ndef compute_loss(logits, positions):\n one_hot_positions = tf.one_hot(\n positions, depth=seq_length, dtype=tf.float32)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n loss = -tf.reduce_mean(tf.reduce_sum(one_hot_positions * log_probs, axis=-1))\n return loss\n\n# get the max prob for the predicted start/end position\nstart_probs = tf.nn.softmax(start_logits, axis=-1)\nstart_prob = tf.reduce_max(start_probs, axis=-1)\nend_probs = tf.nn.softmax(end_logits, axis=-1)\nend_prob = tf.reduce_max(end_probs, axis=-1)\n\nstart_loss = compute_loss(start_logits, start_positions)\nend_loss = compute_loss(end_logits, end_positions)\ntotal_loss = (start_loss + end_loss) / 2.0\ntf.summary.scalar('total_loss', total_loss)\n\n\nif FLAGS.do_train:\n train_op = optimization.create_optimizer(total_loss, FLAGS.learning_rate, num_train_steps, num_warmup_steps, False)\n\n print(\"***** Running training *****\")\n print(\" Num orig examples = %d\", len(train_examples))\n print(\" Num train_features = %d\", len(train_features))\n print(\" Batch size = %d\", FLAGS.train_batch_size)\n print(\" Num steps = %d\", num_train_steps)\n \nmerged_summary_op = tf.summary.merge_all()\n\nRawResult = collections.namedtuple(\"RawResult\", [\"unique_id\", \"start_logits\", \"end_logits\"])\n\nsaver = tf.train.Saver()\n# Initializing the variables\ninit = tf.global_variables_initializer()\ntf.get_default_graph().finalize()\nwith tf.Session() as sess:\n sess.run(init)\n\n if FLAGS.do_train:\n train_summary_writer = tf.summary.FileWriter(FLAGS.output_dir + 'summaries/train', sess.graph)\n val_summary_writer = tf.summary.FileWriter(FLAGS.output_dir + 'summaries/val')\n \n f1_list = []\n heq_list = []\n dheq_list = []\n \n # Training cycle\n for step, batch in enumerate(train_batches):\n if step > num_train_steps:\n # this means the learning rate has been decayed to 0\n break\n \n batch_features, batch_example_tracker, batch_variation_tracker = batch\n \n\n selected_example_features, relative_selected_pos = get_selected_example_features_without_actions(\n batch_features, batch_example_tracker, batch_variation_tracker)\n\n fd = convert_features_to_feed_dict(selected_example_features) # feed_dict\n try:\n _, train_summary, total_loss_res = sess.run([train_op, merged_summary_op, total_loss], \n feed_dict={unique_ids: fd['unique_ids'], input_ids: fd['input_ids'], \n input_mask: fd['input_mask'], segment_ids: fd['segment_ids'], \n start_positions: fd['start_positions'], end_positions: fd['end_positions'], \n history_answer_marker: fd['history_answer_marker'], training: True})\n except:\n print('features length: ', len(selected_example_features))\n\n train_summary_writer.add_summary(train_summary, step)\n train_summary_writer.flush()\n print('training step: {}, total_loss: {}'.format(step, total_loss_res))\n \n if step >= FLAGS.evaluate_after and step % FLAGS.evaluation_steps == 0 and step != 0:\n val_total_loss = []\n all_results = []\n all_selected_examples = []\n all_selected_features = []\n \n total_num_selected = 0\n total_num_actions = 0\n total_num_examples = 0\n \n val_batches = cqa_gen_example_aware_batches(val_features, val_example_tracker, val_variation_tracker, \n val_example_features_nums, FLAGS.predict_batch_size, 1, shuffle=False)\n \n for val_batch in val_batches:\n\n batch_results = []\n batch_features, batch_example_tracker, batch_variation_tracker = val_batch\n \n selected_example_features, relative_selected_pos = get_selected_example_features_without_actions(\n batch_features, batch_example_tracker, batch_variation_tracker)\n\n \n try:\n all_selected_features.extend(selected_example_features)\n\n fd = convert_features_to_feed_dict(selected_example_features) # feed_dict\n start_logits_res, end_logits_res, batch_total_loss = sess.run([start_logits, end_logits, total_loss], \n feed_dict={unique_ids: fd['unique_ids'], input_ids: fd['input_ids'], \n input_mask: fd['input_mask'], segment_ids: fd['segment_ids'], \n start_positions: fd['start_positions'], end_positions: fd['end_positions'], \n history_answer_marker: fd['history_answer_marker'], training: False})\n\n val_total_loss.append(batch_total_loss)\n\n for each_unique_id, each_start_logits, each_end_logits in zip(fd['unique_ids'], start_logits_res, \n end_logits_res): \n each_unique_id = int(each_unique_id)\n each_start_logits = [float(x) for x in each_start_logits.flat]\n each_end_logits = [float(x) for x in each_end_logits.flat]\n batch_results.append(RawResult(unique_id=each_unique_id, start_logits=each_start_logits, \n end_logits=each_end_logits))\n\n all_results.extend(batch_results)\n except:\n print('batch dropped because too large!')\n\n output_prediction_file = os.path.join(FLAGS.output_dir, \"predictions_{}.json\".format(step))\n output_nbest_file = os.path.join(FLAGS.output_dir, \"nbest_predictions_{}.json\".format(step))\n\n write_predictions(val_examples, all_selected_features, all_results,\n FLAGS.n_best_size, FLAGS.max_answer_length,\n FLAGS.do_lower_case, output_prediction_file,\n output_nbest_file)\n\n val_total_loss_value = np.average(val_total_loss)\n \n \n # call the official evaluation script\n val_summary = tf.Summary() \n val_eval_res = external_call(val_file_json, output_prediction_file)\n\n val_f1 = val_eval_res['f1']\n val_followup = val_eval_res['followup']\n val_yesno = val_eval_res['yes/no']\n val_heq = val_eval_res['HEQ']\n val_dheq = val_eval_res['DHEQ']\n\n heq_list.append(val_heq)\n dheq_list.append(val_dheq)\n\n val_summary.value.add(tag=\"followup\", simple_value=val_followup)\n val_summary.value.add(tag=\"val_yesno\", simple_value=val_yesno)\n val_summary.value.add(tag=\"val_heq\", simple_value=val_heq)\n val_summary.value.add(tag=\"val_dheq\", simple_value=val_dheq)\n\n print('evaluation: {}, total_loss: {}, f1: {}, followup: {}, yesno: {}, heq: {}, dheq: {}\\n'.format(\n step, val_total_loss_value, val_f1, val_followup, val_yesno, val_heq, val_dheq))\n with open(FLAGS.output_dir + 'step_result.txt', 'a') as fout:\n fout.write('{},{},{},{},{},{}\\n'.format(step, val_f1, val_heq, val_dheq, \n FLAGS.history, FLAGS.output_dir))\n \n val_summary.value.add(tag=\"total_loss\", simple_value=val_total_loss_value)\n val_summary.value.add(tag=\"f1\", simple_value=val_f1)\n f1_list.append(val_f1)\n \n val_summary_writer.add_summary(val_summary, step)\n val_summary_writer.flush()\n \n save_path = saver.save(sess, '{}/model_{}.ckpt'.format(FLAGS.output_dir, step))\n print('Model saved in path', save_path)\n\n \n\n\n# In[5]:\n\n\nbest_f1 = max(f1_list)\nbest_f1_idx = f1_list.index(best_f1)\nbest_heq = heq_list[best_f1_idx]\nbest_dheq = dheq_list[best_f1_idx]\nwith open(FLAGS.output_dir + 'result.txt', 'w') as fout:\n fout.write('{},{},{},{},{}\\n'.format(best_f1, best_heq, best_dheq, FLAGS.history, FLAGS.output_dir))\n\n" ]
[ [ "tensorflow.nn.log_softmax", "tensorflow.reduce_sum", "tensorflow.train.init_from_checkpoint", "tensorflow.gfile.MakeDirs", "tensorflow.get_default_graph", "tensorflow.summary.scalar", "tensorflow.logging.set_verbosity", "tensorflow.Session", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.Summary", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.summary.merge_all", "tensorflow.one_hot", "tensorflow.set_random_seed", "tensorflow.reduce_max", "tensorflow.nn.softmax", "tensorflow.summary.FileWriter", "numpy.average" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
sander-adam/four-in-a-row-competition
[ "6a35d0375ce079ba94662d9fc9d2d54669a5725c" ]
[ "game.py" ]
[ "'''\nWe are playing the classic 'four in a row' game. Two players (1/2, blue/red) play against each other. Player 1/blue start.\nChips can only be placed on the bottom of each column. First player to get four in a row (horizontally, vertically or \ndiagonal) wins. \n\nInterface:\n\nRules:\n'''\nimport pandas as pd\nimport numpy as np\nimport random\n\nfrom agents import *\n\nclass InvalidMove(Exception):\n '''Raise for invalid moves'''\n pass\n\n\nclass FourInARow:\n def __init__(self, agents):\n self.board_width = 7\n self.col_range = range(self.board_width)\n self.board_height = 6\n self.row_range = range(self.board_height)\n self.board = pd.DataFrame(0, index = self.row_range, columns = self.col_range, dtype = 'uint8')\n self.winner = 0\n self.status = 'new' # Game status in [new, playing, finished, error]\n self.agents = agents\n\n def play(self):\n print('We are ready to play some FourInARow')\n self.status = 'playing'\n self.turn = 0\n\n while True:\n self.turn += 1\n\n print('Ready for turn {turn}')\n print(self.board)\n\n # Determine move\n player = (self.turn % 2) + 1\n agent = self.agents[player]\n column = agent.move(self)\n \n # Execute move\n print(f'Player {player} ({agent.name}) plays column {column}')\n if self.move(column=column, player=player):\n print(self.board)\n print(f'Player {player} ({agent.name}) wins after {self.turn} turns!!')\n break\n\n\n def move(self, *, player=None, column=None):\n '''Make a move '''\n assert column in list(range(7))\n assert player in [1,2]\n\n \n row = (self.board[column] == 0).sum() - 1\n if row < 0:\n raise InvalidMove \n\n self.board.loc[row, column] = player\n return self.check_winner(player, column)\n\n def check_winner(self, player, column_index):\n '''Check whether the selected player has won'''\n added_chip_row = self.board[column_index].idxmax(player)\n \n dirs = (\n (0,1),\n (1,0),\n (1,1),\n (1, -1),\n )\n\n for row_dir, col_dir in dirs:\n row_length = 1\n\n row,col = added_chip_row, column_index,\n while True:\n row += row_dir\n col += col_dir\n if (row in self.row_range) and (col in self.col_range) and (self.board.loc[row, col] == player):\n row_length += 1\n else:\n break\n \n row,col = added_chip_row, column_index,\n while True:\n row -= row_dir\n col -= col_dir\n if (row in self.row_range) and (col in self.col_range) and (self.board.loc[row, col] == player):\n row_length += 1\n else:\n break\n\n if row_length >= 4:\n return True\n return False\n\n def legal_moves(self):\n return list(self.board.columns[self.board.loc[0] == 0])\n\n\n\nagent1 = RandomMove()\nagent2 = AllLeft()\n\ngame = FourInARow(agents = {1: agent1, 2: agent2})\n\ngame.play()\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
gaozhihan/gluon-ts
[ "a28bd7f044a9a1641d8eb5b6cada8c9aa8ce5cc9" ]
[ "src/gluonts/model/deepstate/issm.py" ]
[ "# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nfrom typing import List, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.tseries.frequencies import to_offset\n\nfrom gluonts.core.component import validated\nfrom gluonts.mx import Tensor\nfrom gluonts.mx.distribution.distribution import getF\nfrom gluonts.mx.util import _broadcast_param\nfrom gluonts.time_feature import (\n DayOfWeekIndex,\n HourOfDayIndex,\n MinuteOfHourIndex,\n MonthOfYearIndex,\n TimeFeature,\n WeekOfYearIndex,\n norm_freq_str,\n)\n\n\ndef _make_block_diagonal(blocks: List[Tensor]) -> Tensor:\n assert (\n len(blocks) > 0\n ), \"You need at least one tensor to make a block-diagonal tensor\"\n\n if len(blocks) == 1:\n return blocks[0]\n\n F = getF(blocks[0])\n\n # transition coefficient is block diagonal!\n block_diagonal = _make_2_block_diagonal(F, blocks[0], blocks[1])\n for i in range(2, len(blocks)):\n block_diagonal = _make_2_block_diagonal(\n F=F, left=block_diagonal, right=blocks[i]\n )\n\n return block_diagonal\n\n\ndef _make_2_block_diagonal(F, left: Tensor, right: Tensor) -> Tensor:\n \"\"\"\n Creates a block diagonal matrix of shape (batch_size, m+n, m+n) where m and n are the sizes of\n the axis 1 of left and right respectively.\n\n Parameters\n ----------\n F\n left\n Tensor of shape (batch_size, seq_length, m, m)\n right\n Tensor of shape (batch_size, seq_length, n, n)\n Returns\n -------\n Tensor\n Block diagonal matrix of shape (batch_size, seq_length, m+n, m+n)\n \"\"\"\n # shape (batch_size, seq_length, m, n)\n zeros_off_diag = F.broadcast_add(\n left.slice_axis(\n axis=-1, begin=0, end=1\n ).zeros_like(), # shape (batch_size, seq_length, m, 1)\n right.slice_axis(\n axis=-2, begin=0, end=1\n ).zeros_like(), # shape (batch_size, seq_length, 1, n)\n )\n\n # shape (batch_size, n, m)\n zeros_off_diag_tr = zeros_off_diag.swapaxes(2, 3)\n\n # block diagonal: shape (batch_size, seq_length, m+n, m+n)\n _block_diagonal = F.concat(\n F.concat(left, zeros_off_diag, dim=3),\n F.concat(zeros_off_diag_tr, right, dim=3),\n dim=2,\n )\n\n return _block_diagonal\n\n\nclass ZeroFeature(TimeFeature):\n \"\"\"\n A feature that is identically zero.\n \"\"\"\n\n def __call__(self, index: pd.DatetimeIndex) -> np.ndarray:\n return np.zeros(index.values.shape)\n\n\nclass ISSM:\n r\"\"\"\n An abstract class for providing the basic structure of Innovation State Space Model (ISSM).\n\n The structure of ISSM is given by\n\n * dimension of the latent state\n * transition and innovation coefficients of the transition model\n * emission coefficient of the observation model\n\n \"\"\"\n\n @validated()\n def __init__(self):\n pass\n\n def latent_dim(self) -> int:\n raise NotImplementedError\n\n def output_dim(self) -> int:\n raise NotImplementedError\n\n def time_features(self) -> List[TimeFeature]:\n raise NotImplementedError\n\n def emission_coeff(self, features: Tensor) -> Tensor:\n raise NotImplementedError\n\n def transition_coeff(self, features: Tensor) -> Tensor:\n raise NotImplementedError\n\n def innovation_coeff(self, features: Tensor) -> Tensor:\n raise NotImplementedError\n\n def get_issm_coeff(\n self, features: Tensor\n ) -> Tuple[Tensor, Tensor, Tensor]:\n return (\n self.emission_coeff(features),\n self.transition_coeff(features),\n self.innovation_coeff(features),\n )\n\n\nclass LevelISSM(ISSM):\n def latent_dim(self) -> int:\n return 1\n\n def output_dim(self) -> int:\n return 1\n\n def time_features(self) -> List[TimeFeature]:\n return [ZeroFeature()]\n\n def emission_coeff(\n self, feature: Tensor # (batch_size, time_length, 1)\n ) -> Tensor:\n F = getF(feature)\n\n _emission_coeff = F.ones(shape=(1, 1, 1, self.latent_dim()))\n\n # get the right shape: (batch_size, time_length, obs_dim, latent_dim)\n zeros = _broadcast_param(\n feature.squeeze(axis=2),\n axes=[2, 3],\n sizes=[1, self.latent_dim()],\n )\n\n return _emission_coeff.broadcast_like(zeros)\n\n def transition_coeff(\n self, feature: Tensor # (batch_size, time_length, 1)\n ) -> Tensor:\n F = getF(feature)\n\n _transition_coeff = (\n F.eye(self.latent_dim()).expand_dims(axis=0).expand_dims(axis=0)\n )\n\n # get the right shape: (batch_size, time_length, latent_dim, latent_dim)\n zeros = _broadcast_param(\n feature.squeeze(axis=2),\n axes=[2, 3],\n sizes=[self.latent_dim(), self.latent_dim()],\n )\n\n return _transition_coeff.broadcast_like(zeros)\n\n def innovation_coeff(\n self, feature: Tensor # (batch_size, time_length, 1)\n ) -> Tensor:\n return self.emission_coeff(feature).squeeze(axis=2)\n\n\nclass LevelTrendISSM(LevelISSM):\n def latent_dim(self) -> int:\n return 2\n\n def output_dim(self) -> int:\n return 1\n\n def time_features(self) -> List[TimeFeature]:\n return [ZeroFeature()]\n\n def transition_coeff(\n self, feature: Tensor # (batch_size, time_length, 1)\n ) -> Tensor:\n F = getF(feature)\n\n _transition_coeff = (\n (F.diag(F.ones(shape=(2,)), k=0) + F.diag(F.ones(shape=(1,)), k=1))\n .expand_dims(axis=0)\n .expand_dims(axis=0)\n )\n\n # get the right shape: (batch_size, time_length, latent_dim, latent_dim)\n zeros = _broadcast_param(\n feature.squeeze(axis=2),\n axes=[2, 3],\n sizes=[self.latent_dim(), self.latent_dim()],\n )\n\n return _transition_coeff.broadcast_like(zeros)\n\n\nclass SeasonalityISSM(LevelISSM):\n \"\"\"\n Implements periodic seasonality which is entirely determined by the period `num_seasons`.\n \"\"\"\n\n @validated()\n def __init__(self, num_seasons: int, time_feature: TimeFeature) -> None:\n super(SeasonalityISSM, self).__init__()\n self.num_seasons = num_seasons\n self.time_feature = time_feature\n\n def latent_dim(self) -> int:\n return self.num_seasons\n\n def output_dim(self) -> int:\n return 1\n\n def time_features(self) -> List[TimeFeature]:\n return [self.time_feature]\n\n def emission_coeff(self, feature: Tensor) -> Tensor:\n F = getF(feature)\n return F.one_hot(feature, depth=self.latent_dim())\n\n def innovation_coeff(self, feature: Tensor) -> Tensor:\n F = getF(feature)\n return F.one_hot(feature, depth=self.latent_dim()).squeeze(axis=2)\n\n\ndef MonthOfYearSeasonalISSM():\n return SeasonalityISSM(num_seasons=12, time_feature=MonthOfYearIndex())\n\n\ndef WeekOfYearSeasonalISSM():\n return SeasonalityISSM(num_seasons=53, time_feature=WeekOfYearIndex())\n\n\ndef DayOfWeekSeasonalISSM():\n return SeasonalityISSM(num_seasons=7, time_feature=DayOfWeekIndex())\n\n\ndef HourOfDaySeasonalISSM():\n return SeasonalityISSM(num_seasons=24, time_feature=HourOfDayIndex())\n\n\ndef MinuteOfHourSeasonalISSM():\n return SeasonalityISSM(num_seasons=60, time_feature=MinuteOfHourIndex())\n\n\nclass CompositeISSM(ISSM):\n DEFAULT_ADD_TREND: bool = True\n\n @validated()\n def __init__(\n self,\n seasonal_issms: List[SeasonalityISSM],\n add_trend: bool = DEFAULT_ADD_TREND,\n ) -> None:\n super(CompositeISSM, self).__init__()\n self.seasonal_issms = seasonal_issms\n self.nonseasonal_issm = (\n LevelISSM() if add_trend is False else LevelTrendISSM()\n )\n\n def latent_dim(self) -> int:\n return (\n sum([issm.latent_dim() for issm in self.seasonal_issms])\n + self.nonseasonal_issm.latent_dim()\n )\n\n def output_dim(self) -> int:\n return self.nonseasonal_issm.output_dim()\n\n def time_features(self) -> List[TimeFeature]:\n ans = self.nonseasonal_issm.time_features()\n for issm in self.seasonal_issms:\n ans.extend(issm.time_features())\n return ans\n\n @classmethod\n def get_from_freq(cls, freq: str, add_trend: bool = DEFAULT_ADD_TREND):\n offset = to_offset(freq)\n\n seasonal_issms: List[SeasonalityISSM] = []\n\n if offset.name == \"M\":\n seasonal_issms = [MonthOfYearSeasonalISSM()]\n elif norm_freq_str(offset.name) == \"W\":\n seasonal_issms = [WeekOfYearSeasonalISSM()]\n elif offset.name == \"D\":\n seasonal_issms = [DayOfWeekSeasonalISSM()]\n elif offset.name == \"B\": # TODO: check this case\n seasonal_issms = [DayOfWeekSeasonalISSM()]\n elif offset.name == \"H\":\n seasonal_issms = [\n HourOfDaySeasonalISSM(),\n DayOfWeekSeasonalISSM(),\n ]\n elif offset.name == \"T\":\n seasonal_issms = [\n MinuteOfHourSeasonalISSM(),\n HourOfDaySeasonalISSM(),\n ]\n else:\n RuntimeError(f\"Unsupported frequency {offset.name}\")\n\n return cls(seasonal_issms=seasonal_issms, add_trend=add_trend)\n\n def get_issm_coeff(\n self, features: Tensor # (batch_size, time_length, num_features)\n ) -> Tuple[Tensor, Tensor, Tensor]:\n F = getF(features)\n emission_coeff_ls, transition_coeff_ls, innovation_coeff_ls = zip(\n *[\n issm.get_issm_coeff(\n features.slice_axis(axis=-1, begin=ix, end=ix + 1)\n )\n for ix, issm in enumerate(\n [self.nonseasonal_issm] + self.seasonal_issms\n )\n ],\n )\n\n # stack emission and innovation coefficients\n emission_coeff = F.concat(*emission_coeff_ls, dim=-1)\n\n innovation_coeff = F.concat(*innovation_coeff_ls, dim=-1)\n\n # transition coefficient is block diagonal!\n transition_coeff = _make_block_diagonal(transition_coeff_ls)\n\n return emission_coeff, transition_coeff, innovation_coeff\n" ]
[ [ "pandas.tseries.frequencies.to_offset", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20", "1.0", "0.25" ], "scipy": [], "tensorflow": [] } ]
loiccoyle/dtaidistance
[ "5316fad44513db745c2447abe3e9e0f0c22dd308" ]
[ "tests/test_cython.py" ]
[ "import pytest\nimport numpy as np\nimport sys\nimport os\nimport math\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\nfrom dtaidistance import dtw, dtw_c\n\n\ndef test_numpymatrix():\n \"\"\"Passing a matrix instead of a list failed because the array is now a\n view instead of the original data structure.\"\"\"\n s = np.array([\n [0., 0, 1, 2, 1, 0, 1, 0, 0],\n [0., 1, 2, 0, 0, 0, 0, 0, 0],\n [1., 2, 0, 0, 0, 0, 0, 1, 0]])\n m = dtw_c.distance_matrix_nogil(s)\n m = dtw.distances_array_to_matrix(m, len(s))\n m2 = dtw.distance_matrix(s)\n correct = np.array([\n [np.inf, 1.41421356, 1.73205081],\n [np.inf, np.inf, 1.41421356],\n [np.inf, np.inf, np.inf]])\n assert m[0, 1] == pytest.approx(math.sqrt(2))\n assert m2[0, 1] == pytest.approx(math.sqrt(2))\n np.testing.assert_almost_equal(correct, m, decimal=4)\n np.testing.assert_almost_equal(correct, m2, decimal=4)\n\n\ndef test_numpymatrix_compact():\n \"\"\"Passing a matrix instead of a list failed because the array is now a\n view instead of the original data structure.\"\"\"\n s = np.array([\n [0., 0, 1, 2, 1, 0, 1, 0, 0],\n [0., 1, 2, 0, 0, 0, 0, 0, 0],\n [1., 2, 0, 0, 0, 0, 0, 1, 0]])\n m = dtw_c.distance_matrix_nogil(s)\n m2 = dtw.distance_matrix(s, compact=True)\n correct = np.array([1.41421356, 1.73205081, 1.41421356])\n assert m[0] == pytest.approx(math.sqrt(2))\n assert m2[0] == pytest.approx(math.sqrt(2))\n np.testing.assert_almost_equal(correct, m, decimal=4)\n np.testing.assert_almost_equal(correct, m2, decimal=4)\n\n\ndef test_numpymatrix_transpose():\n \"\"\"Passing a matrix instead of a list failed because the array is now a\n view instead of the original data structure.\"\"\"\n s = np.array([\n [0., 0., 1.,],\n [0, 1, 2],\n [1, 2, 0],\n [2, 0, 0],\n [1, 0, 0],\n [0, 0, 0],\n [1, 0, 0],\n [0, 0, 1],\n [0, 0, 0]\n ]).T\n m = dtw_c.distance_matrix_nogil(s)\n m = dtw.distances_array_to_matrix(m, len(s))\n m2 = dtw.distance_matrix(s)\n correct = np.array([\n [np.inf, 1.41421356, 1.73205081],\n [np.inf, np.inf, 1.41421356],\n [np.inf, np.inf, np.inf]])\n assert m[0, 1] == pytest.approx(math.sqrt(2))\n assert m2[0, 1] == pytest.approx(math.sqrt(2))\n np.testing.assert_almost_equal(correct, m, decimal=4)\n np.testing.assert_almost_equal(correct, m2, decimal=4)\n\n\n# def test_negativedimensions():\n# \"\"\"Failed for sizes of (62706, 104): ValueError: negative dimensions are not allowed\n# \"\"\"\n# s = np.array([[ 0., 0., 0., 0., 2., 4., 5., 10., 11., 10., 10., 6., 3.,\n# 2., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1., 0., 2.,\n# 4., 4., 5., 5., 3., 4., 4., 2., 2., 2., 3., 3., 4.,\n# 4., 4., 4., 2., 2., 3., 3., 7., 6., 4., 4., 8., 8.,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN],\n# [ 1., np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN],\n# [ 3., 4., 11., 13., 12., 10., 3., 1., 5., 3., 14., 20., 37.,\n# 40., 38., 31., 18., 10., 9., 12., 8., 16., 15., 19., 27., 26.,\n# 30., 23., 18., 15., 13., 25., 28., 25., 27., 15., 8., 11., 13.,\n# 23., 18., 12., 6., np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n# np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN]])\n#\n# window = 1\n# dists = dtw.distance_matrix_fast(s, window=int(0.01 * window * s.shape[1]))\n# print(dists)\n#\n# dists = dtw.distance_matrix(s, window=int(0.01 * window * s.shape[1]))\n# print(dists)\n#\n# wp = dtw.warping_paths(s[0], s[2])\n# print(wp)\n\n\ndef test_negativedimensions2():\n \"\"\"\n For length 62706, the computation (len_cur * (len_cur - 1)) is a number that is too large.\n\n For length 62706 the length calculation for the distance matrix returned 1965958512 but should return 1965989865\n Without parenthesis len_cur * (len_cur - 1) / 2 returns -181493783\n Incorrect behaviour can be simulated using fixedint.Int32(62706)\n Problem is with dividing an uneven number to optimize the computation and require smaller number.\n This dividing the uneven number should and can be avoided.\n \"\"\"\n # s = np.full((62706, 104), 1.0)\n s = np.full((10, 104), 1.0)\n window = 1\n dists = dtw.distance_matrix_fast(s, window=int(0.01 * window * s.shape[1]))\n print(dists)\n\n\nif __name__ == \"__main__\":\n # test_numpymatrix()\n # test_numpymatrix_transpose()\n # test_negativedimensions()\n test_negativedimensions2()\n\n" ]
[ [ "numpy.testing.assert_almost_equal", "numpy.array", "numpy.full" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cl-tohoku/showcase
[ "c3b1e16cb6c9ae0945abadd7c734260e32216983" ]
[ "showcase/convert_word2vec_to_npz.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n入力: word2vecから獲得した単語ベクトルファイル(.txt) & 品詞細分類を含めた全語彙ファイル(1行1vocab)\n出力: 単語ベクトルファイルをnpyファイルにしたもの.全語彙ファイルに登場しないものについては適当に初期化.\n\"\"\"\nimport argparse\nimport os\nfrom itertools import islice\nfrom pathlib import Path\n\nimport numpy as np\n\n\ndef main(args):\n # load vocabulary file\n word_to_index = {l.strip().split('\\t')[0]: int(l.strip().split('\\t')[1]) for l in open(args.vocab, 'r')}\n\n # set word2vec vector to the matrix\n array = np.random.uniform(low=-0.05, high=0.05, size=(len(word_to_index), args.dim))\n with open(args.word2vec, 'r') as fi:\n for line in islice(fi, 1, None):\n fields = line.rstrip().split(' ')\n assert len(fields) == (args.dim + 1)\n\n token = fields[0]\n vec = np.asarray(fields[1::], dtype=np.float32)\n if token in word_to_index:\n array[word_to_index[token]] = vec\n\n # save matrix\n path = Path(args.word2vec)\n dest = str(Path(path.parent, path.stem))\n np.savez_compressed(dest, array)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Convert Word2Vec')\n parser.add_argument('--word2vec', type=os.path.abspath, help='word2vec embedding file (*.txt format)')\n parser.add_argument('--vocab', type=os.path.abspath, help='vocabulary file')\n parser.add_argument('--dim', type=int, help='dimension')\n args = parser.parse_args()\n main(args)\n" ]
[ [ "numpy.asarray", "numpy.savez_compressed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alessandrostranieri/icns_adhd_fmri
[ "10ba36b45b8c805cde8dd1c61a9f1879be39eb8e" ]
[ "display_diagnosis_by_institutes.py" ]
[ "import logging\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom icns import common\nfrom icns.common import DataScope\n\ninstitute_diagnosis = dict()\nfor institute in common.Institute.get_directories():\n phenotype_file_path: str = common.create_phenotype_path(institute, DataScope.TRAIN)\n logging.debug(f'Reading phenotype file {phenotype_file_path}')\n\n phenotype_df: pd.DataFrame = pd.read_csv(phenotype_file_path)\n\n diagnosis_counts: pd.Series = phenotype_df.DX.value_counts()\n diagnosis_counts.sort_index(inplace=True)\n institute_diagnosis[institute] = diagnosis_counts\n\nfig, ax = plt.subplots(figsize=(12, 8))\nfig: plt.Figure = fig\nax: plt.Axes = ax\nwidth = 1.0\ndiagnosis_colors = {0: 'green',\n 1: 'red',\n 2: 'orange',\n 3: 'yellow'}\ndiagnosis_labels = {0: 'Typically Developing Children',\n 1: 'ADHD-Combined',\n 2: 'ADHD-Hyperactive/Impulsive',\n 3: 'ADHD-Inattentive'}\nbar_positions = list()\nlegend_handles = [None] * 4\nfor pos, institute in enumerate(institute_diagnosis.keys()):\n single_institute_diagnosis = institute_diagnosis[institute]\n bar_position = int(pos * 2 * width)\n bar_positions.append(bar_position)\n # TD\n bottom = 0\n for (dx_index, dx_bin) in single_institute_diagnosis.iteritems():\n legend_handles[dx_index] = ax.bar(bar_position, dx_bin, width=width, bottom=bottom,\n color=diagnosis_colors[dx_index],\n label=diagnosis_labels[dx_index])\n bottom += dx_bin\n\nax.set_title('Diagnosis composition by institute')\nax.set_ylabel('Diagnosis sample size')\nax.set_xlabel('Institutes')\nax.set_xticks(bar_positions)\nax.set_xticklabels(common.Institute.get_directories(), rotation=45)\n\nplt.legend(legend_handles, ('Typically Developing Children',\n 'ADHD-Combined',\n 'ADHD-Hyperactive/Impulsive',\n 'ADHD-Inattentive'))\nplt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
derek14/models
[ "ef972951ebae395fcb52877a3b267cf89ffd0642" ]
[ "research/delf/delf/python/training/datasets/googlelandmarks.py" ]
[ "# Lint as: python3\n# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Google Landmarks Dataset(GLD).\n\nPlaceholder for Google Landmarks dataset.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nimport tensorflow as tf\n\n\nclass _GoogleLandmarksInfo(object):\n \"\"\"Metadata about the Google Landmarks dataset.\"\"\"\n num_classes = {'gld_v1': 14951, 'gld_v2': 203094, 'gld_v2_clean': 81313}\n\n\nclass _DataAugmentationParams(object):\n \"\"\"Default parameters for augmentation.\"\"\"\n # The following are used for training.\n min_object_covered = 0.1\n aspect_ratio_range_min = 3. / 4\n aspect_ratio_range_max = 4. / 3\n area_range_min = 0.08\n area_range_max = 1.0\n max_attempts = 100\n update_labels = False\n # 'central_fraction' is used for central crop in inference.\n central_fraction = 0.875\n\n random_reflection = False\n\n\ndef NormalizeImages(images, pixel_value_scale=0.5, pixel_value_offset=0.5):\n \"\"\"Normalize pixel values in image.\n\n Output is computed as\n normalized_images = (images - pixel_value_offset) / pixel_value_scale.\n\n Args:\n images: `Tensor`, images to normalize.\n pixel_value_scale: float, scale.\n pixel_value_offset: float, offset.\n\n Returns:\n normalized_images: `Tensor`, normalized images.\n \"\"\"\n images = tf.cast(images, tf.float32)\n normalized_images = tf.math.divide(\n tf.subtract(images, pixel_value_offset), pixel_value_scale)\n return normalized_images\n\n\ndef _ImageNetCrop(image, image_size):\n \"\"\"Imagenet-style crop with random bbox and aspect ratio.\n\n Args:\n image: a `Tensor`, image to crop.\n image_size: an `int`. The image size for the decoded image, on each side.\n\n Returns:\n cropped_image: `Tensor`, cropped image.\n \"\"\"\n\n params = _DataAugmentationParams()\n bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])\n (bbox_begin, bbox_size, _) = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bbox,\n min_object_covered=params.min_object_covered,\n aspect_ratio_range=(params.aspect_ratio_range_min,\n params.aspect_ratio_range_max),\n area_range=(params.area_range_min, params.area_range_max),\n max_attempts=params.max_attempts,\n use_image_if_no_bounding_boxes=True)\n cropped_image = tf.slice(image, bbox_begin, bbox_size)\n cropped_image.set_shape([None, None, 3])\n\n cropped_image = tf.image.resize(\n cropped_image, [image_size, image_size], method='area')\n if params.random_reflection:\n cropped_image = tf.image.random_flip_left_right(cropped_image)\n\n return cropped_image\n\n\ndef _ParseFunction(example, name_to_features, image_size, augmentation):\n \"\"\"Parse a single TFExample to get the image and label and process the image.\n\n Args:\n example: a `TFExample`.\n name_to_features: a `dict`. The mapping from feature names to its type.\n image_size: an `int`. The image size for the decoded image, on each side.\n augmentation: a `boolean`. True if the image will be augmented.\n\n Returns:\n image: a `Tensor`. The processed image.\n label: a `Tensor`. The ground-truth label.\n \"\"\"\n parsed_example = tf.io.parse_single_example(example, name_to_features)\n # Parse to get image.\n image = parsed_example['image/encoded']\n image = tf.io.decode_jpeg(image)\n image = NormalizeImages(\n image, pixel_value_scale=128.0, pixel_value_offset=128.0)\n if augmentation:\n image = _ImageNetCrop(image, image_size)\n else:\n image = tf.image.resize(image, [image_size, image_size])\n image.set_shape([image_size, image_size, 3])\n # Parse to get label.\n label = parsed_example['image/class/label']\n\n return image, label\n\n\ndef CreateDataset(file_pattern,\n image_size=321,\n batch_size=32,\n augmentation=False,\n seed=0):\n \"\"\"Creates a dataset.\n\n Args:\n file_pattern: str, file pattern of the dataset files.\n image_size: int, image size.\n batch_size: int, batch size.\n augmentation: bool, whether to apply augmentation.\n seed: int, seed for shuffling the dataset.\n\n Returns:\n tf.data.TFRecordDataset.\n \"\"\"\n filenames = tf.data.Dataset.list_files(file_pattern)\n dataset = tf.data.TFRecordDataset(filenames)\n dataset = dataset.repeat().shuffle(buffer_size=100, seed=seed)\n\n # Create a description of the features.\n feature_description = {\n 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n 'image/channels': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'image/id': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'image/filename': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n }\n\n customized_parse_func = functools.partial(\n _ParseFunction,\n name_to_features=feature_description,\n image_size=image_size,\n augmentation=augmentation)\n dataset = dataset.map(customized_parse_func)\n dataset = dataset.batch(batch_size)\n\n return dataset\n\n\ndef GoogleLandmarksInfo():\n \"\"\"Returns metadata information on the Google Landmarks dataset.\n\n Returns:\n object _GoogleLandmarksInfo containing metadata about the GLD dataset.\n \"\"\"\n return _GoogleLandmarksInfo()\n" ]
[ [ "tensorflow.constant", "tensorflow.image.random_flip_left_right", "tensorflow.shape", "tensorflow.slice", "tensorflow.io.decode_jpeg", "tensorflow.data.TFRecordDataset", "tensorflow.cast", "tensorflow.io.parse_single_example", "tensorflow.subtract", "tensorflow.io.FixedLenFeature", "tensorflow.data.Dataset.list_files", "tensorflow.image.resize" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HousedHorse/COMP4906
[ "a2ca3990797342fbf3b51564bc6c0eea686e856f" ]
[ "data/analyze-bpfbench.py" ]
[ "#! /usr/bin/env python3\n\nimport os, sys\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-b', '--base', type=str, nargs='+', required=1, help='base data')\nparser.add_argument('-e', '--ebph', type=str, nargs='+', required=1, help='ebpH data')\nparser.add_argument('-o', '--out', type=str, help='Path to output table')\nparser.add_argument('-f', '--figs', type=str, help='Output figs as ...-<figs>.png')\nparser.add_argument('--noavg', action='store_true', help='Do not average times')\nargs = parser.parse_args(sys.argv[1:])\n\npd.options.display.float_format = '{:.2f}'.format\nsns.set()\n\ndef read_benchmarks(*files):\n \"\"\"\n Read benchmarking data from ss files and return a series of data frames.\n \"\"\"\n data = []\n for f in files:\n df = pd.read_csv(f, sep=r'\\s+', skiprows=5, error_bad_lines=0, header=None)\n df= df.iloc[:, :3]\n df.columns = ['syscall', 'count', 'time']\n data.append(df)\n return data\n\ndef merge_frames(*data):\n \"\"\"\n Merge many frames together. Should not be called on \"averaged\" data.\n \"\"\"\n result = pd.concat(*data).groupby(['syscall'], as_index=False)[[\"count\", \"time\"]].sum()\n return result\n\ndef average_times(data):\n \"\"\"\n Convert time to average time.\n \"\"\"\n # Calculate average times\n data.loc[:, 'time'] = data.loc[:, 'time'] / data.loc[:, 'count']\n\ndef std_times(data):\n # Calculate standard deviations\n std = data['time'].std()\n mean = data['time'].mean()\n data['stdev'] = np.abs(data['time'] - mean) / (std if not np.isnan(std) else 1)\n return data\n\ndef std_overhead(data):\n std = data['overhead'].std()\n mean = data['overhead'].mean()\n data['stdev_overhead'] = np.abs(data['overhead'] - mean) / (std if not np.isnan(std) else 1)\n return data\n\ndef calculate(base, ebph):\n \"\"\"\n Join tables and calculate values.\n \"\"\"\n data = pd.merge(base, ebph, on=['syscall'], suffixes=('_base', '_ebph'))\n # Overhead\n data.loc[:, 'overhead'] = (data[:]['time_ebph'] - data[:]['time_base']) / data[:]['time_base'] * 100\n # Total count\n data.loc[:, 'total_count'] = data[:]['count_ebph'] + data[:]['count_base']\n # Percent of data points\n data.loc[:, 'percent_data'] = data[:]['total_count'] / sum(data[:]['total_count']) * 100\n return data\n\ndef strip_outliers(data):\n data = data[(data['stdev_base'] < 3) & (data['stdev_ebph'] < 3 & (data['stdev_overhead'] < 3))]\n return data\n\ndef sort_and_filter(data, top=20, sort='total_count'):\n # Sort and slice data\n data = data.sort_values(sort, ascending=0)\n data = data[:top]\n return data\n\ndef plot_times(data, suffix=''):\n data['key'] = data['time_base'] + data['time_ebph']\n data = data.sort_values('key')\n data = data[['syscall', 'time_base', 'time_ebph']]\n errors = data.sem()\n plot = data.plot(yerr={'time_base': errors['time_base'],'time_ebph': errors['time_ebph']},\n y=['time_base', 'time_ebph'],\n x='syscall',\n kind='bar',\n capsize=2)\n plot.set_xlabel(\"System Call\")\n plot.set_ylabel(\"Time ($\\mu$s)\")\n plot.legend(['Base', 'ebpH'])\n plot.get_figure().savefig('times-' + suffix + '.png', bbox_inches='tight', dpi=200)\n\ndef plot_overheads(data, suffix=''):\n data = data.sort_values('overhead')\n data = data[['syscall', 'overhead']]\n errors = data.sem()\n plot = data.plot(yerr={'overhead': errors['overhead']},\n y='overhead',\n x='syscall',\n kind='bar',\n capsize=2)\n plot.set_xlabel(\"System Call\")\n plot.set_ylabel(\"Overhead (%)\")\n plot.legend().remove()\n plot.get_figure().savefig('overheads-' + suffix + '.png', bbox_inches='tight', dpi=200)\n\ndef export_table(data, path):\n \"\"\"\n Export final table as LaTeX table.\n \"\"\"\n # Keep columns we care about\n data['time_base'] = data['time_base'].map('{:.3f}'.format) + ' ' + data['stdev_base'].map('({:.4f})'.format)\n data['time_ebph'] = data['time_ebph'].map('{:.3f}'.format) + ' ' + data['stdev_ebph'].map('({:.4f})'.format)\n data['overhead'] = data['overhead'].map('{:.3f}'.format) + ' ' + data['stdev_overhead'].map('({:.4f})'.format)\n data = data[['syscall', 'time_base', 'time_ebph', 'overhead']]\n # Export table, after renaming columns\n if args.out:\n data[:]['syscall'] = data[:]['syscall'].str.replace('_', r'\\_')\n data = data.rename(columns={\n 'syscall':r'\\multicolumn{1}{l}{System Call}',\n 'time_base':r'$T_{\\text{base}}$ ($\\mu$s)',\n 'time_ebph':r'$T_{\\text{ebpH}}$ ($\\mu$s)',\n 'overhead':r'\\% Overhead'})\n data.to_latex(index=0, escape=0, buf=path, column_format=r'>{\\ttfamily}lrrrr')\n else:\n print(data)\n\nif __name__ == '__main__':\n base = merge_frames(read_benchmarks(*args.base))\n ebph = merge_frames(read_benchmarks(*args.ebph))\n\n if not args.noavg:\n average_times(base)\n average_times(ebph)\n\n base = std_times(base)\n ebph = std_times(ebph)\n\n data = calculate(base, ebph)\n data = std_overhead(data)\n data = strip_outliers(data)\n\n # Custom filtration\n #data = data[data['time_base'] < 7]\n\n data = sort_and_filter(data, top=400)\n\n if args.figs:\n plot_times(data, args.figs)\n plot_overheads(data, args.figs)\n\n export_table(data, args.out)\n\n" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.concat", "numpy.abs", "numpy.isnan" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
SafronovNikita/hough-plane-python
[ "abdd3e941d44ec758c202116c97dd13f0830c3cd" ]
[ "vizualization.py" ]
[ "import numpy as np\nimport math\nfrom plotly.offline import iplot\nfrom plotly import graph_objs as go\n\ndef _show_data(data, show_zero=True, is_hough_space=False):\n if show_zero:\n data.append(\n go.Scatter3d(\n x=[0],\n y=[0],\n z=[0],\n mode='markers',\n marker=dict(\n size=10,\n color=(255, 180, 60)\n )\n )\n )\n\n fig = go.Figure(data=data)\n fig.update_layout(\n margin=dict(l=20, r=20, t=20, b=20),\n height=400,\n paper_bgcolor=\"LightSteelBlue\",\n )\n if is_hough_space:\n fig.update_layout(\n scene=go.Scene(\n xaxis=go.XAxis(title='φ'),\n yaxis=go.YAxis(title='θ'),\n zaxis=go.ZAxis(title='d')\n )\n )\n\n iplot(fig)\n\ndef show_points(points, is_hough_space=False):\n '''Shows points with or without color'''\n\n l,d = points.shape\n marker = {\n 'size':1\n }\n if d == 4:\n marker['color'] = points[:, 3]\n marker['colorbar'] = dict(thickness=50)\n\n data = [\n go.Scatter3d(\n x=points[:, 0],\n y=points[:, 1],\n z=points[:, 2],\n mode='markers',\n marker=marker,\n )\n ]\n _show_data(data, is_hough_space=is_hough_space)\n\ndef _make_points2(points1, points2):\n '''Make data for two types of points'''\n\n data = [\n go.Scatter3d(\n x=points1[:, 0],\n y=points1[:, 1],\n z=points1[:, 2],\n mode='markers',\n marker=dict(\n size=1,\n )\n ),\n go.Scatter3d(\n x=points2[:, 0],\n y=points2[:, 1],\n z=points2[:, 2],\n mode='markers',\n marker=dict(\n size=5,\n )\n ),\n ]\n return data\n\ndef show_points_and_plane_vectors(points, plane_vectors):\n data = _make_points2(points, plane_vectors)\n _show_data(data)\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef vec_norm(vec):\n x, y, z = vec\n vec_len = (x ** 2 + y ** 2 + z ** 2) ** 0.5\n return vec / vec_len\n\ndef vec_len(vec):\n x,y,z = vec\n len_ = (x**2 + y**2 + z**2)**0.5\n return len_\n\ndef get_cos(vec1, vec2):\n x, y, z = vec1\n xx, yy, zz = vec2\n dot = x * xx + y * yy + z * zz\n\n len1 = (x ** 2 + y ** 2 + z ** 2) ** 0.5\n len2 = (xx ** 2 + yy ** 2 + zz ** 2) ** 0.5\n\n cos = dot / (len1 * len2 + 1e-6)\n\n return cos\n\ndef get_plane_polygon_from_vector(vector, radius, steps=20):\n orts = np.array([\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n ], dtype=np.float)\n\n for ort in orts:\n cos = abs(get_cos(ort, vector))\n if cos < 0.1:\n continue\n\n vector1 = np.cross(ort, vector)\n vector2 = np.cross(vector, vector1)\n break\n\n vector1_norm = vec_norm(vector1)\n vector2_norm = vec_norm(vector2)\n\n vectors_out = []\n for i in range(steps):\n direction = np.pi * 2 / steps * i\n vector_out = vector + \\\n math.cos(direction) * vector1_norm * radius + \\\n math.sin(direction) * vector2_norm * radius\n vectors_out.append(vector_out)\n vectors_out.append(vectors_out[0])\n vectors_out = np.array(vectors_out)\n\n return vectors_out\n\ndef visualize_plane(points, vectors):\n data = _make_points2(points, vectors)\n\n for vec in vectors:\n vec_len_ = vec_len(vec)\n for radius in [vec_len_ / 2, vec_len_, vec_len_ * 1.5]:\n poly = get_plane_polygon_from_vector(vec[:3], radius)\n data.append(\n go.Scatter3d(\n x=poly[:,0],\n y=poly[:,1],\n z=poly[:,2],\n mode='lines',\n ),\n )\n\n _show_data(data)" ]
[ [ "numpy.array", "numpy.cross" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
evanphilip/vedo
[ "e8504fb1a7d2cb667a776180d69bb17cad634e1e" ]
[ "examples/pyplot/earthquake_browser.py" ]
[ "\"\"\"Browse earthquakes of magnitude 2.5+ in the past 30 days\"\"\"\nimport pandas, numpy as np\nfrom vedo import *\n\nnum = 50 # nr of earthquakes to be visualized in the time window\n\nprintc(\"..downloading USGS data.. please wait..\", invert=True)\npath = download(\"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.csv\")\nusecols = ['time','place','latitude','longitude','depth','mag']\ndata = pandas.read_csv(path, usecols=usecols)[usecols][::-1].reset_index(drop=True) # reverse list\n\npic = Picture(\"https://eoimages.gsfc.nasa.gov/images/imagerecords/147000/147190/eo_base_2020_clean_3600x1800.png\")\nemag = Picture('https://www.dropbox.com/s/ynp7kts2lhf32cb/earthq_mag_e.jpg').scale(0.4).pos(1400,10,1)\npicscale = [pic.shape[0]/2, pic.shape[1]/2, 1]\n\ndef GeoCircle(lat, lon, r, res=50):\n coords = []\n for phi in np.linspace(0, 2*np.pi, num=res, endpoint=False):\n clat = np.arcsin(sin(lat) * cos(r) + cos(lat) * sin(r) * cos(phi))\n clng = lon + np.arctan2(sin(phi) * sin(r) * cos(lat), cos(r) - sin(lat) * sin(clat))\n coords.append([clng/np.pi + 1, clat*2/np.pi + 1, 0])\n return Polygon(nsides=res).points(coords) # reset polygon points\n\n\ncenters = []\npb = ProgressBar(0, len(data))\nfor i, d in data.iterrows():\n pb.print(\"Parsing USGS data..\")\n M = d['mag'] # earthquake estimated magnitude\n E = sqrt(exp(5.24+1.44*M) * picscale[0])/10000 # empirical formula for sqrt(energy_release(M))\n rgb = colorMap(E, name='Reds', vmin=0, vmax=7) # map energy to color\n lat, long = np.deg2rad(d['latitude']), np.deg2rad(d['longitude'])\n ce = GeoCircle(lat, long, E/50).scale(picscale).z(num/M).c(rgb).lw(0.1).useBounds(False)\n ce.time = i\n ce.info = '\\n'.join(str(d).split('\\n')[:-1]) # remove of the last line in string d\n #if M > 6.5: ce.alpha(0.8) # make the big ones slightly transparent\n if i < len(data)-num: ce.off() # switch off older ones: make circles invisible\n centers.append(ce)\n\n\ndef sliderfunc(widget, event):\n value = widget.GetRepresentation().GetValue() # get the slider current value\n widget.GetRepresentation().SetTitleText(f\"{data['time'][int(value)][:10]}\")\n for ce in centers:\n isinside = abs(value-ce.time) < num # switch on if inside of time window\n ce.on() if isinside else ce.off()\n plt.render()\n\nplt = Plotter(size=(2200,1100), title=__doc__)\nplt.addSlider2D(sliderfunc, 0, len(centers)-1, value=len(centers)-1, showValue=False, title=\"today\")\nplt.addHoverLegend(useInfo=True, alpha=1, c='w', bg='red2', s=1)\ncomment = Text2D(\"Areas are proportional to energy release\\n[hover mouse to get more info]\", bg='g9', alpha=.7)\nplt.show(pic.pickable(False), emag.pickable(False), centers, comment, zoom=2.27).close()\n" ]
[ [ "numpy.deg2rad", "pandas.read_csv", "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]