repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
HTDPNJ/Sentiment-Classification-Via-Galvanic-Skin-Response-Based-on-Deep-Learning-Models
|
[
"bcb9cdb84bd4d2f73c19d781139d060b1d433171"
] |
[
"Src/Pidian_select_average_tezheng_2_aftfft_getlastdata.py"
] |
[
"###从皮电每几个数值求了均值后,获取每个用户对应视频num的数据\nimport csv\nimport pandas as pd\nimport numpy as np\ndef get_last_sec_data(source_path,dis_path,num): ##源文件路径,目标文件路径,num表示最后几秒的数据/若num表示-1取得则是所有时间数据\n name_testtime_Filmname_list=[]\n csvfile = open(source_path, newline='') # 打开文件\n csvReader = csv.reader(csvfile) # 返回的可迭代类型\n data = [] # 用于存储该文件里的整个数据\n for content in csvReader:\n data.append(content)\n csvfile.close() # 关闭文件\n # 存储文件\n csvFile = open(dis_path, 'a+', newline='') # 创建被写入文件名,,否则会有多余空格,创建新文件用于写入处理后的数据\n csvWriter = csv.writer(csvFile)\n csvWriter.writerow(('INFO', 'Sex', 'Dawu',\"QINGGAN\",\"PD\"))\n for i in range(1, len(data)): # 获取姓名、测试次数、刺激视频姓名\n if(int (data[i][9])!=1): #把过渡视频去掉\n subname_list = []\n subname_list.append(data[i][0])\n subname_list.append(data[i][6])\n subname_list.append(data[i][10])\n if subname_list not in name_testtime_Filmname_list:\n name_testtime_Filmname_list.append(subname_list)\n df = pd.read_csv(source_path) # df是导入整个表数据\n for i in range(0, len(name_testtime_Filmname_list)):\n SAVE_LIST=[]\n relax = df[df.Person_name == name_testtime_Filmname_list[i][0]] # 进行筛选控制 and df.Test_time== 2 and df.Has_blank==1\n relax = relax[relax.Test_time == int(name_testtime_Filmname_list[i][1])]\n relax = relax[relax.Set_id == name_testtime_Filmname_list[i][2]]\n relax = relax[relax.Film_name == name_testtime_Filmname_list[i][4]]\n print(pd_all_average[0])\n print(type(pd_all_average[0]))\n\n\n dawu=relax.Dawu.tolist() #存储该条数据对应的大五人格\n qinggan=relax.QINGGAN.tolist() #存储该条对应的情感评分\n sex=relax.Sex.tolist() #性别\n SAVE_LIST.append(name_testtime_Filmname_list[i])\n if(len(sex)>0):\n SAVE_LIST.append(sex[0])\n if(len(dawu)>0):\n SAVE_LIST.append(dawu[0])\n if (len(qinggan) > 0):\n SAVE_LIST.append(qinggan[0])\n SAVE_LIST.append(save_pd)\n csvWriter.writerow(SAVE_LIST)\n"
] |
[
[
"pandas.read_csv"
]
] |
kanelouise/python-projects
|
[
"abbce0df88719140e25232d06539155e0466189b"
] |
[
"la.py"
] |
[
"import pandas as pd\nimport lxml\nfrom datetime import date\n\ntoday = date.today()\n\n#create dataframe of polling locations from LA County website\nla = pd.read_html(\"https://locator.lavote.net/locations-list/vc?id=4085\")[0]\n\n#output dataframe to CSV and save it with today's date so we have a record of when/how polling locations changed\nla = la.to_csv(\"la_county_pls_{0}.csv\".format(today))\n"
] |
[
[
"pandas.read_html"
]
] |
watersnaily/RGB-D-3D-object-detection-based-real-time-monitoring-system-in-an-agile-production-environment
|
[
"49b2b8f97df36bb2057a5f7032ce12c7920c08b4"
] |
[
"object_detector_cpu/src/train/svm_classifier/svm_predict.py"
] |
[
"import cv2\nimport numpy as np\nimport os\n\nclass svm_predictor():\n\n def __init__ (self,svm_load_path,bow_load_path,bow_threshold):\n self.svm = cv2.ml.SVM_load(svm_load_path) \n self.surf = cv2.xfeatures2d.SURF_create(bow_threshold)\n self.bow_extractor = cv2.BOWImgDescriptorExtractor(self.surf, cv2.BFMatcher(cv2.NORM_L2))\n self.load_bow(bow_load_path)\n\n def load_bow(self,load_path):\n vocabulary = np.load(load_path)\n self.bow_extractor.setVocabulary(vocabulary)\n\n def predict(self,image_path):\n img = cv2.imread(image_path)\n gray=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n key_points = self.surf.detect(gray,None)\n feature = self.bow_extractor.compute(gray, key_points)[0]\n feature = np.float32(feature)\n feature = feature.reshape(1,-1)\n _,label = self.svm.predict(feature)\n\n return label\n\nif __name__ == '__main__':\n\n bow_load_path = \"../../weights/bow_vocabulary.npy\"\n svm_load_path = \"../../weights/svm_classifier.mat\"\n bow_threshold = 500\n predictor = svm_predictor(svm_load_path,bow_load_path,bow_threshold)\n while True:\n image_name = raw_input(\"image_name:\")\n image_path = \"/home/he/Kit/Masterarbeit/3D_Mapping_ws/src/object_detector/photos/rgb/1/capture_corlor\"+image_name+\".png\"\n label = predictor.predict(image_path)\n print (label)\n print ('the label is %d'%label)\n # pos_path = \"/home/he/Kit/Masterarbeit/3D_Mapping_ws/src/object_detector/photos/rgb/1\"\n # neg_path = \"/home/he/Kit/Masterarbeit/3D_Mapping_ws/src/object_detector/photos/rgb/0\"\n # pos_image = os.listdir(pos_path)\n # neg_image = os.listdir(neg_path)\n # total = 0\n # c = 0\n # for image_name in pos_image:\n # image_path = pos_path + \"/\" + image_name\n # label = predictor.predict(image_path)\n # total += 1\n # if label[0,0] == 1:\n # c += 1\n # else:\n # print ('rgb/1/%s'%image_name)\n # for image_name in neg_image:\n # image_path = neg_path + \"/\" + image_name\n # label = predictor.predict(image_path)\n # total += 1\n # if label[0,0] == 0:\n # c += 1\n # else:\n # print ('rgb/0/%s'%image_name)\n # print (total)\n # print (c)\n # print (float(c)/total)\n"
] |
[
[
"numpy.load",
"numpy.float32"
]
] |
ChuinHongYap/permutation-python
|
[
"51efa0d23a086a1520d77f6ed095be10cd7e182e"
] |
[
"permutation_combination/combination.py"
] |
[
"import numpy as np\nimport math\n\n'''\nDifferent combination methods using python\n'''\n\n# Using raw mathematics\ndef comb(n, r):\n num = denom_a = denom_b= 1\n \n # n!\n if n >= 1:\n for i in range (1,n+1):\n num=num*i\n\n if r < n:\n # r!\n for i in range (1,r+1):\n denom_a=denom_a*i\n \n # (n-r)!\n for i in range (1,n-r+1):\n denom_b=denom_b*i\n \n return num/(denom_a*denom_b)\n\n# Using factorial \ndef comb_fact(n, r):\n return math.factorial(n)/(math.factorial(r)*math.factorial(n-r))\n\n# Using Stirling Approximation\ndef comb_stir(n,r):\n def stirling(n):\n return math.sqrt(2*math.pi*n)*(n/math.e)**n\n return stirling(n)/(stirling(r)*stirling(n-r))\n\n# Using list\ndef comb_list(n, r):\n num_list = []\n denom_a = 1\n denom_list = []\n\n if n >= 1:\n for i in range (1,n+1):\n num_list.append(i)\n\n if r < n:\n for i in range (1,r+1):\n denom_a=denom_a*i\n \n for i in range (1,n-r+1):\n denom_list.append(i)\n\n # or just use math.factorial\n # denom_a = math.factorial(r)\n\n new_num = [x for x in num_list if x not in denom_list]\n\n return np.prod(new_num)/denom_a\n\n# Using list (shortened)\ndef comb_list_v2(n, r):\n num_list = []\n denom_a = 1\n denom_list = []\n\n if r < n:\n for i in range (1,r+1):\n denom_a=denom_a*i\n\n if n >= 1:\n for i in range (n-r+1,n+1):\n num_list.append(i)\n\n # or just use math.factorial\n # denom_a = math.factorial(r)\n\n return np.prod(num_list)/denom_a"
] |
[
[
"numpy.prod"
]
] |
djain454/Show-Attend-and-Tell-Neural-Image-Caption-Generation-with-Visual-Attention
|
[
"c6619fdb748a8cbb4bb7daba1af87e5c17a06d8e"
] |
[
"generate_caption.py"
] |
[
"\"\"\"\nWe use the same strategy as the author to display visualizations\nas in the examples shown in the paper. The strategy used is adapted for\nPyTorch from here:\nhttps://github.com/kelvinxu/arctic-captions/blob/master/alpha_visualization.ipynb\n\"\"\"\n\nimport argparse, json, os\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport skimage\nimport skimage.transform\nimport torch\nimport torchvision.transforms as transforms\nfrom math import ceil\nfrom PIL import Image\n\nfrom dataset import pil_loader\nfrom decoder import Decoder\nfrom encoder import Encoder\nfrom train import data_transforms\n\n\ndef generate_caption_visualization(encoder, decoder, img_path, word_dict, beam_size=10, smooth=True):\n img = pil_loader(img_path)\n img = data_transforms(img)\n img = torch.FloatTensor(img)\n img = img.unsqueeze(0)\n\n img_features = encoder(img)\n img_features = img_features.expand(beam_size, img_features.size(1), img_features.size(2))\n print(img_features)\n sentence, alpha = decoder.caption(img_features, beam_size)\n\n token_dict = {idx: word for word, idx in word_dict.items()}\n sentence_tokens = []\n for word_idx in sentence:\n sentence_tokens.append(token_dict[word_idx])\n if word_idx == word_dict['<eos>']:\n break\n\n img = Image.open(img_path)\n w, h = img.size\n if w > h:\n w = w * 256 / h\n h = 256\n else:\n h = h * 256 / w\n w = 256\n left = (w - 224) / 2\n top = (h - 224) / 2\n resized_img = img.resize((int(w), int(h)), Image.BICUBIC).crop((left, top, left + 224, top + 224))\n img = np.array(resized_img.convert('RGB').getdata()).reshape(224, 224, 3)\n img = img.astype('float32') / 255\n\n num_words = len(sentence_tokens)\n w = np.round(np.sqrt(num_words))\n h = np.ceil(np.float32(num_words) / w)\n alpha = torch.tensor(alpha)\n\n plot_height = ceil((num_words + 3) / 4.0)\n ax1 = plt.subplot(4, plot_height, 1)\n plt.imshow(img)\n plt.axis('off')\n for idx in range(num_words):\n ax2 = plt.subplot(4, plot_height, idx + 2)\n label = sentence_tokens[idx]\n plt.text(0, 1, label, backgroundcolor='white', fontsize=13)\n plt.text(0, 1, label, color='black', fontsize=13)\n plt.imshow(img)\n\n if encoder.network == 'vgg19':\n shape_size = 14\n else:\n shape_size = 7\n\n if smooth:\n alpha_img = skimage.transform.pyramid_expand(alpha[idx, :].reshape(shape_size, shape_size), upscale=16, sigma=20)\n else:\n alpha_img = skimage.transform.resize(alpha[idx, :].reshape(shape_size,shape_size), [img.shape[0], img.shape[1]])\n plt.imshow(alpha_img, alpha=0.8)\n plt.set_cmap(cm.Greys_r)\n plt.axis('off')\n plt.show()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Show, Attend and Tell Caption Generator')\n parser.add_argument('--img-path', type=str, help='path to image')\n parser.add_argument('--network', choices=['vgg19', 'resnet152'], default='vgg19',\n help='Network to use in the encoder (default: vgg19)')\n parser.add_argument('--model', type=str, help='path to model paramters')\n parser.add_argument('--data-path', type=str, default='dataset',\n help='path to data (default: dataset)')\n args = parser.parse_args()\n\n word_dict = json.load(open(args.data_path + '/word_dict.json', 'r'))\n vocabulary_size = len(word_dict)\n\n encoder = Encoder(network=args.network)\n decoder = Decoder(vocabulary_size, encoder.dim)\n\n decoder.load_state_dict(torch.load(args.model))\n\n # encoder.cuda()\n # decoder.cuda()\n\n encoder.eval()\n decoder.eval()\n\n generate_caption_visualization(encoder, decoder, args.img_path, word_dict)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.sqrt",
"torch.load",
"torch.tensor",
"matplotlib.pyplot.set_cmap",
"matplotlib.pyplot.subplot",
"torch.FloatTensor",
"numpy.float32",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.text",
"matplotlib.pyplot.show"
]
] |
jinamshah/xlnet
|
[
"67084a2a1d2a6ca0232b320c582e18072fd2ea05"
] |
[
"xlnet.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport tensorflow as tf\nimport modeling\n\n\ndef _get_initializer(FLAGS):\n\t\"\"\"Get variable intializer.\"\"\"\n\tif FLAGS.init == \"uniform\":\n\t\tinitializer = tf.initializers.random_uniform(\n\t\t\tminval=-FLAGS.init_range,\n\t\t\tmaxval=FLAGS.init_range,\n\t\t\tseed=None)\n\telif FLAGS.init == \"normal\":\n\t\tinitializer = tf.initializers.random_normal(\n\t\t\tstddev=FLAGS.init_std,\n\t\t\tseed=None)\n\telse:\n\t\traise ValueError(\"Initializer {} not supported\".format(FLAGS.init))\n\treturn initializer\n\n\nclass XLNetConfig(object):\n\t\"\"\"XLNetConfig contains hyperparameters that are specific to a model checkpoint;\n\ti.e., these hyperparameters should be the same between\n\tpretraining and finetuning.\n \n\tThe following hyperparameters are defined:\n\t n_layer: int, the number of layers.\n\t d_model: int, the hidden size.\n\t n_head: int, the number of attention heads.\n\t d_head: int, the dimension size of each attention head.\n\t d_inner: int, the hidden size in feed-forward layers.\n\t ff_activation: str, \"relu\" or \"gelu\".\n\t untie_r: bool, whether to untie the biases in attention.\n\t n_token: int, the vocab size.\n\t\"\"\"\n\n\tdef __init__(self, FLAGS=None, json_path=None):\n\t\t\"\"\"Constructing an XLNetConfig.\n\t\tOne of FLAGS or json_path should be provided.\"\"\"\n\n\t\tassert FLAGS is not None or json_path is not None\n\n\t\tself.keys = [\"n_layer\", \"d_model\", \"n_head\", \"d_head\", \"d_inner\",\n\t\t\t\t\t \"ff_activation\", \"untie_r\", \"n_token\"]\n\n\t\tif FLAGS is not None:\n\t\t\tself.init_from_flags(FLAGS)\n\n\t\tif json_path is not None:\n\t\t\tself.init_from_json(json_path)\n\n\tdef init_from_flags(self, FLAGS):\n\t\tfor key in self.keys:\n\t\t\tsetattr(self, key, getattr(FLAGS, key))\n\n\tdef init_from_json(self, json_path):\n\t\twith tf.gfile.Open(json_path) as f:\n\t\t\tjson_data = json.load(f)\n\t\t\tfor key in self.keys:\n\t\t\t\tsetattr(self, key, json_data[key])\n\n\tdef to_json(self, json_path):\n\t\t\"\"\"Save XLNetConfig to a json file.\"\"\"\n\t\tjson_data = {}\n\t\tfor key in self.keys:\n\t\t\tjson_data[key] = getattr(self, key)\n\n\t\tjson_dir = os.path.dirname(json_path)\n\t\tif not tf.gfile.Exists(json_dir):\n\t\t\ttf.gfile.MakeDirs(json_dir)\n\t\twith tf.gfile.Open(json_path, \"w\") as f:\n\t\t\tjson.dump(json_data, f, indent=4, sort_keys=True)\n\n\ndef create_run_config(is_training, is_finetune, FLAGS):\n\tkwargs = dict(\n\t\tis_training=is_training,\n\t\tuse_tpu=FLAGS.use_tpu,\n\t\tuse_bfloat16=FLAGS.use_bfloat16,\n\t\tdropout=FLAGS.dropout,\n\t\tdropatt=FLAGS.dropatt,\n\t\tinit=FLAGS.init,\n\t\tinit_range=FLAGS.init_range,\n\t\tinit_std=FLAGS.init_std,\n\t\tclamp_len=FLAGS.clamp_len)\n\n\tif not is_finetune:\n\t\tkwargs.update(dict(\n\t\t\tmem_len=FLAGS.mem_len,\n\t\t\treuse_len=FLAGS.reuse_len,\n\t\t\tbi_data=FLAGS.bi_data,\n\t\t\tclamp_len=FLAGS.clamp_len,\n\t\t\tsame_length=FLAGS.same_length))\n\n\treturn RunConfig(**kwargs)\n\n\nclass RunConfig(object):\n\t\"\"\"RunConfig contains hyperparameters that could be different\n\tbetween pretraining and finetuning.\n\tThese hyperparameters can also be changed from run to run.\n\tWe store them separately from XLNetConfig for flexibility.\n\t\"\"\"\n\n\tdef __init__(self, is_training, use_tpu, use_bfloat16, dropout, dropatt,\n\t\t\t\t init=\"normal\", init_range=0.1, init_std=0.02, mem_len=None,\n\t\t\t\t reuse_len=None, bi_data=False, clamp_len=-1, same_length=False):\n\t\t\"\"\"\n\t\tArgs:\n\t\t is_training: bool, whether in training mode.\n\t\t use_tpu: bool, whether TPUs are used.\n\t\t use_bfloat16: bool, use bfloat16 instead of float32.\n\t\t dropout: float, dropout rate.\n\t\t dropatt: float, dropout rate on attention probabilities.\n\t\t init: str, the initialization scheme, either \"normal\" or \"uniform\".\n\t\t init_range: float, initialize the parameters with a uniform distribution\n\t\t\tin [-init_range, init_range]. Only effective when init=\"uniform\".\n\t\t init_std: float, initialize the parameters with a normal distribution\n\t\t\twith mean 0 and stddev init_std. Only effective when init=\"normal\".\n\t\t mem_len: int, the number of tokens to cache.\n\t\t reuse_len: int, the number of tokens in the currect batch to be cached\n\t\t\tand reused in the future.\n\t\t bi_data: bool, whether to use bidirectional input pipeline.\n\t\t\tUsually set to True during pretraining and False during finetuning.\n\t\t clamp_len: int, clamp all relative distances larger than clamp_len.\n\t\t\t-1 means no clamping.\n\t\t same_length: bool, whether to use the same attention length for each token.\n\t\t\"\"\"\n\n\t\tself.init = init\n\t\tself.init_range = init_range\n\t\tself.init_std = init_std\n\t\tself.is_training = is_training\n\t\tself.dropout = dropout\n\t\tself.dropatt = dropatt\n\t\tself.use_tpu = use_tpu\n\t\tself.use_bfloat16 = use_bfloat16\n\t\tself.mem_len = mem_len\n\t\tself.reuse_len = reuse_len\n\t\tself.bi_data = bi_data\n\t\tself.clamp_len = clamp_len\n\t\tself.same_length = same_length\n\n\nclass XLNetModel(object):\n\t\"\"\"A wrapper of the XLNet model used during both pretraining and finetuning.\"\"\"\n\n\tdef __init__(self, xlnet_config, run_config, input_ids, seg_ids, input_mask,\n\t\t\t\t mems=None, perm_mask=None, target_mapping=None, inp_q=None,\n\t\t\t\t **kwargs):\n\t\t\"\"\"\n\t\tArgs:\n\t\t xlnet_config: XLNetConfig,\n\t\t run_config: RunConfig,\n\t\t input_ids: int32 Tensor in shape [len, bsz], the input token IDs.\n\t\t seg_ids: int32 Tensor in shape [len, bsz], the input segment IDs.\n\t\t input_mask: float32 Tensor in shape [len, bsz], the input mask.\n\t\t\t0 for real tokens and 1 for padding.\n\t\t mems: a list of float32 Tensors in shape [mem_len, bsz, d_model], memory\n\t\t\tfrom previous batches. The length of the list equals n_layer.\n\t\t\tIf None, no memory is used.\n\t\t perm_mask: float32 Tensor in shape [len, len, bsz].\n\t\t\tIf perm_mask[i, j, k] = 0, i attend to j in batch k;\n\t\t\tif perm_mask[i, j, k] = 1, i does not attend to j in batch k.\n\t\t\tIf None, each position attends to all the others.\n\t\t target_mapping: float32 Tensor in shape [num_predict, len, bsz].\n\t\t\tIf target_mapping[i, j, k] = 1, the i-th predict in batch k is\n\t\t\ton the j-th token.\n\t\t\tOnly used during pretraining for partial prediction.\n\t\t\tSet to None during finetuning.\n\t\t inp_q: float32 Tensor in shape [len, bsz].\n\t\t\t1 for tokens with losses and 0 for tokens without losses.\n\t\t\tOnly used during pretraining for two-stream attention.\n\t\t\tSet to None during finetuning.\n\t\t\"\"\"\n\n\t\tinitializer = _get_initializer(run_config)\n\n\t\ttfm_args = dict(\n\t\t\tn_token=xlnet_config.n_token,\n\t\t\tinitializer=initializer,\n\t\t\tattn_type=\"bi\",\n\t\t\tn_layer=xlnet_config.n_layer,\n\t\t\td_model=xlnet_config.d_model,\n\t\t\tn_head=xlnet_config.n_head,\n\t\t\td_head=xlnet_config.d_head,\n\t\t\td_inner=xlnet_config.d_inner,\n\t\t\tff_activation=xlnet_config.ff_activation,\n\t\t\tuntie_r=xlnet_config.untie_r,\n\n\t\t\tis_training=run_config.is_training,\n\t\t\tuse_bfloat16=run_config.use_bfloat16,\n\t\t\tuse_tpu=run_config.use_tpu,\n\t\t\tdropout=run_config.dropout,\n\t\t\tdropatt=run_config.dropatt,\n\n\t\t\tmem_len=run_config.mem_len,\n\t\t\treuse_len=run_config.reuse_len,\n\t\t\tbi_data=run_config.bi_data,\n\t\t\tclamp_len=run_config.clamp_len,\n\t\t\tsame_length=run_config.same_length\n\t\t)\n\n\t\tinput_args = dict(\n\t\t\tinp_k=input_ids,\n\t\t\tseg_id=seg_ids,\n\t\t\tinput_mask=input_mask,\n\t\t\tmems=mems,\n\t\t\tperm_mask=perm_mask,\n\t\t\ttarget_mapping=target_mapping,\n\t\t\tinp_q=inp_q)\n\t\ttfm_args.update(input_args)\n\n\t\twith tf.variable_scope(\"model\", reuse=tf.AUTO_REUSE):\n\t\t\t(self.output, self.new_mems, self.lookup_table\n\t\t\t ) = modeling.transformer_xl(**tfm_args)\n\n\t\tself.input_mask = input_mask\n\t\tself.initializer = initializer\n\t\tself.xlnet_config = xlnet_config\n\t\tself.run_config = run_config\n\n\tdef get_pooled_out(self, summary_type, use_summ_proj=True):\n\t\t\"\"\"\n\t\tArgs:\n\t\t summary_type: str, \"last\", \"first\", \"mean\", or \"attn\". The method\n\t\t\tto pool the input to get a vector representation.\n\t\t use_summ_proj: bool, whether to use a linear projection during pooling.\n\t\n\t\tReturns:\n\t\t float32 Tensor in shape [bsz, d_model], the pooled representation.\n\t\t\"\"\"\n\n\t\txlnet_config = self.xlnet_config\n\t\trun_config = self.run_config\n\n\t\twith tf.variable_scope(\"model\", reuse=tf.AUTO_REUSE):\n\t\t\tsummary = modeling.summarize_sequence(\n\t\t\t\tsummary_type=summary_type,\n\t\t\t\thidden=self.output,\n\t\t\t\td_model=xlnet_config.d_model,\n\t\t\t\tn_head=xlnet_config.n_head,\n\t\t\t\td_head=xlnet_config.d_head,\n\t\t\t\tdropout=run_config.dropout,\n\t\t\t\tdropatt=run_config.dropatt,\n\t\t\t\tis_training=run_config.is_training,\n\t\t\t\tinput_mask=self.input_mask,\n\t\t\t\tinitializer=self.initializer,\n\t\t\t\tuse_proj=use_summ_proj)\n\n\t\treturn summary\n\n\tdef get_sequence_output(self):\n\t\t\"\"\"\n\t\tReturns:\n\t\t float32 Tensor in shape [len, bsz, d_model]. The last layer hidden\n\t\t representation of XLNet.\n\t\t\"\"\"\n\n\t\treturn self.output\n\n\tdef get_new_memory(self):\n\t\t\"\"\"\n\t\tReturns:\n\t\t list of float32 Tensors in shape [mem_len, bsz, d_model], the new\n\t\t memory that concatenates the previous memory with the current input\n\t\t representations.\n\t\t The length of the list equals n_layer.\n\t\t\"\"\"\n\t\treturn self.new_mems\n\n\tdef get_embedding_table(self):\n\t\t\"\"\"\n\t\tReturns:\n\t\t float32 Tensor in shape [n_token, d_model]. The embedding lookup table.\n\t\t Used for tying embeddings between input and output layers.\n\t\t\"\"\"\n\t\treturn self.lookup_table\n\n\tdef get_initializer(self):\n\t\t\"\"\"\n\t\tReturns:\n\t\t A tf initializer. Used to initialize variables in layers on top of XLNet.\n\t\t\"\"\"\n\t\treturn self.initializer\n"
] |
[
[
"tensorflow.gfile.Open",
"tensorflow.gfile.Exists",
"tensorflow.initializers.random_normal",
"tensorflow.gfile.MakeDirs",
"tensorflow.variable_scope",
"tensorflow.initializers.random_uniform"
]
] |
lwgkzl/ICLR2021-Workshop-Challenge-Track2-Baseline
|
[
"b0a71c422134bc6e801aba9c925932d7650e59bc"
] |
[
"baseline_a2c/Collect.py"
] |
[
"import gym\r\nimport time\r\nimport torch\r\nimport warnings\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nfrom numbers import Number\r\nfrom typing import Dict, List, Union, Optional, Callable\r\n\r\nfrom tianshou.policy import BasePolicy\r\nfrom tianshou.exploration import BaseNoise\r\nfrom tianshou.data.batch import _create_value\r\nfrom tianshou.env import BaseVectorEnv, DummyVectorEnv\r\nfrom tianshou.data import Batch, ReplayBuffer, ListReplayBuffer, to_numpy\r\nfrom collections import defaultdict\r\n\r\nclass MyCollector(object):\r\n \"\"\"Collector enables the policy to interact with different types of envs.\r\n\r\n :param policy: an instance of the :class:`~tianshou.policy.BasePolicy`\r\n class.\r\n :param env: a ``gym.Env`` environment or an instance of the\r\n :class:`~tianshou.env.BaseVectorEnv` class.\r\n :param buffer: an instance of the :class:`~tianshou.data.ReplayBuffer`\r\n class. If set to ``None`` (testing phase), it will not store the data.\r\n :param function preprocess_fn: a function called before the data has been\r\n added to the buffer, see issue #42 and :ref:`preprocess_fn`, defaults\r\n to None.\r\n :param BaseNoise action_noise: add a noise to continuous action. Normally\r\n a policy already has a noise param for exploration in training phase,\r\n so this is recommended to use in test collector for some purpose.\r\n :param function reward_metric: to be used in multi-agent RL. The reward to\r\n report is of shape [agent_num], but we need to return a single scalar\r\n to monitor training. This function specifies what is the desired\r\n metric, e.g., the reward of agent 1 or the average reward over all\r\n agents. By default, the behavior is to select the reward of agent 1.\r\n\r\n The ``preprocess_fn`` is a function called before the data has been added\r\n to the buffer with batch format, which receives up to 7 keys as listed in\r\n :class:`~tianshou.data.Batch`. It will receive with only ``obs`` when the\r\n collector resets the environment. It returns either a dict or a\r\n :class:`~tianshou.data.Batch` with the modified keys and values. Examples\r\n are in \"test/base/test_collector.py\".\r\n\r\n Here is the example:\r\n ::\r\n\r\n policy = PGPolicy(...) # or other policies if you wish\r\n env = gym.make('CartPole-v0')\r\n replay_buffer = ReplayBuffer(size=10000)\r\n # here we set up a collector with a single environment\r\n collector = Collector(policy, env, buffer=replay_buffer)\r\n\r\n # the collector supports vectorized environments as well\r\n envs = DummyVectorEnv([lambda: gym.make('CartPole-v0')\r\n for _ in range(3)])\r\n collector = Collector(policy, envs, buffer=replay_buffer)\r\n\r\n # collect 3 episodes\r\n collector.collect(n_episode=3)\r\n # collect 1 episode for the first env, 3 for the third env\r\n collector.collect(n_episode=[1, 0, 3])\r\n # collect at least 2 steps\r\n collector.collect(n_step=2)\r\n # collect episodes with visual rendering (the render argument is the\r\n # sleep time between rendering consecutive frames)\r\n collector.collect(n_episode=1, render=0.03)\r\n\r\n Collected data always consist of full episodes. So if only ``n_step``\r\n argument is give, the collector may return the data more than the\r\n ``n_step`` limitation. Same as ``n_episode`` for the multiple environment\r\n case.\r\n\r\n .. note::\r\n\r\n Please make sure the given environment has a time limitation.\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n policy: BasePolicy,\r\n env: Union[gym.Env, BaseVectorEnv],\r\n buffer: Optional[ReplayBuffer] = None, # buff里面的东西是最终更新模型参数的数据, 所以buff里面存的是什么呢\r\n preprocess_fn: Optional[Callable[..., Batch]] = None,\r\n action_noise: Optional[BaseNoise] = None,\r\n reward_metric: Optional[Callable[[np.ndarray], float]] = None,\r\n ) -> None:\r\n super().__init__()\r\n if not isinstance(env, BaseVectorEnv):\r\n env = DummyVectorEnv([lambda: env])\r\n self.env = env\r\n self.env_num = len(env)\r\n # environments that are available in step()\r\n # this means all environments in synchronous simulation\r\n # but only a subset of environments in asynchronous simulation\r\n self._ready_env_ids = np.arange(self.env_num)\r\n # self.async is a flag to indicate whether this collector works\r\n # with asynchronous simulation\r\n self.is_async = env.is_async\r\n # need cache buffers before storing in the main buffer\r\n self._cached_buf = [ListReplayBuffer() for _ in range(self.env_num)]\r\n self.buffer = buffer\r\n self.policy = policy\r\n self.preprocess_fn = preprocess_fn\r\n # self.process_fn = policy.process_fn\r\n self.process_fn = None\r\n self._action_space = env.action_space\r\n self._action_noise = action_noise\r\n self._rew_metric = reward_metric or MyCollector._default_rew_metric\r\n # avoid creating attribute outside __init__\r\n self.reset()\r\n\r\n @staticmethod\r\n def _default_rew_metric(\r\n x: Union[Number, np.number]\r\n ) -> Union[Number, np.number]:\r\n # this internal function is designed for single-agent RL\r\n # for multi-agent RL, a reward_metric must be provided\r\n assert np.asanyarray(x).size == 1, (\r\n \"Please specify the reward_metric \"\r\n \"since the reward is not a scalar.\"\r\n )\r\n return x\r\n\r\n def reset(self) -> None:\r\n \"\"\"Reset all related variables in the collector.\"\"\"\r\n # use empty Batch for ``state`` so that ``self.data`` supports slicing\r\n # convert empty Batch to None when passing data to policy\r\n self.data = Batch(state={}, obs={}, act={}, rew={}, done={}, info={},\r\n obs_next={}, policy={})\r\n # print(\"before reset env\")\r\n self.reset_env()\r\n # print(\"after reset env\")\r\n self.reset_buffer()\r\n self.reset_stat()\r\n if self._action_noise is not None:\r\n self._action_noise.reset()\r\n\r\n def reset_stat(self) -> None:\r\n \"\"\"Reset the statistic variables.\"\"\"\r\n self.collect_time, self.collect_step, self.collect_episode = 0.0, 0, 0\r\n\r\n def reset_buffer(self) -> None:\r\n \"\"\"Reset the main data buffer.\"\"\"\r\n if self.buffer is not None:\r\n self.buffer.reset()\r\n\r\n def get_env_num(self) -> int:\r\n \"\"\"Return the number of environments the collector have.\"\"\"\r\n return self.env_num\r\n\r\n def reset_env(self) -> None:\r\n \"\"\"Reset all of the environment(s)' states and the cache buffers.\"\"\"\r\n self._ready_env_ids = np.arange(self.env_num)\r\n obs = self.env.reset()\r\n if self.preprocess_fn:\r\n obs = self.preprocess_fn(obs=obs).get(\"obs\", obs)\r\n self.data.obs = obs\r\n for b in self._cached_buf:\r\n b.reset()\r\n\r\n def _reset_state(self, id: Union[int, List[int]]) -> None:\r\n \"\"\"Reset the hidden state: self.data.state[id].\"\"\"\r\n # print(\"in reset_state: \", self.data.state)\r\n state = self.data.state # it is a reference\r\n if isinstance(state, torch.Tensor):\r\n state[id].zero_()\r\n elif isinstance(state, np.ndarray):\r\n state[id] = None if state.dtype == np.object else 0\r\n elif isinstance(state, Batch):\r\n state.empty_(id)\r\n\r\n def collect(\r\n self,\r\n n_step: Optional[int] = None,\r\n n_episode: Optional[Union[int, List[int]]] = None, # 多少个episodes\r\n random: bool = False,\r\n render: Optional[float] = None,\r\n no_grad: bool = True,\r\n ) -> Dict[str, float]:\r\n \"\"\"Collect a specified number of step or episode.\r\n\r\n :param int n_step: how many steps you want to collect.\r\n :param n_episode: how many episodes you want to collect. If it is an\r\n int, it means to collect at lease ``n_episode`` episodes; if it is\r\n a list, it means to collect exactly ``n_episode[i]`` episodes in\r\n the i-th environment\r\n :param bool random: whether to use random policy for collecting data,\r\n defaults to False.\r\n :param float render: the sleep time between rendering consecutive\r\n frames, defaults to None (no rendering).\r\n :param bool no_grad: whether to retain gradient in policy.forward,\r\n defaults to True (no gradient retaining).\r\n\r\n .. note::\r\n\r\n One and only one collection number specification is permitted,\r\n either ``n_step`` or ``n_episode``.\r\n\r\n :return: A dict including the following keys\r\n\r\n * ``n/ep`` the collected number of episodes.\r\n * ``n/st`` the collected number of steps.\r\n * ``v/st`` the speed of steps per second.\r\n * ``v/ep`` the speed of episode per second.\r\n * ``rew`` the mean reward over collected episodes.\r\n * ``len`` the mean length over collected episodes.\r\n \"\"\"\r\n assert (n_step is not None and n_episode is None and n_step > 0) or (\r\n n_step is None and n_episode is not None and np.sum(n_episode) > 0\r\n ), \"Only one of n_step or n_episode is allowed in Collector.collect, \"\r\n f\"got n_step = {n_step}, n_episode = {n_episode}.\"\r\n start_time = time.time()\r\n step_count = 0\r\n # episode of each environment\r\n episode_count = np.zeros(self.env_num)\r\n # If n_episode is a list, and some envs have collected the required\r\n # number of episodes, these envs will be recorded in this list, and\r\n # they will not be stepped.\r\n\r\n finished_env_ids = []\r\n rewards = []\r\n whole_data = Batch()\r\n if isinstance(n_episode, list):\r\n assert len(n_episode) == self.get_env_num()\r\n finished_env_ids = [\r\n i for i in self._ready_env_ids if n_episode[i] <= 0]\r\n self._ready_env_ids = np.array(\r\n [x for x in self._ready_env_ids if x not in finished_env_ids])\r\n right, wrong = 0., 0.\r\n mate_num = 0.\r\n right_index = defaultdict(int)\r\n while True:\r\n if step_count >= 100000 and episode_count.sum() == 0:\r\n warnings.warn(\r\n \"There are already many steps in an episode. \"\r\n \"You should add a time limitation to your environment!\",\r\n Warning)\r\n\r\n is_async = self.is_async or len(finished_env_ids) > 0\r\n if is_async:\r\n # self.data are the data for all environments in async(异步的)\r\n # simulation or some envs have finished,\r\n # **only a subset of data are disposed**,\r\n # so we store the whole data in ``whole_data``, let self.data\r\n # to be the data available in ready environments, and finally\r\n # set these back into all the data\r\n whole_data = self.data\r\n self.data = self.data[self._ready_env_ids]\r\n\r\n # restore the state and the input data\r\n last_state = self.data.state\r\n if isinstance(last_state, Batch) and last_state.is_empty():\r\n last_state = None\r\n self.data.update(state=Batch(), obs_next=Batch(), policy=Batch())\r\n # print(\"self.data: \", self.data)\r\n # print(\"know: \", self.env.goal_num)\r\n # calculate the next action\r\n # print(\"self.data.obs: \", self.data.obs.shape)\r\n if random:\r\n spaces = self._action_space\r\n result = Batch(\r\n act=[spaces[i].sample() for i in self._ready_env_ids])\r\n else:\r\n if no_grad:\r\n with torch.no_grad(): # faster than retain_grad version\r\n result = self.policy(self.data, last_state)\r\n else:\r\n result = self.policy(self.data, last_state)\r\n\r\n # print(\"result: \", result['logits'].size())\r\n # print(\"really: \", self.env.goal_num)\r\n state = result.get(\"state\", Batch())\r\n # convert None to Batch(), since None is reserved for 0-init\r\n if state is None:\r\n state = Batch()\r\n self.data.update(state=state, policy=result.get(\"policy\", Batch()))\r\n # save hidden state to policy._state, in order to save into buffer\r\n if not (isinstance(state, Batch) and state.is_empty()):\r\n self.data.policy._state = self.data.state\r\n\r\n self.data.act = to_numpy(result.act)\r\n if self._action_noise is not None:\r\n assert isinstance(self.data.act, np.ndarray)\r\n self.data.act += self._action_noise(self.data.act.shape)\r\n\r\n # step in env\r\n # print(self.env_num)\r\n # print(\"is_async: \", is_async)\r\n # print(\"in collect data.act: \", self.data.act)\r\n # print('fuck', self.env.goal_num)\r\n # print('self.data: ', type(self.data.act))\r\n # print(self.data.act)\r\n # 实在不行就在这里修改一下action吧\r\n if not is_async:\r\n obs_next, rew, done, info = self.env.step(self.data.act)\r\n # print(\"kk: \", self.env.goal_num)\r\n else:\r\n # store computed actions, states, etc\r\n _batch_set_item(\r\n whole_data, self._ready_env_ids, self.data, self.env_num)\r\n # fetch finished data\r\n obs_next, rew, done, info = self.env.step(\r\n self.data.act, id=self._ready_env_ids)\r\n self._ready_env_ids = np.array([i[\"env_id\"] for i in info])\r\n # get the stepped data\r\n self.data = whole_data[self._ready_env_ids]\r\n # move data to self.data\r\n # print(\"in every step info: \",info)\r\n # print(\"self.data: \", type(self.data))\r\n # self.data.update(obs_next=obs_next, rew=rew, done=done, info=info) # 暂时还不能更新info,得要在更新obs的地方更新info\r\n self.data.update(obs_next=obs_next, rew=rew, done=done) # 暂时还不能更新info,得要在更新obs的地方更新info\r\n # print(\"what? \", done)\r\n # print(\"action: \", self.data.act)\r\n if render:\r\n self.env.render()\r\n time.sleep(render)\r\n # print('Updatea: ', self.env.goal_num)\r\n # add data into the buffer\r\n if self.preprocess_fn:\r\n result = self.preprocess_fn(**self.data) # type: ignore\r\n self.data.update(result)\r\n\r\n # print(\"self._ready_env_ids: \", self._ready_env_ids)\r\n # print('len: ', [len(self._cached_buf[i]) for i in self._ready_env_ids])\r\n # print(\"\",self.data)\r\n for j, i in enumerate(self._ready_env_ids):\r\n # print(i,j)\r\n # j is the index in current ready_env_ids\r\n # i is the index in all environments\r\n if self.buffer is None:\r\n # users do not want to store data, so we store\r\n # small fake data here to make the code clean\r\n self._cached_buf[i].add(obs=0, act=0, rew=rew[j], done=0) # 每一个env都有一个cached_bug收集已经经历过的状态\r\n else:\r\n self._cached_buf[i].add(**self.data[j]) # 增加,并非覆盖,所以过程中的所有采样都会被采样到\r\n # print(\"maybe: \", self.env.goal_num)\r\n # print(\"buffer: \")\r\n # print(self.buffer)\r\n # print(\"done: \",done)\r\n if done[j]:\r\n if not (isinstance(n_episode, list)\r\n and episode_count[i] >= n_episode[i]):\r\n episode_count[i] += 1\r\n rewards.append(self._rew_metric(\r\n np.sum(self._cached_buf[i].rew, axis=0)))\r\n step_count += len(self._cached_buf[i])\r\n if self.buffer is not None:\r\n self.buffer.update(self._cached_buf[i])\r\n if isinstance(n_episode, list) and \\\r\n episode_count[i] >= n_episode[i]:\r\n # env i has collected enough data, it has finished\r\n finished_env_ids.append(i)\r\n # print(\"right? \", info[j]['right'])\r\n # print(\"two: \", self.env.goal_num)\r\n mate_num += info[j]['mate_num']\r\n # print(\"mate_num:\", mate_num)\r\n if info[j]['right']:\r\n right += 1\r\n right_index[info[j]['ans']] += 1\r\n else:\r\n wrong += 1\r\n self._cached_buf[i].reset()\r\n self._reset_state(j)\r\n # print(\"really?\", i, j)\r\n # print(\"three: \", self.env.goal_num)\r\n # print(\"after done: \", self.data['obs_next'])\r\n obs_next = self.data.obs_next\r\n self.data.info = info\r\n if sum(done): ##在这里会自动更新一个新的state\r\n env_ind_local = np.where(done)[0]\r\n env_ind_global = self._ready_env_ids[env_ind_local]\r\n # print(\"env_ind_global: \", env_ind_global)\r\n obs_reset = self.env.reset(env_ind_global)\r\n self.data['info']['history'][env_ind_local] = np.where(obs_reset != 0,np.ones_like(obs_reset), np.zeros_like(obs_reset))\r\n self.data['info']['turn'][env_ind_local] = np.zeros(len(env_ind_global))\r\n # print(\"Data: \", self.data)\r\n # print(\"obs_reset: \",obs_reset)\r\n if self.preprocess_fn:\r\n obs_reset = self.preprocess_fn(\r\n obs=obs_reset).get(\"obs\", obs_reset)\r\n obs_next[env_ind_local] = obs_reset\r\n self.data.obs = obs_next\r\n if is_async:\r\n # set data back\r\n whole_data = deepcopy(whole_data) # avoid reference in ListBuf\r\n _batch_set_item(\r\n whole_data, self._ready_env_ids, self.data, self.env_num)\r\n # let self.data be the data in all environments again\r\n self.data = whole_data\r\n self._ready_env_ids = np.array(\r\n [x for x in self._ready_env_ids if x not in finished_env_ids])\r\n if n_step:\r\n if step_count >= n_step:\r\n break\r\n else:\r\n if isinstance(n_episode, int) and \\\r\n episode_count.sum() >= n_episode:\r\n break\r\n if isinstance(n_episode, list) and \\\r\n (episode_count >= n_episode).all():\r\n break\r\n\r\n # finished envs are ready, and can be used for the next collection\r\n self._ready_env_ids = np.array(\r\n self._ready_env_ids.tolist() + finished_env_ids)\r\n\r\n # generate the statistics\r\n episode_count = sum(episode_count)\r\n duration = max(time.time() - start_time, 1e-9)\r\n self.collect_step += step_count\r\n self.collect_episode += episode_count\r\n self.collect_time += duration\r\n # print(self.env_num == 2, right + wrong)\r\n return {\r\n \"n/ep\": episode_count,\r\n \"n/st\": step_count,\r\n \"v/st\": step_count / duration,\r\n \"v/ep\": episode_count / duration,\r\n \"rew\": np.mean(rewards),\r\n \"rew_std\": np.std(rewards),\r\n \"len\": step_count / episode_count,\r\n \"hit_rate\": right / (right + wrong),\r\n \"class_rate\": right_index,\r\n 'mate_num': mate_num\r\n }\r\n\r\n\r\ndef _batch_set_item(\r\n source: Batch, indices: np.ndarray, target: Batch, size: int\r\n) -> None:\r\n # for any key chain k, there are four cases\r\n # 1. source[k] is non-reserved, but target[k] does not exist or is reserved\r\n # 2. source[k] does not exist or is reserved, but target[k] is non-reserved\r\n # 3. both source[k] and target[k] are non-reserved\r\n # 4. both source[k] and target[k] do not exist or are reserved, do nothing.\r\n # A special case in case 4, if target[k] is reserved but source[k] does\r\n # not exist, make source[k] reserved, too.\r\n for k, vt in target.items():\r\n if not isinstance(vt, Batch) or not vt.is_empty():\r\n # target[k] is non-reserved\r\n vs = source.get(k, Batch())\r\n if isinstance(vs, Batch):\r\n if vs.is_empty():\r\n # case 2, use __dict__ to avoid many type checks\r\n source.__dict__[k] = _create_value(vt[0], size)\r\n else:\r\n assert isinstance(vt, Batch)\r\n _batch_set_item(source.__dict__[k], indices, vt, size)\r\n else:\r\n # target[k] is reserved\r\n # case 1 or special case of case 4\r\n if k not in source.__dict__:\r\n source.__dict__[k] = Batch()\r\n continue\r\n source.__dict__[k][indices] = vt\r\n"
] |
[
[
"numpy.ones_like",
"numpy.arange",
"numpy.std",
"numpy.asanyarray",
"numpy.mean",
"numpy.where",
"numpy.zeros_like",
"torch.no_grad",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] |
vikozlov89/mlflow
|
[
"40b7367dd4e3bb4424b5a53cccaa1a70218cccc9"
] |
[
"mlflow/tracking/client.py"
] |
[
"\"\"\"\nInternal package providing a Python CRUD interface to MLflow experiments, runs, registered models,\nand model versions. This is a lower level API than the :py:mod:`mlflow.tracking.fluent` module,\nand is exposed in the :py:mod:`mlflow.tracking` module.\n\"\"\"\nimport contextlib\nimport logging\nimport json\nimport os\nimport posixpath\nimport sys\nimport tempfile\nimport yaml\nfrom typing import Any, Dict, Sequence, List, Optional, Union, TYPE_CHECKING\n\nfrom mlflow.entities import Experiment, Run, RunInfo, Param, Metric, RunTag, FileInfo, ViewType\nfrom mlflow.store.entities.paged_list import PagedList\nfrom mlflow.entities.model_registry import RegisteredModel, ModelVersion\nfrom mlflow.entities.model_registry.model_version_stages import ALL_STAGES\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.protos.databricks_pb2 import FEATURE_DISABLED\nfrom mlflow.store.model_registry import SEARCH_REGISTERED_MODEL_MAX_RESULTS_DEFAULT\nfrom mlflow.store.tracking import SEARCH_MAX_RESULTS_DEFAULT\nfrom mlflow.tracking._model_registry.client import ModelRegistryClient\nfrom mlflow.tracking._model_registry import utils as registry_utils\nfrom mlflow.tracking._model_registry import DEFAULT_AWAIT_MAX_SLEEP_SECONDS\nfrom mlflow.tracking._tracking_service import utils\nfrom mlflow.tracking._tracking_service.client import TrackingServiceClient\nfrom mlflow.tracking.artifact_utils import _upload_artifacts_to_databricks\nfrom mlflow.tracking.registry import UnsupportedModelRegistryStoreURIException\nfrom mlflow.utils.databricks_utils import (\n is_databricks_default_tracking_uri,\n is_in_databricks_job,\n is_in_databricks_notebook,\n get_workspace_info_from_dbutils,\n get_workspace_info_from_databricks_secrets,\n)\nfrom mlflow.utils.logging_utils import eprint\nfrom mlflow.utils.uri import is_databricks_uri, construct_run_url\nfrom mlflow.utils.annotations import experimental\n\nif TYPE_CHECKING:\n import matplotlib # pylint: disable=unused-import\n import plotly # pylint: disable=unused-import\n import numpy # pylint: disable=unused-import\n import PIL # pylint: disable=unused-import\n\n_logger = logging.getLogger(__name__)\n\n\nclass MlflowClient(object):\n \"\"\"\n Client of an MLflow Tracking Server that creates and manages experiments and runs, and of an\n MLflow Registry Server that creates and manages registered models and model versions. It's a\n thin wrapper around TrackingServiceClient and RegistryClient so there is a unified API but we\n can keep the implementation of the tracking and registry clients independent from each other.\n \"\"\"\n\n def __init__(self, tracking_uri: Optional[str] = None, registry_uri: Optional[str] = None):\n \"\"\"\n :param tracking_uri: Address of local or remote tracking server. If not provided, defaults\n to the service set by ``mlflow.tracking.set_tracking_uri``. See\n `Where Runs Get Recorded <../tracking.html#where-runs-get-recorded>`_\n for more info.\n :param registry_uri: Address of local or remote model registry server. If not provided,\n defaults to the service set by ``mlflow.tracking.set_registry_uri``. If\n no such service was set, defaults to the tracking uri of the client.\n \"\"\"\n final_tracking_uri = utils._resolve_tracking_uri(tracking_uri)\n self._registry_uri = registry_utils._resolve_registry_uri(registry_uri, tracking_uri)\n self._tracking_client = TrackingServiceClient(final_tracking_uri)\n # `MlflowClient` also references a `ModelRegistryClient` instance that is provided by the\n # `MlflowClient._get_registry_client()` method. This `ModelRegistryClient` is not explicitly\n # defined as an instance variable in the `MlflowClient` constructor; an instance variable\n # is assigned lazily by `MlflowClient._get_registry_client()` and should not be referenced\n # outside of the `MlflowClient._get_registry_client()` method\n\n def _get_registry_client(self):\n \"\"\"\n Attempts to create a py:class:`ModelRegistryClient` if one does not already exist.\n\n :raises: py:class:`mlflow.exceptions.MlflowException` if the py:class:`ModelRegistryClient`\n cannot be created. This may occur, for example, when the registry URI refers\n to an unsupported store type (e.g., the FileStore).\n :return: A py:class:`ModelRegistryClient` instance\n \"\"\"\n # Attempt to fetch a `ModelRegistryClient` that is lazily instantiated and defined as\n # an instance variable on this `MlflowClient` instance. Because the instance variable\n # is undefined until the first invocation of _get_registry_client(), the `getattr()`\n # function is used to safely fetch the variable (if it is defined) or a NoneType\n # (if it is not defined)\n registry_client_attr = \"_registry_client_lazy\"\n registry_client = getattr(self, registry_client_attr, None)\n if registry_client is None:\n try:\n registry_client = ModelRegistryClient(self._registry_uri)\n # Define an instance variable on this `MlflowClient` instance to reference the\n # `ModelRegistryClient` that was just constructed. `setattr()` is used to ensure\n # that the variable name is consistent with the variable name specified in the\n # preceding call to `getattr()`\n setattr(self, registry_client_attr, registry_client)\n except UnsupportedModelRegistryStoreURIException as exc:\n raise MlflowException(\n \"Model Registry features are not supported by the store with URI:\"\n \" '{uri}'. Stores with the following URI schemes are supported:\"\n \" {schemes}.\".format(uri=self._registry_uri, schemes=exc.supported_uri_schemes),\n FEATURE_DISABLED,\n )\n return registry_client\n\n # Tracking API\n\n def get_run(self, run_id: str) -> Run:\n \"\"\"\n Fetch the run from backend store. The resulting :py:class:`Run <mlflow.entities.Run>`\n contains a collection of run metadata -- :py:class:`RunInfo <mlflow.entities.RunInfo>`,\n as well as a collection of run parameters, tags, and metrics --\n :py:class:`RunData <mlflow.entities.RunData>`. In the case where multiple metrics with the\n same key are logged for the run, the :py:class:`RunData <mlflow.entities.RunData>` contains\n the most recently logged value at the largest step for each metric.\n\n :param run_id: Unique identifier for the run.\n\n :return: A single :py:class:`mlflow.entities.Run` object, if the run exists. Otherwise,\n raises an exception.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n with mlflow.start_run() as run:\n mlflow.log_param(\"p\", 0)\n\n # The run has finished since we have exited the with block\n # Fetch the run\n client = MlflowClient()\n run = client.get_run(run.info.run_id)\n print(\"run_id: {}\".format(run.info.run_id))\n print(\"params: {}\".format(run.data.params))\n print(\"status: {}\".format(run.info.status))\n\n .. code-block:: text\n :caption: Output\n\n run_id: e36b42c587a1413ead7c3b6764120618\n params: {'p': '0'}\n status: FINISHED\n \"\"\"\n return self._tracking_client.get_run(run_id)\n\n def get_metric_history(self, run_id: str, key: str) -> List[Metric]:\n \"\"\"\n Return a list of metric objects corresponding to all values logged for a given metric.\n\n :param run_id: Unique identifier for run\n :param key: Metric name within the run\n\n :return: A list of :py:class:`mlflow.entities.Metric` entities if logged, else empty list\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_metric_info(history):\n for m in history:\n print(\"name: {}\".format(m.key))\n print(\"value: {}\".format(m.value))\n print(\"step: {}\".format(m.step))\n print(\"timestamp: {}\".format(m.timestamp))\n print(\"--\")\n\n # Create a run under the default experiment (whose id is \"0\"). Since this is low-level\n # CRUD operation, the method will create a run. To end the run, you'll have\n # to explicitly end it.\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n print(\"run_id: {}\".format(run.info.run_id))\n print(\"--\")\n\n # Log couple of metrics, update their initial value, and fetch each\n # logged metrics' history.\n for k, v in [(\"m1\", 1.5), (\"m2\", 2.5)]:\n client.log_metric(run.info.run_id, k, v, step=0)\n client.log_metric(run.info.run_id, k, v + 1, step=1)\n print_metric_info(client.get_metric_history(run.info.run_id, k))\n client.set_terminated(run.info.run_id)\n\n .. code-block:: text\n :caption: Output\n\n run_id: c360d15714994c388b504fe09ea3c234\n --\n name: m1\n value: 1.5\n step: 0\n timestamp: 1603423788607\n --\n name: m1\n value: 2.5\n step: 1\n timestamp: 1603423788608\n --\n name: m2\n value: 2.5\n step: 0\n timestamp: 1603423788609\n --\n name: m2\n value: 3.5\n step: 1\n timestamp: 1603423788610\n --\n \"\"\"\n return self._tracking_client.get_metric_history(run_id, key)\n\n def create_run(\n self,\n experiment_id: str,\n start_time: Optional[int] = None,\n tags: Optional[Dict[str, Any]] = None,\n ) -> Run:\n \"\"\"\n Create a :py:class:`mlflow.entities.Run` object that can be associated with\n metrics, parameters, artifacts, etc.\n Unlike :py:func:`mlflow.projects.run`, creates objects but does not run code.\n Unlike :py:func:`mlflow.start_run`, does not change the \"active run\" used by\n :py:func:`mlflow.log_param`.\n\n :param experiment_id: The string ID of the experiment to create a run in.\n :param start_time: If not provided, use the current timestamp.\n :param tags: A dictionary of key-value pairs that are converted into\n :py:class:`mlflow.entities.RunTag` objects.\n :return: :py:class:`mlflow.entities.Run` that was created.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create a run with a tag under the default experiment (whose id is '0').\n tags = {\"engineering\": \"ML Platform\"}\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id, tags=tags)\n\n # Show newly created run metadata info\n print(\"Run tags: {}\".format(run.data.tags))\n print(\"Experiment id: {}\".format(run.info.experiment_id))\n print(\"Run id: {}\".format(run.info.run_id))\n print(\"lifecycle_stage: {}\".format(run.info.lifecycle_stage))\n print(\"status: {}\".format(run.info.status))\n\n .. code-block:: text\n :caption: Output\n\n Run tags: {'engineering': 'ML Platform'}\n Experiment id: 0\n Run id: 65fb9e2198764354bab398105f2e70c1\n lifecycle_stage: active\n status: RUNNING\n \"\"\"\n return self._tracking_client.create_run(experiment_id, start_time, tags)\n\n def list_run_infos(\n self,\n experiment_id: str,\n run_view_type: int = ViewType.ACTIVE_ONLY,\n max_results: int = SEARCH_MAX_RESULTS_DEFAULT,\n order_by: Optional[List[str]] = None,\n page_token: Optional[str] = None,\n ) -> PagedList[RunInfo]:\n \"\"\"\n Return run information for runs which belong to the experiment_id.\n\n :param experiment_id: The experiment id which to search\n :param run_view_type: ACTIVE_ONLY, DELETED_ONLY, or ALL runs\n :param max_results: Maximum number of results desired.\n :param order_by: List of order_by clauses. Currently supported values are\n are ``metric.key``, ``parameter.key``, ``tag.key``, ``attribute.key``.\n For example, ``order_by=[\"tag.release ASC\", \"metric.click_rate DESC\"]``.\n\n :return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of\n :py:class:`RunInfo <mlflow.entities.RunInfo>` objects that satisfy the search\n expressions. If the underlying tracking store supports pagination, the token for the\n next page may be obtained via the ``token`` attribute of the returned object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n from mlflow.entities import ViewType\n\n def print_run_infos(run_infos):\n for r in run_infos:\n print(\"- run_id: {}, lifecycle_stage: {}\".format(r.run_id, r.lifecycle_stage))\n\n # Create two runs\n with mlflow.start_run() as run1:\n mlflow.log_metric(\"click_rate\", 1.55)\n\n with mlflow.start_run() as run2:\n mlflow.log_metric(\"click_rate\", 2.50)\n\n # Delete the last run\n client = MlflowClient()\n client.delete_run(run2.info.run_id)\n\n # Get all runs under the default experiment (whose id is 0)\n print(\"Active runs:\")\n print_run_infos(mlflow.list_run_infos(\"0\", run_view_type=ViewType.ACTIVE_ONLY))\n\n print(\"Deleted runs:\")\n print_run_infos(mlflow.list_run_infos(\"0\", run_view_type=ViewType.DELETED_ONLY))\n\n print(\"All runs:\")\n print_run_infos(mlflow.list_run_infos(\"0\", run_view_type=ViewType.ALL,\n order_by=[\"metric.click_rate DESC\"]))\n\n .. code-block:: text\n :caption: Output\n\n Active runs:\n - run_id: 47b11b33f9364ee2b148c41375a30a68, lifecycle_stage: active\n Deleted runs:\n - run_id: bc4803439bdd4a059103811267b6b2f4, lifecycle_stage: deleted\n All runs:\n - run_id: bc4803439bdd4a059103811267b6b2f4, lifecycle_stage: deleted\n - run_id: 47b11b33f9364ee2b148c41375a30a68, lifecycle_stage: active\n \"\"\"\n return self._tracking_client.list_run_infos(\n experiment_id, run_view_type, max_results, order_by, page_token\n )\n\n def list_experiments(\n self,\n view_type: int = ViewType.ACTIVE_ONLY,\n max_results: Optional[int] = None,\n page_token: Optional[str] = None,\n ) -> PagedList[Experiment]:\n \"\"\"\n :param view_type: Qualify requested type of experiments.\n :param max_results: If passed, specifies the maximum number of experiments desired. If not\n passed, all experiments will be returned for the File and SQL backends.\n For the REST backend, the server will pick a maximum number of results\n to return.\n :param page_token: Token specifying the next page of results. It should be obtained from\n a ``list_experiments`` call.\n :return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of\n :py:class:`Experiment <mlflow.entities.Experiment>` objects. The pagination token\n for the next page can be obtained via the ``token`` attribute of the object.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n from mlflow.entities import ViewType\n\n def print_experiment_info(experiments):\n for e in experiments:\n print(\"- experiment_id: {}, name: {}, lifecycle_stage: {}\"\n .format(e.experiment_id, e.name, e.lifecycle_stage))\n\n client = MlflowClient()\n for name in [\"Experiment 1\", \"Experiment 2\"]:\n exp_id = client.create_experiment(name)\n\n # Delete the last experiment\n client.delete_experiment(exp_id)\n\n # Fetch experiments by view type\n print(\"Active experiments:\")\n print_experiment_info(client.list_experiments(view_type=ViewType.ACTIVE_ONLY))\n print(\"Deleted experiments:\")\n print_experiment_info(client.list_experiments(view_type=ViewType.DELETED_ONLY))\n print(\"All experiments:\")\n print_experiment_info(client.list_experiments(view_type=ViewType.ALL))\n\n .. code-block:: text\n :caption: Output\n\n Active experiments:\n - experiment_id: 0, name: Default, lifecycle_stage: active\n - experiment_id: 1, name: Experiment 1, lifecycle_stage: active\n Deleted experiments:\n - experiment_id: 2, name: Experiment 2, lifecycle_stage: deleted\n All experiments:\n - experiment_id: 0, name: Default, lifecycle_stage: active\n - experiment_id: 1, name: Experiment 1, lifecycle_stage: active\n - experiment_id: 2, name: Experiment 2, lifecycle_stage: deleted\n \"\"\"\n return self._tracking_client.list_experiments(\n view_type=view_type, max_results=max_results, page_token=page_token\n )\n\n def get_experiment(self, experiment_id: str) -> Experiment:\n \"\"\"\n Retrieve an experiment by experiment_id from the backend store\n\n :param experiment_id: The experiment ID returned from ``create_experiment``.\n :return: :py:class:`mlflow.entities.Experiment`\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n client = MlflowClient()\n exp_id = client.create_experiment(\"Experiment\")\n experiment = client.get_experiment(exp_id)\n\n # Show experiment info\n print(\"Name: {}\".format(experiment.name))\n print(\"Experiment ID: {}\".format(experiment.experiment_id))\n print(\"Artifact Location: {}\".format(experiment.artifact_location))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n Name: Experiment\n Experiment ID: 1\n Artifact Location: file:///.../mlruns/1\n Lifecycle_stage: active\n \"\"\"\n return self._tracking_client.get_experiment(experiment_id)\n\n def get_experiment_by_name(self, name: str) -> Optional[Experiment]:\n \"\"\"\n Retrieve an experiment by experiment name from the backend store\n\n :param name: The experiment name, which is case sensitive.\n :return: An instance of :py:class:`mlflow.entities.Experiment`\n if an experiment with the specified name exists, otherwise None.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Case-sensitive name\n client = MlflowClient()\n experiment = client.get_experiment_by_name(\"Default\")\n\n # Show experiment info\n print(\"Name: {}\".format(experiment.name))\n print(\"Experiment ID: {}\".format(experiment.experiment_id))\n print(\"Artifact Location: {}\".format(experiment.artifact_location))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n Name: Default\n Experiment ID: 0\n Artifact Location: file:///.../mlruns/0\n Lifecycle_stage: active\n \"\"\"\n return self._tracking_client.get_experiment_by_name(name)\n\n def create_experiment(self, name: str, artifact_location: Optional[str] = None) -> str:\n \"\"\"Create an experiment.\n\n :param name: The experiment name. Must be unique.\n :param artifact_location: The location to store run artifacts.\n If not provided, the server picks an appropriate default.\n :return: String as an integer ID of the created experiment.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create an experiment with a name that is unique and case sensitive.\n client = MlflowClient()\n experiment_id = client.create_experiment(\"Social NLP Experiments\")\n client.set_experiment_tag(experiment_id, \"nlp.framework\", \"Spark NLP\")\n\n # Fetch experiment metadata information\n experiment = client.get_experiment(experiment_id)\n print(\"Name: {}\".format(experiment.name))\n print(\"Experiment_id: {}\".format(experiment.experiment_id))\n print(\"Artifact Location: {}\".format(experiment.artifact_location))\n print(\"Tags: {}\".format(experiment.tags))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n Name: Social NLP Experiments\n Experiment_id: 1\n Artifact Location: file:///.../mlruns/1\n Tags: {'nlp.framework': 'Spark NLP'}\n Lifecycle_stage: active\n \"\"\"\n return self._tracking_client.create_experiment(name, artifact_location)\n\n def delete_experiment(self, experiment_id: str) -> None:\n \"\"\"\n Delete an experiment from the backend store.\n\n :param experiment_id: The experiment ID returned from ``create_experiment``.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create an experiment with a name that is unique and case sensitive\n client = MlflowClient()\n experiment_id = client.create_experiment(\"New Experiment\")\n client.delete_experiment(experiment_id)\n\n # Examine the deleted experiment details.\n experiment = client.get_experiment(experiment_id)\n print(\"Name: {}\".format(experiment.name))\n print(\"Artifact Location: {}\".format(experiment.artifact_location))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n Name: New Experiment\n Artifact Location: file:///.../mlruns/1\n Lifecycle_stage: deleted\n \"\"\"\n self._tracking_client.delete_experiment(experiment_id)\n\n def restore_experiment(self, experiment_id: str) -> None:\n \"\"\"\n Restore a deleted experiment unless permanently deleted.\n\n :param experiment_id: The experiment ID returned from ``create_experiment``.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_experiment_info(experiment):\n print(\"Name: {}\".format(experiment.name))\n print(\"Experiment Id: {}\".format(experiment.experiment_id))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n # Create and delete an experiment\n client = MlflowClient()\n experiment_id = client.create_experiment(\"New Experiment\")\n client.delete_experiment(experiment_id)\n\n # Examine the deleted experiment details.\n experiment = client.get_experiment(experiment_id)\n print_experiment_info(experiment)\n print(\"--\")\n\n # Restore the experiment and fetch its info\n client.restore_experiment(experiment_id)\n experiment = client.get_experiment(experiment_id)\n print_experiment_info(experiment)\n\n .. code-block:: text\n :caption: Output\n\n Name: New Experiment\n Experiment Id: 1\n Lifecycle_stage: deleted\n --\n Name: New Experiment\n Experiment Id: 1\n Lifecycle_stage: active\n \"\"\"\n self._tracking_client.restore_experiment(experiment_id)\n\n def rename_experiment(self, experiment_id: str, new_name: str) -> None:\n \"\"\"\n Update an experiment's name. The new name must be unique.\n\n :param experiment_id: The experiment ID returned from ``create_experiment``.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_experiment_info(experiment):\n print(\"Name: {}\".format(experiment.name))\n print(\"Experiment_id: {}\".format(experiment.experiment_id))\n print(\"Lifecycle_stage: {}\".format(experiment.lifecycle_stage))\n\n # Create an experiment with a name that is unique and case sensitive\n client = MlflowClient()\n experiment_id = client.create_experiment(\"Social NLP Experiments\")\n\n # Fetch experiment metadata information\n experiment = client.get_experiment(experiment_id)\n print_experiment_info(experiment)\n print(\"--\")\n\n # Rename and fetch experiment metadata information\n client.rename_experiment(experiment_id, \"Social Media NLP Experiments\")\n experiment = client.get_experiment(experiment_id)\n print_experiment_info(experiment)\n\n .. code-block:: text\n :caption: Output\n\n Name: Social NLP Experiments\n Experiment_id: 1\n Lifecycle_stage: active\n --\n Name: Social Media NLP Experiments\n Experiment_id: 1\n Lifecycle_stage: active\n \"\"\"\n self._tracking_client.rename_experiment(experiment_id, new_name)\n\n def log_metric(\n self,\n run_id: str,\n key: str,\n value: float,\n timestamp: Optional[int] = None,\n step: Optional[int] = None,\n ) -> None:\n \"\"\"\n Log a metric against the run ID.\n\n :param run_id: The run id to which the metric should be logged.\n :param key: Metric name.\n :param value: Metric value (float). Note that some special values such\n as +/- Infinity may be replaced by other values depending on the store. For\n example, the SQLAlchemy store replaces +/- Inf with max / min float values.\n :param timestamp: Time when this metric was calculated. Defaults to the current system time.\n :param step: Integer training step (iteration) at which was the metric calculated.\n Defaults to 0.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_run_info(r):\n print(\"run_id: {}\".format(r.info.run_id))\n print(\"metrics: {}\".format(r.data.metrics))\n print(\"status: {}\".format(r.info.status))\n\n # Create a run under the default experiment (whose id is '0').\n # Since these are low-level CRUD operations, this method will create a run.\n # To end the run, you'll have to explicitly end it.\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n print_run_info(run)\n print(\"--\")\n\n # Log the metric. Unlike mlflow.log_metric this method\n # does not start a run if one does not exist. It will log\n # the metric for the run id in the backend store.\n client.log_metric(run.info.run_id, \"m\", 1.5)\n client.set_terminated(run.info.run_id)\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: 95e79843cb2c463187043d9065185e24\n metrics: {}\n status: RUNNING\n --\n run_id: 95e79843cb2c463187043d9065185e24\n metrics: {'m': 1.5}\n status: FINISHED\n \"\"\"\n self._tracking_client.log_metric(run_id, key, value, timestamp, step)\n\n def log_param(self, run_id: str, key: str, value: Any) -> None:\n \"\"\"\n Log a parameter against the run ID.\n\n :param run_id: The run id to which the param should be logged.\n :param value: Value is converted to a string.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_run_info(r):\n print(\"run_id: {}\".format(r.info.run_id))\n print(\"params: {}\".format(r.data.params))\n print(\"status: {}\".format(r.info.status))\n\n # Create a run under the default experiment (whose id is '0').\n # Since these are low-level CRUD operations, this method will create a run.\n # To end the run, you'll have to explicitly end it.\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n print_run_info(run)\n print(\"--\")\n\n # Log the parameter. Unlike mlflow.log_param this method\n # does not start a run if one does not exist. It will log\n # the parameter in the backend store\n client.log_param(run.info.run_id, \"p\", 1)\n client.set_terminated(run.info.run_id)\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: e649e49c7b504be48ee3ae33c0e76c93\n params: {}\n status: RUNNING\n --\n run_id: e649e49c7b504be48ee3ae33c0e76c93\n params: {'p': '1'}\n status: FINISHED\n \"\"\"\n self._tracking_client.log_param(run_id, key, value)\n\n def set_experiment_tag(self, experiment_id: str, key: str, value: Any) -> None:\n \"\"\"\n Set a tag on the experiment with the specified ID. Value is converted to a string.\n\n :param experiment_id: String ID of the experiment.\n :param key: Name of the tag.\n :param value: Tag value (converted to a string).\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create an experiment and set its tag\n client = MlflowClient()\n experiment_id = client.create_experiment(\"Social Media NLP Experiments\")\n client.set_experiment_tag(experiment_id, \"nlp.framework\", \"Spark NLP\")\n\n # Fetch experiment metadata information\n experiment = client.get_experiment(experiment_id)\n print(\"Name: {}\".format(experiment.name))\n print(\"Tags: {}\".format(experiment.tags))\n\n .. code-block:: text\n :caption: Output\n\n Name: Social Media NLP Experiments\n Tags: {'nlp.framework': 'Spark NLP'}\n \"\"\"\n self._tracking_client.set_experiment_tag(experiment_id, key, value)\n\n def set_tag(self, run_id: str, key: str, value: Any) -> None:\n \"\"\"\n Set a tag on the run with the specified ID. Value is converted to a string.\n\n :param run_id: String ID of the run.\n :param key: Name of the tag.\n :param value: Tag value (converted to a string)\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_run_info(run):\n print(\"run_id: {}\".format(run.info.run_id))\n print(\"Tags: {}\".format(run.data.tags))\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n print_run_info(run)\n print(\"--\")\n\n # Set a tag and fetch updated run info\n client.set_tag(run.info.run_id, \"nlp.framework\", \"Spark NLP\")\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: 4f226eb5758145e9b28f78514b59a03b\n Tags: {}\n --\n run_id: 4f226eb5758145e9b28f78514b59a03b\n Tags: {'nlp.framework': 'Spark NLP'}\n \"\"\"\n self._tracking_client.set_tag(run_id, key, value)\n\n def delete_tag(self, run_id: str, key: str) -> None:\n \"\"\"\n Delete a tag from a run. This is irreversible.\n\n :param run_id: String ID of the run\n :param key: Name of the tag\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_run_info(run):\n print(\"run_id: {}\".format(run.info.run_id))\n print(\"Tags: {}\".format(run.data.tags))\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n tags = {\"t1\": 1, \"t2\": 2}\n experiment_id = \"0\"\n run = client.create_run(experiment_id, tags=tags)\n print_run_info(run)\n print(\"--\")\n\n # Delete tag and fetch updated info\n client.delete_tag(run.info.run_id, \"t1\")\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: b7077267a59a45d78cd9be0de4bc41f5\n Tags: {'t2': '2', 't1': '1'}\n --\n run_id: b7077267a59a45d78cd9be0de4bc41f5\n Tags: {'t2': '2'}\n \"\"\"\n self._tracking_client.delete_tag(run_id, key)\n\n def log_batch(\n self,\n run_id: str,\n metrics: Sequence[Metric] = (),\n params: Sequence[Param] = (),\n tags: Sequence[RunTag] = (),\n ) -> None:\n \"\"\"\n Log multiple metrics, params, and/or tags.\n\n :param run_id: String ID of the run\n :param metrics: If provided, List of Metric(key, value, timestamp) instances.\n :param params: If provided, List of Param(key, value) instances.\n :param tags: If provided, List of RunTag(key, value) instances.\n\n Raises an MlflowException if any errors occur.\n :return: None\n\n .. code-block:: python\n :caption: Example\n\n import time\n\n from mlflow.tracking import MlflowClient\n from mlflow.entities import Metric, Param, RunTag\n\n def print_run_info(r):\n print(\"run_id: {}\".format(r.info.run_id))\n print(\"params: {}\".format(r.data.params))\n print(\"metrics: {}\".format(r.data.metrics))\n print(\"tags: {}\".format(r.data.tags))\n print(\"status: {}\".format(r.info.status))\n\n # Create MLflow entities and a run under the default experiment (whose id is '0').\n timestamp = int(time.time() * 1000)\n metrics = [Metric('m', 1.5, timestamp, 1)]\n params = [Param(\"p\", 'p')]\n tags = [RunTag(\"t\", \"t\")]\n experiment_id = \"0\"\n client = MlflowClient()\n run = client.create_run(experiment_id)\n\n # Log entities, terminate the run, and fetch run status\n client.log_batch(run.info.run_id, metrics=metrics, params=params, tags=tags)\n client.set_terminated(run.info.run_id)\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: ef0247fa3205410595acc0f30f620871\n params: {'p': 'p'}\n metrics: {'m': 1.5}\n tags: {'t': 't'}\n status: FINISHED\n \"\"\"\n self._tracking_client.log_batch(run_id, metrics, params, tags)\n\n def log_artifact(self, run_id, local_path, artifact_path=None) -> None:\n \"\"\"\n Write a local file or directory to the remote ``artifact_uri``.\n\n :param local_path: Path to the file or directory to write.\n :param artifact_path: If provided, the directory in ``artifact_uri`` to write to.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n features = \"rooms, zipcode, median_price, school_rating, transport\"\n with open(\"features.txt\", 'w') as f:\n f.write(features)\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n\n # log and fetch the artifact\n client.log_artifact(run.info.run_id, \"features.txt\")\n artifacts = client.list_artifacts(run.info.run_id)\n for artifact in artifacts:\n print(\"artifact: {}\".format(artifact.path))\n print(\"is_dir: {}\".format(artifact.is_dir))\n client.set_terminated(run.info.run_id)\n\n .. code-block:: text\n :caption: Output\n\n artifact: features.txt\n is_dir: False\n \"\"\"\n self._tracking_client.log_artifact(run_id, local_path, artifact_path)\n\n def log_artifacts(\n self, run_id: str, local_dir: str, artifact_path: Optional[str] = None\n ) -> None:\n \"\"\"\n Write a directory of files to the remote ``artifact_uri``.\n\n :param local_dir: Path to the directory of files to write.\n :param artifact_path: If provided, the directory in ``artifact_uri`` to write to.\n\n .. code-block:: python\n :caption: Example\n\n import os\n import json\n\n # Create some artifacts data to preserve\n features = \"rooms, zipcode, median_price, school_rating, transport\"\n data = {\"state\": \"TX\", \"Available\": 25, \"Type\": \"Detached\"}\n\n # Create couple of artifact files under the local directory \"data\"\n os.makedirs(\"data\", exist_ok=True)\n with open(\"data/data.json\", 'w', encoding='utf-8') as f:\n json.dump(data, f, indent=2)\n with open(\"data/features.txt\", 'w') as f:\n f.write(features)\n\n # Create a run under the default experiment (whose id is '0'), and log\n # all files in \"data\" to root artifact_uri/states\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n client.log_artifacts(run.info.run_id, \"data\", artifact_path=\"states\")\n artifacts = client.list_artifacts(run.info.run_id)\n for artifact in artifacts:\n print(\"artifact: {}\".format(artifact.path))\n print(\"is_dir: {}\".format(artifact.is_dir))\n client.set_terminated(run.info.run_id)\n\n .. code-block:: text\n :caption: Output\n\n artifact: states\n is_dir: True\n \"\"\"\n self._tracking_client.log_artifacts(run_id, local_dir, artifact_path)\n\n @contextlib.contextmanager\n def _log_artifact_helper(self, run_id, artifact_file):\n \"\"\"\n Yields a temporary path to store a file, and then calls `log_artifact` against that path.\n\n :param run_id: String ID of the run.\n :param artifact_file: The run-relative artifact file path in posixpath format.\n :return: Temporary path to store a file.\n \"\"\"\n norm_path = posixpath.normpath(artifact_file)\n filename = posixpath.basename(norm_path)\n artifact_dir = posixpath.dirname(norm_path)\n artifact_dir = None if artifact_dir == \"\" else artifact_dir\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n tmp_path = os.path.join(tmp_dir, filename)\n yield tmp_path\n self.log_artifact(run_id, tmp_path, artifact_dir)\n\n def log_text(self, run_id: str, text: str, artifact_file: str) -> None:\n \"\"\"\n Log text as an artifact.\n\n :param run_id: String ID of the run.\n :param text: String containing text to log.\n :param artifact_file: The run-relative artifact file path in posixpath format to which\n the text is saved (e.g. \"dir/file.txt\").\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n client = MlflowClient()\n run = client.create_run(experiment_id=\"0\")\n\n # Log text to a file under the run's root artifact directory\n client.log_text(run.info.run_id, \"text1\", \"file1.txt\")\n\n # Log text in a subdirectory of the run's root artifact directory\n client.log_text(run.info.run_id, \"text2\", \"dir/file2.txt\")\n\n # Log HTML text\n client.log_text(run.info.run_id, \"<h1>header</h1>\", \"index.html\")\n \"\"\"\n with self._log_artifact_helper(run_id, artifact_file) as tmp_path:\n with open(tmp_path, \"w\") as f:\n f.write(text)\n\n @experimental\n def log_dict(self, run_id: str, dictionary: Any, artifact_file: str) -> None:\n \"\"\"\n Log a JSON/YAML-serializable object (e.g. `dict`) as an artifact. The serialization\n format (JSON or YAML) is automatically inferred from the extension of `artifact_file`.\n If the file extension doesn't exist or match any of [\".json\", \".yml\", \".yaml\"],\n JSON format is used.\n\n :param run_id: String ID of the run.\n :param dictionary: Dictionary to log.\n :param artifact_file: The run-relative artifact file path in posixpath format to which\n the dictionary is saved (e.g. \"dir/data.json\").\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n client = MlflowClient()\n run = client.create_run(experiment_id=\"0\")\n run_id = run.info.run_id\n\n dictionary = {\"k\": \"v\"}\n\n # Log a dictionary as a JSON file under the run's root artifact directory\n client.log_dict(run_id, dictionary, \"data.json\")\n\n # Log a dictionary as a YAML file in a subdirectory of the run's root artifact directory\n client.log_dict(run_id, dictionary, \"dir/data.yml\")\n\n # If the file extension doesn't exist or match any of [\".json\", \".yaml\", \".yml\"],\n # JSON format is used.\n mlflow.log_dict(run_id, dictionary, \"data\")\n mlflow.log_dict(run_id, dictionary, \"data.txt\")\n \"\"\"\n extension = os.path.splitext(artifact_file)[1]\n\n with self._log_artifact_helper(run_id, artifact_file) as tmp_path:\n with open(tmp_path, \"w\") as f:\n # Specify `indent` to prettify the output\n if extension in [\".yml\", \".yaml\"]:\n yaml.dump(dictionary, f, indent=2, default_flow_style=False)\n else:\n json.dump(dictionary, f, indent=2)\n\n @experimental\n def log_figure(\n self,\n run_id: str,\n figure: Union[\"matplotlib.figure.Figure\", \"plotly.graph_objects.Figure\"],\n artifact_file: str,\n ) -> None:\n \"\"\"\n Log a figure as an artifact. The following figure objects are supported:\n\n - `matplotlib.figure.Figure`_\n - `plotly.graph_objects.Figure`_\n\n .. _matplotlib.figure.Figure:\n https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html\n\n .. _plotly.graph_objects.Figure:\n https://plotly.com/python-api-reference/generated/plotly.graph_objects.Figure.html\n\n :param run_id: String ID of the run.\n :param figure: Figure to log.\n :param artifact_file: The run-relative artifact file path in posixpath format to which\n the figure is saved (e.g. \"dir/file.png\").\n\n .. code-block:: python\n :caption: Matplotlib Example\n\n import mlflow\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n ax.plot([0, 1], [2, 3])\n\n run = client.create_run(experiment_id=\"0\")\n client.log_figure(run.info.run_id, fig, \"figure.png\")\n\n .. code-block:: python\n :caption: Plotly Example\n\n import mlflow\n from plotly import graph_objects as go\n\n fig = go.Figure(go.Scatter(x=[0, 1], y=[2, 3]))\n\n run = client.create_run(experiment_id=\"0\")\n client.log_figure(run.info.run_id, fig, \"figure.html\")\n \"\"\"\n\n def _is_matplotlib_figure(fig):\n import matplotlib\n\n return isinstance(fig, matplotlib.figure.Figure)\n\n def _is_plotly_figure(fig):\n import plotly\n\n return isinstance(fig, plotly.graph_objects.Figure)\n\n with self._log_artifact_helper(run_id, artifact_file) as tmp_path:\n # `is_matplotlib_figure` is executed only when `matplotlib` is found in `sys.modules`.\n # This allows logging a `plotly` figure in an environment where `matplotlib` is not\n # installed.\n if \"matplotlib\" in sys.modules and _is_matplotlib_figure(figure):\n figure.savefig(tmp_path)\n elif \"plotly\" in sys.modules and _is_plotly_figure(figure):\n figure.write_html(tmp_path, include_plotlyjs=\"cdn\", auto_open=False)\n else:\n raise TypeError(\"Unsupported figure object type: '{}'\".format(type(figure)))\n\n @experimental\n def log_image(\n self, run_id: str, image: Union[\"numpy.ndarray\", \"PIL.Image.Image\"], artifact_file: str\n ) -> None:\n \"\"\"\n Log an image as an artifact. The following image objects are supported:\n\n - `numpy.ndarray`_\n - `PIL.Image.Image`_\n\n .. _numpy.ndarray:\n https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html\n\n .. _PIL.Image.Image:\n https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image\n\n Numpy array support\n - data type (( ) represents a valid value range):\n\n - bool\n - integer (0 ~ 255)\n - unsigned integer (0 ~ 255)\n - float (0.0 ~ 1.0)\n\n .. warning::\n\n - Out-of-range integer values will be **clipped** to [0, 255].\n - Out-of-range float values will be **clipped** to [0, 1].\n\n - shape (H: height, W: width):\n\n - H x W (Grayscale)\n - H x W x 1 (Grayscale)\n - H x W x 3 (an RGB channel order is assumed)\n - H x W x 4 (an RGBA channel order is assumed)\n\n :param run_id: String ID of the run.\n :param image: Image to log.\n :param artifact_file: The run-relative artifact file path in posixpath format to which\n the image is saved (e.g. \"dir/image.png\").\n\n .. code-block:: python\n :caption: Numpy Example\n\n import mlflow\n import numpy as np\n\n image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)\n\n run = client.create_run(experiment_id=\"0\")\n client.log_image(run.info.run_id, image, \"image.png\")\n\n .. code-block:: python\n :caption: Pillow Example\n\n import mlflow\n from PIL import Image\n\n image = Image.new(\"RGB\", (100, 100))\n\n run = client.create_run(experiment_id=\"0\")\n client.log_image(run.info.run_id, image, \"image.png\")\n \"\"\"\n\n def _is_pillow_image(image):\n from PIL.Image import Image\n\n return isinstance(image, Image)\n\n def _is_numpy_array(image):\n import numpy as np\n\n return isinstance(image, np.ndarray)\n\n def _normalize_to_uint8(x):\n # Based on: https://github.com/matplotlib/matplotlib/blob/06567e021f21be046b6d6dcf00380c1cb9adaf3c/lib/matplotlib/image.py#L684 # noqa\n\n is_int = np.issubdtype(x.dtype, np.integer)\n low = 0\n high = 255 if is_int else 1\n if x.min() < low or x.max() > high:\n msg = (\n \"Out-of-range values are detected. \"\n \"Clipping array (dtype: '{}') to [{}, {}]\".format(x.dtype, low, high)\n )\n _logger.warning(msg)\n x = np.clip(x, low, high)\n\n # float or bool\n if not is_int:\n x = x * 255\n\n return x.astype(np.uint8)\n\n with self._log_artifact_helper(run_id, artifact_file) as tmp_path:\n if \"PIL\" in sys.modules and _is_pillow_image(image):\n image.save(tmp_path)\n elif \"numpy\" in sys.modules and _is_numpy_array(image):\n import numpy as np\n\n try:\n from PIL import Image\n except ImportError as exc:\n raise ImportError(\n \"`log_image` requires Pillow to serialize a numpy array as an image.\"\n \"Please install it via: pip install Pillow\"\n ) from exc\n\n # Ref.: https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html#numpy-dtype-kind # noqa\n valid_data_types = {\n \"b\": \"bool\",\n \"i\": \"signed integer\",\n \"u\": \"unsigned integer\",\n \"f\": \"floating\",\n }\n\n if image.dtype.kind not in valid_data_types.keys():\n raise TypeError(\n \"Invalid array data type: '{}'. Must be one of {}\".format(\n image.dtype, list(valid_data_types.values())\n )\n )\n\n if image.ndim not in [2, 3]:\n raise ValueError(\n \"`image` must be a 2D or 3D array but got a {}D array\".format(image.ndim)\n )\n\n if (image.ndim == 3) and (image.shape[2] not in [1, 3, 4]):\n raise ValueError(\n \"Invalid channel length: {}. Must be one of [1, 3, 4]\".format(\n image.shape[2]\n )\n )\n\n # squeeze a 3D grayscale image since `Image.fromarray` doesn't accept it.\n if image.ndim == 3 and image.shape[2] == 1:\n image = image[:, :, 0]\n\n image = _normalize_to_uint8(image)\n\n Image.fromarray(image).save(tmp_path)\n\n else:\n raise TypeError(\"Unsupported image object type: '{}'\".format(type(image)))\n\n def _record_logged_model(self, run_id, mlflow_model):\n \"\"\"\n Record logged model info with the tracking server.\n\n :param run_id: run_id under which the model has been logged.\n :param mlflow_model: Model info to be recorded.\n \"\"\"\n self._tracking_client._record_logged_model(run_id, mlflow_model)\n\n def list_artifacts(self, run_id: str, path=None) -> List[FileInfo]:\n \"\"\"\n List the artifacts for a run.\n\n :param run_id: The run to list artifacts from.\n :param path: The run's relative artifact path to list from. By default it is set to None\n or the root artifact path.\n :return: List of :py:class:`mlflow.entities.FileInfo`\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_artifact_info(artifact):\n print(\"artifact: {}\".format(artifact.path))\n print(\"is_dir: {}\".format(artifact.is_dir))\n print(\"size: {}\".format(artifact.file_size))\n\n features = \"rooms zipcode, median_price, school_rating, transport\"\n labels = \"price\"\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n\n # Create some artifacts and log under the above run\n for file, content in [(\"features\", features), (\"labels\", labels)]:\n with open(\"{}.txt\".format(file), 'w') as f:\n f.write(content)\n client.log_artifact(run.info.run_id, \"{}.txt\".format(file))\n\n # Fetch the logged artifacts\n artifacts = client.list_artifacts(run.info.run_id)\n for artifact in artifacts:\n print_artifact_info(artifact)\n client.set_terminated(run.info.run_id)\n\n .. code-block:: text\n :caption: Output\n\n artifact: features.txt\n is_dir: False\n size: 53\n artifact: labels.txt\n is_dir: False\n size: 5\n \"\"\"\n return self._tracking_client.list_artifacts(run_id, path)\n\n def download_artifacts(self, run_id: str, path: str, dst_path: Optional[str] = None) -> str:\n \"\"\"\n Download an artifact file or directory from a run to a local directory if applicable,\n and return a local path for it.\n\n :param run_id: The run to download artifacts from.\n :param path: Relative source path to the desired artifact.\n :param dst_path: Absolute path of the local filesystem destination directory to which to\n download the specified artifacts. This directory must already exist.\n If unspecified, the artifacts will either be downloaded to a new\n uniquely-named directory on the local filesystem or will be returned\n directly in the case of the LocalArtifactRepository.\n :return: Local path of desired artifact.\n\n .. code-block:: python\n :caption: Example\n\n import os\n import mlflow\n from mlflow.tracking import MlflowClient\n\n features = \"rooms, zipcode, median_price, school_rating, transport\"\n with open(\"features.txt\", 'w') as f:\n f.write(features)\n\n # Log artifacts\n with mlflow.start_run() as run:\n mlflow.log_artifact(\"features.txt\", artifact_path=\"features\")\n\n # Download artifacts\n client = MlflowClient()\n local_dir = \"/tmp/artifact_downloads\"\n if not os.path.exists(local_dir):\n os.mkdir(local_dir)\n local_path = client.download_artifacts(run.info.run_id, \"features\", local_dir)\n print(\"Artifacts downloaded in: {}\".format(local_path))\n print(\"Artifacts: {}\".format(os.listdir(local_path)))\n\n .. code-block:: text\n :caption: Output\n\n Artifacts downloaded in: /tmp/artifact_downloads/features\n Artifacts: ['features.txt']\n \"\"\"\n return self._tracking_client.download_artifacts(run_id, path, dst_path)\n\n def set_terminated(\n self, run_id: str, status: Optional[str] = None, end_time: Optional[int] = None\n ) -> None:\n \"\"\"Set a run's status to terminated.\n\n :param status: A string value of :py:class:`mlflow.entities.RunStatus`.\n Defaults to \"FINISHED\".\n :param end_time: If not provided, defaults to the current time.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n def print_run_info(r):\n print(\"run_id: {}\".format(r.info.run_id))\n print(\"status: {}\".format(r.info.status))\n\n # Create a run under the default experiment (whose id is '0').\n # Since this is low-level CRUD operation, this method will create a run.\n # To end the run, you'll have to explicitly terminate it.\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n print_run_info(run)\n print(\"--\")\n\n # Terminate the run and fetch updated status. By default,\n # the status is set to \"FINISHED\". Other values you can\n # set are \"KILLED\", \"FAILED\", \"RUNNING\", or \"SCHEDULED\".\n client.set_terminated(run.info.run_id, status=\"KILLED\")\n run = client.get_run(run.info.run_id)\n print_run_info(run)\n\n .. code-block:: text\n :caption: Output\n\n run_id: 575fb62af83f469e84806aee24945973\n status: RUNNING\n --\n run_id: 575fb62af83f469e84806aee24945973\n status: KILLED\n \"\"\"\n self._tracking_client.set_terminated(run_id, status, end_time)\n\n def delete_run(self, run_id: str) -> None:\n \"\"\"Deletes a run with the given ID.\n\n :param run_id: The unique run id to delete.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n run_id = run.info.run_id\n print(\"run_id: {}; lifecycle_stage: {}\".format(run_id, run.info.lifecycle_stage))\n print(\"--\")\n client.delete_run(run_id)\n del_run = client.get_run(run_id)\n print(\"run_id: {}; lifecycle_stage: {}\".format(run_id, del_run.info.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n run_id: a61c7a1851324f7094e8d5014c58c8c8; lifecycle_stage: active\n run_id: a61c7a1851324f7094e8d5014c58c8c8; lifecycle_stage: deleted\n \"\"\"\n self._tracking_client.delete_run(run_id)\n\n def restore_run(self, run_id: str) -> None:\n \"\"\"\n Restores a deleted run with the given ID.\n\n :param run_id: The unique run id to restore.\n\n .. code-block:: python\n :caption: Example\n\n from mlflow.tracking import MlflowClient\n\n # Create a run under the default experiment (whose id is '0').\n client = MlflowClient()\n experiment_id = \"0\"\n run = client.create_run(experiment_id)\n run_id = run.info.run_id\n print(\"run_id: {}; lifecycle_stage: {}\".format(run_id, run.info.lifecycle_stage))\n client.delete_run(run_id)\n del_run = client.get_run(run_id)\n print(\"run_id: {}; lifecycle_stage: {}\".format(run_id, del_run.info.lifecycle_stage))\n client.restore_run(run_id)\n rest_run = client.get_run(run_id)\n print(\"run_id: {}; lifecycle_stage: {}\".format(run_id, res_run.info.lifecycle_stage))\n\n .. code-block:: text\n :caption: Output\n\n run_id: 7bc59754d7e74534a7917d62f2873ac0; lifecycle_stage: active\n run_id: 7bc59754d7e74534a7917d62f2873ac0; lifecycle_stage: deleted\n run_id: 7bc59754d7e74534a7917d62f2873ac0; lifecycle_stage: active\n \"\"\"\n self._tracking_client.restore_run(run_id)\n\n def search_runs(\n self,\n experiment_ids: List[str],\n filter_string: str = \"\",\n run_view_type: int = ViewType.ACTIVE_ONLY,\n max_results: int = SEARCH_MAX_RESULTS_DEFAULT,\n order_by: Optional[List[str]] = None,\n page_token: Optional[str] = None,\n ) -> PagedList[Run]:\n \"\"\"\n Search experiments that fit the search criteria.\n\n :param experiment_ids: List of experiment IDs, or a single int or string id.\n :param filter_string: Filter query string, defaults to searching all runs.\n :param run_view_type: one of enum values ACTIVE_ONLY, DELETED_ONLY, or ALL runs\n defined in :py:class:`mlflow.entities.ViewType`.\n :param max_results: Maximum number of runs desired.\n :param order_by: List of columns to order by (e.g., \"metrics.rmse\"). The ``order_by`` column\n can contain an optional ``DESC`` or ``ASC`` value. The default is ``ASC``.\n The default ordering is to sort by ``start_time DESC``, then ``run_id``.\n :param page_token: Token specifying the next page of results. It should be obtained from\n a ``search_runs`` call.\n\n :return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of\n :py:class:`Run <mlflow.entities.Run>` objects that satisfy the search expressions.\n If the underlying tracking store supports pagination, the token for the next page may\n be obtained via the ``token`` attribute of the returned object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n from mlflow.entities import ViewType\n\n def print_run_info(runs):\n for r in runs:\n print(\"run_id: {}\".format(r.info.run_id))\n print(\"lifecycle_stage: {}\".format(r.info.lifecycle_stage))\n print(\"metrics: {}\".format(r.data.metrics))\n\n # Exclude mlflow system tags\n tags = {k: v for k, v in r.data.tags.items() if not k.startswith(\"mlflow.\")}\n print(\"tags: {}\".format(tags))\n\n # Create an experiment and log two runs with metrics and tags under the experiment\n experiment_id = mlflow.create_experiment(\"Social NLP Experiments\")\n with mlflow.start_run(experiment_id=experiment_id) as run:\n mlflow.log_metric(\"m\", 1.55)\n mlflow.set_tag(\"s.release\", \"1.1.0-RC\")\n with mlflow.start_run(experiment_id=experiment_id):\n mlflow.log_metric(\"m\", 2.50)\n mlflow.set_tag(\"s.release\", \"1.2.0-GA\")\n\n # Search all runs under experiment id and order them by\n # descending value of the metric 'm'\n client = MlflowClient()\n runs = client.search_runs(experiment_id, order_by=[\"metrics.m DESC\"])\n print_run_info(runs)\n print(\"--\")\n\n # Delete the first run\n client.delete_run(run_id=run.info.run_id)\n\n # Search only deleted runs under the experiment id and use a case insensitive pattern\n # in the filter_string for the tag.\n filter_string = \"tags.s.release ILIKE '%rc%'\"\n runs = client.search_runs(experiment_id, run_view_type=ViewType.DELETED_ONLY,\n filter_string=filter_string)\n print_run_info(runs)\n\n .. code-block:: text\n :caption: Output\n\n run_id: 0efb2a68833d4ee7860a964fad31cb3f\n lifecycle_stage: active\n metrics: {'m': 2.5}\n tags: {'s.release': '1.2.0-GA'}\n run_id: 7ab027fd72ee4527a5ec5eafebb923b8\n lifecycle_stage: active\n metrics: {'m': 1.55}\n tags: {'s.release': '1.1.0-RC'}\n --\n run_id: 7ab027fd72ee4527a5ec5eafebb923b8\n lifecycle_stage: deleted\n metrics: {'m': 1.55}\n tags: {'s.release': '1.1.0-RC'}\n \"\"\"\n return self._tracking_client.search_runs(\n experiment_ids, filter_string, run_view_type, max_results, order_by, page_token\n )\n\n # Registry API\n\n # Registered Model Methods\n\n def create_registered_model(\n self, name: str, tags: Optional[Dict[str, Any]] = None, description: Optional[str] = None\n ) -> RegisteredModel:\n \"\"\"\n Create a new registered model in backend store.\n\n :param name: Name of the new model. This is expected to be unique in the backend store.\n :param tags: A dictionary of key-value pairs that are converted into\n :py:class:`mlflow.entities.model_registry.RegisteredModelTag` objects.\n :param description: Description of the model.\n :return: A single object of :py:class:`mlflow.entities.model_registry.RegisteredModel`\n created by backend.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_registered_model_info(rm):\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n print(\"description: {}\".format(rm.description))\n\n name = \"SocialMediaTextAnalyzer\"\n tags = {\"nlp.framework\": \"Spark NLP\"}\n desc = \"This sentiment analysis model classifies the tone-happy, sad, angry.\"\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n client.create_registered_model(name, tags, desc)\n print_registered_model_info(client.get_registered_model(name))\n\n .. code-block:: text\n :caption: Output\n\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies the tone-happy, sad, angry.\n \"\"\"\n return self._get_registry_client().create_registered_model(name, tags, description)\n\n def rename_registered_model(self, name: str, new_name: str) -> RegisteredModel:\n \"\"\"\n Update registered model name.\n\n :param name: Name of the registered model to update.\n :param new_name: New proposed name for the registered model.\n\n :return: A single updated :py:class:`mlflow.entities.model_registry.RegisteredModel` object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_registered_model_info(rm):\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n print(\"description: {}\".format(rm.description))\n\n name = \"SocialTextAnalyzer\"\n tags = {\"nlp.framework\": \"Spark NLP\"}\n desc = \"This sentiment analysis model classifies the tone-happy, sad, angry.\"\n\n # create a new registered model name\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n client.create_registered_model(name, tags, desc)\n print_registered_model_info(client.get_registered_model(name))\n print(\"--\")\n\n # rename the model\n new_name = \"SocialMediaTextAnalyzer\"\n client.rename_registered_model(name, new_name)\n print_registered_model_info(client.get_registered_model(new_name))\n\n .. code-block:: python\n :caption: Output\n\n name: SocialTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies the tone-happy, sad, angry.\n --\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies the tone-happy, sad, angry.\n \"\"\"\n self._get_registry_client().rename_registered_model(name, new_name)\n\n def update_registered_model(\n self, name: str, description: Optional[str] = None\n ) -> RegisteredModel:\n \"\"\"\n Updates metadata for RegisteredModel entity. Input field ``description`` should be non-None.\n Backend raises exception if a registered model with given name does not exist.\n\n :param name: Name of the registered model to update.\n :param description: (Optional) New description.\n :return: A single updated :py:class:`mlflow.entities.model_registry.RegisteredModel` object.\n\n .. code-block:: python\n :caption: Example\n\n def print_registered_model_info(rm):\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n print(\"description: {}\".format(rm.description))\n\n name = \"SocialMediaTextAnalyzer\"\n tags = {\"nlp.framework\": \"Spark NLP\"}\n desc = \"This sentiment analysis model classifies the tone-happy, sad, angry.\"\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n client.create_registered_model(name, tags, desc)\n print_registered_model_info(client.get_registered_model(name))\n print(\"--\")\n\n # Update the model's description\n desc = \"This sentiment analysis model classifies tweets' tone: happy, sad, angry.\"\n client.update_registered_model(name, desc)\n print_registered_model_info(client.get_registered_model(name))\n\n .. code-block:: text\n :caption: Output\n\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies the tone-happy, sad, angry.\n --\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies tweets' tone: happy, sad, angry.\n \"\"\"\n if description is None:\n raise MlflowException(\"Attempting to update registered model with no new field values.\")\n\n return self._get_registry_client().update_registered_model(\n name=name, description=description\n )\n\n def delete_registered_model(self, name: str):\n \"\"\"\n Delete registered model.\n Backend raises exception if a registered model with given name does not exist.\n\n :param name: Name of the registered model to update.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_registered_models_info(r_models):\n print(\"--\")\n for rm in r_models:\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n print(\"description: {}\".format(rm.description))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n\n # Register a couple of models with respective names, tags, and descriptions\n for name, tags, desc in [(\"name1\", {\"t1\": \"t1\"}, 'description1'),\n (\"name2\", {\"t2\": \"t2\"}, 'description2')]:\n client.create_registered_model(name, tags, desc)\n\n # Fetch all registered models\n print_registered_models_info(client.list_registered_models())\n\n # Delete one registered model and fetch again\n client.delete_registered_model(\"name1\")\n print_registered_models_info(client.list_registered_models())\n\n .. code-block:: text\n :caption: Output\n\n --\n name: name1\n tags: {'t1': 't1'}\n description: description1\n name: name2\n tags: {'t2': 't2'}\n description: description2\n --\n name: name2\n tags: {'t2': 't2'}\n description: description2\n \"\"\"\n self._get_registry_client().delete_registered_model(name)\n\n def list_registered_models(\n self,\n max_results: int = SEARCH_REGISTERED_MODEL_MAX_RESULTS_DEFAULT,\n page_token: Optional[str] = None,\n ) -> PagedList[RegisteredModel]:\n \"\"\"\n List of all registered models\n\n :param max_results: Maximum number of registered models desired.\n :param page_token: Token specifying the next page of results. It should be obtained from\n a ``list_registered_models`` call.\n :return: A PagedList of :py:class:`mlflow.entities.model_registry.RegisteredModel` objects\n that can satisfy the search expressions. The pagination token for the next page\n can be obtained via the ``token`` attribute of the object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_model_info(models):\n for m in models:\n print(\"--\")\n print(\"name: {}\".format(m.name))\n print(\"tags: {}\".format(m.tags))\n print(\"description: {}\".format(m.description))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n\n # Register a couple of models with respective names, tags, and descriptions\n for name, tags, desc in [(\"name1\", {\"t1\": \"t1\"}, 'description1'),\n (\"name2\", {\"t2\": \"t2\"}, 'description2')]:\n client.create_registered_model(name, tags, desc)\n\n # Fetch all registered models\n print_model_info(client.list_registered_models())\n\n .. code-block:: text\n :caption: Output\n\n --\n name: name1\n tags: {'t1': 't1'}\n description: description1\n --\n name: name2\n tags: {'t2': 't2'}\n description: description2\n \"\"\"\n return self._get_registry_client().list_registered_models(max_results, page_token)\n\n def search_registered_models(\n self,\n filter_string: Optional[str] = None,\n max_results: int = SEARCH_REGISTERED_MODEL_MAX_RESULTS_DEFAULT,\n order_by: Optional[List[str]] = None,\n page_token: Optional[str] = None,\n ) -> PagedList[RegisteredModel]:\n \"\"\"\n Search for registered models in backend that satisfy the filter criteria.\n\n :param filter_string: Filter query string, defaults to searching all registered\n models. Currently, it supports only a single filter condition as the name\n of the model, for example, ``name = 'model_name'`` or a search expression\n to match a pattern in the registered model name.\n For example, ``name LIKE 'Boston%'`` (case sensitive) or\n ``name ILIKE '%boston%'`` (case insensitive).\n :param max_results: Maximum number of registered models desired.\n :param order_by: List of column names with ASC|DESC annotation, to be used for ordering\n matching search results.\n :param page_token: Token specifying the next page of results. It should be obtained from\n a ``search_registered_models`` call.\n :return: A PagedList of :py:class:`mlflow.entities.model_registry.RegisteredModel` objects\n that satisfy the search expressions. The pagination token for the next page can be\n obtained via the ``token`` attribute of the object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n client = MlflowClient()\n\n # Get search results filtered by the registered model name\n model_name=\"CordobaWeatherForecastModel\"\n filter_string = \"name='{}'\".format(model_name)\n results = client.search_registered_models(filter_string=filter_string)\n print(\"-\" * 80)\n for res in results:\n for mv in res.latest_versions:\n print(\"name={}; run_id={}; version={}\".format(mv.name, mv.run_id, mv.version))\n\n # Get search results filtered by the registered model name that matches\n # prefix pattern\n filter_string = \"name LIKE 'Boston%'\"\n results = client.search_registered_models(filter_string=filter_string)\n for res in results:\n for mv in res.latest_versions:\n print(\"name={}; run_id={}; version={}\".format(mv.name, mv.run_id, mv.version))\n\n # Get all registered models and order them by ascending order of the names\n results = client.search_registered_models(order_by=[\"name ASC\"])\n print(\"-\" * 80)\n for res in results:\n for mv in res.latest_versions:\n print(\"name={}; run_id={}; version={}\".format(mv.name, mv.run_id, mv.version))\n\n .. code-block:: text\n :caption: Output\n\n ------------------------------------------------------------------------------------\n name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1\n name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2\n ------------------------------------------------------------------------------------\n name=BostonWeatherForecastModel; run_id=ddc51b9407a54b2bb795c8d680e63ff6; version=1\n name=BostonWeatherForecastModel; run_id=48ac94350fba40639a993e1b3d4c185d; version=2\n -----------------------------------------------------------------------------------\n name=AzureWeatherForecastModel; run_id=5fcec6c4f1c947fc9295fef3fa21e52d; version=1\n name=AzureWeatherForecastModel; run_id=8198cb997692417abcdeb62e99052260; version=3\n name=BostonWeatherForecastModel; run_id=ddc51b9407a54b2bb795c8d680e63ff6; version=1\n name=BostonWeatherForecastModel; run_id=48ac94350fba40639a993e1b3d4c185d; version=2\n name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1\n name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2\n\n \"\"\"\n return self._get_registry_client().search_registered_models(\n filter_string, max_results, order_by, page_token\n )\n\n def get_registered_model(self, name: str) -> RegisteredModel:\n \"\"\"\n :param name: Name of the registered model to update.\n :return: A single :py:class:`mlflow.entities.model_registry.RegisteredModel` object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_model_info(rm):\n print(\"--\")\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n print(\"description: {}\".format(rm.description))\n\n name = \"SocialMediaTextAnalyzer\"\n tags = {\"nlp.framework\": \"Spark NLP\"}\n desc = \"This sentiment analysis model classifies the tone-happy, sad, angry.\"\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n\n # Create and fetch the registered model\n client.create_registered_model(name, tags, desc)\n model = client.get_registered_model(name)\n print_model_info(model)\n\n .. code-block:: text\n :caption: Output\n\n --\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework': 'Spark NLP'}\n description: This sentiment analysis model classifies the tone-happy, sad, angry.\n \"\"\"\n return self._get_registry_client().get_registered_model(name)\n\n def get_latest_versions(self, name: str, stages: List[str] = None) -> ModelVersion:\n \"\"\"\n Latest version models for each requests stage. If no ``stages`` provided, returns the\n latest version for each stage.\n\n :param name: Name of the registered model to update.\n :param stages: List of desired stages. If input list is None, return latest versions for\n for ALL_STAGES.\n :return: List of :py:class:`mlflow.entities.model_registry.ModelVersion` objects.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_models_info(mv):\n for m in mv:\n print(\"name: {}\".format(m.name))\n print(\"latest version: {}\".format(m.version))\n print(\"run_id: {}\".format(m.run_id))\n print(\"current_stage: {}\".format(m.current_stage))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n\n # Create two runs Log MLflow entities\n with mlflow.start_run() as run1:\n params = {\"n_estimators\": 3, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n with mlflow.start_run() as run2:\n params = {\"n_estimators\": 6, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n name = \"RandomForestRegression\"\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a two versions of the rfr model under the registered model name\n for run_id in [run1.info.run_id, run2.info.run_id]:\n model_uri = \"runs:/{}/sklearn-model\".format(run_id)\n mv = client.create_model_version(name, model_uri, run_id)\n print(\"model version {} created\".format(mv.version))\n\n # Fetch latest version; this will be version 2\n print(\"--\")\n print_models_info(client.get_latest_versions(name, stages=[\"None\"]))\n\n .. code-block:: text\n :caption: Output\n\n model version 1 created\n model version 2 created\n --\n name: RandomForestRegression\n latest version: 2\n run_id: 31165664be034dc698c52a4bdeb71663\n current_stage: None\n \"\"\"\n return self._get_registry_client().get_latest_versions(name, stages)\n\n def set_registered_model_tag(self, name, key, value) -> None:\n \"\"\"\n Set a tag for the registered model.\n\n :param name: Registered model name.\n :param key: Tag key to log.\n :param value: Tag value log.\n :return: None\n\n .. code-block:: Python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_model_info(rm):\n print(\"--\")\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n\n name = \"SocialMediaTextAnalyzer\"\n tags = {\"nlp.framework1\": \"Spark NLP\"}\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n\n # Create registered model, set an additional tag, and fetch\n # update model info\n client.create_registered_model(name, tags, desc)\n model = client.get_registered_model(name)\n print_model_info(model)\n\n client.set_registered_model_tag(name, \"nlp.framework2\", \"VADER\")\n model = client.get_registered_model(name)\n print_model_info(model)\n\n .. code-block:: text\n :caption: Output\n\n --\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework1': 'Spark NLP'}\n --\n name: SocialMediaTextAnalyzer\n tags: {'nlp.framework1': 'Spark NLP', 'nlp.framework2': 'VADER'}\n \"\"\"\n self._get_registry_client().set_registered_model_tag(name, key, value)\n\n def delete_registered_model_tag(self, name: str, key: str) -> None:\n \"\"\"\n Delete a tag associated with the registered model.\n\n :param name: Registered model name.\n :param key: Registered model tag key.\n :return: None\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n def print_registered_models_info(r_models):\n print(\"--\")\n for rm in r_models:\n print(\"name: {}\".format(rm.name))\n print(\"tags: {}\".format(rm.tags))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n client = MlflowClient()\n\n # Register a couple of models with respective names and tags\n for name, tags in [(\"name1\", {\"t1\": \"t1\"}),(\"name2\", {\"t2\": \"t2\"})]:\n client.create_registered_model(name, tags)\n\n # Fetch all registered models\n print_registered_models_info(client.list_registered_models())\n\n # Delete a tag from model `name2`\n client.delete_registered_model_tag(\"name2\", 't2')\n print_registered_models_info(client.list_registered_models())\n\n .. code-block:: text\n :caption: Output\n\n --\n name: name1\n tags: {'t1': 't1'}\n name: name2\n tags: {'t2': 't2'}\n --\n name: name1\n tags: {'t1': 't1'}\n name: name2\n tags: {}\n \"\"\"\n self._get_registry_client().delete_registered_model_tag(name, key)\n\n # Model Version Methods\n\n def create_model_version(\n self,\n name: str,\n source: str,\n run_id: Optional[str] = None,\n tags: Optional[Dict[str, Any]] = None,\n run_link: Optional[str] = None,\n description: Optional[str] = None,\n await_creation_for: int = DEFAULT_AWAIT_MAX_SLEEP_SECONDS,\n ) -> ModelVersion:\n \"\"\"\n Create a new model version from given source (artifact URI).\n\n :param name: Name for the containing registered model.\n :param source: Source path where the MLflow model is stored.\n :param run_id: Run ID from MLflow tracking server that generated the model\n :param tags: A dictionary of key-value pairs that are converted into\n :py:class:`mlflow.entities.model_registry.ModelVersionTag` objects.\n :param run_link: Link to the run from an MLflow tracking server that generated this model.\n :param description: Description of the version.\n :param await_creation_for: Number of seconds to wait for the model version to finish being\n created and is in ``READY`` status. By default, the function\n waits for five minutes. Specify 0 or None to skip waiting.\n :return: Single :py:class:`mlflow.entities.model_registry.ModelVersion` object created by\n backend.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n desc = \"A new version of the model\"\n model_uri = \"runs:/{}/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id, description=desc)\n print(\"Name: {}\".format(mv.name))\n print(\"Version: {}\".format(mv.version))\n print(\"Description: {}\".format(mv.description))\n print(\"Status: {}\".format(mv.status))\n print(\"Stage: {}\".format(mv.current_stage))\n\n .. code-block:: text\n :caption: Output\n\n Name: RandomForestRegression\n Version: 1\n Description: A new version of the model\n Status: READY\n Stage: None\n \"\"\"\n tracking_uri = self._tracking_client.tracking_uri\n if not run_link and is_databricks_uri(tracking_uri) and tracking_uri != self._registry_uri:\n if not run_id:\n eprint(\n \"Warning: no run_link will be recorded with the model version \"\n \"because no run_id was given\"\n )\n else:\n run_link = self._get_run_link(tracking_uri, run_id)\n new_source = source\n if is_databricks_uri(self._registry_uri) and tracking_uri != self._registry_uri:\n # Print out some info for user since the copy may take a while for large models.\n eprint(\n \"=== Copying model files from the source location to the model\"\n + \" registry workspace ===\"\n )\n new_source = _upload_artifacts_to_databricks(\n source, run_id, tracking_uri, self._registry_uri\n )\n # NOTE: we can't easily delete the target temp location due to the async nature\n # of the model version creation - printing to let the user know.\n eprint(\n \"=== Source model files were copied to %s\" % new_source\n + \" in the model registry workspace. You may want to delete the files once the\"\n + \" model version is in 'READY' status. You can also find this location in the\"\n + \" `source` field of the created model version. ===\"\n )\n return self._get_registry_client().create_model_version(\n name=name,\n source=new_source,\n run_id=run_id,\n tags=tags,\n run_link=run_link,\n description=description,\n await_creation_for=await_creation_for,\n )\n\n def _get_run_link(self, tracking_uri, run_id):\n # if using the default Databricks tracking URI and in a notebook, we can automatically\n # figure out the run-link.\n if is_databricks_default_tracking_uri(tracking_uri) and (\n is_in_databricks_notebook() or is_in_databricks_job()\n ):\n # use DBUtils to determine workspace information.\n workspace_host, workspace_id = get_workspace_info_from_dbutils()\n else:\n # in this scenario, we're not able to automatically extract the workspace ID\n # to proceed, and users will need to pass in a databricks profile with the scheme:\n # databricks://scope:prefix and store the host and workspace-ID as a secret in the\n # Databricks Secret Manager with scope=<scope> and key=<prefix>-workspaceid.\n workspace_host, workspace_id = get_workspace_info_from_databricks_secrets(tracking_uri)\n if not workspace_id:\n print(\n \"No workspace ID specified; if your Databricks workspaces share the same\"\n \" host URL, you may want to specify the workspace ID (along with the host\"\n \" information in the secret manager) for run lineage tracking. For more\"\n \" details on how to specify this information in the secret manager,\"\n \" please refer to the model registry documentation.\"\n )\n # retrieve experiment ID of the run for the URL\n experiment_id = self.get_run(run_id).info.experiment_id\n if workspace_host and run_id and experiment_id:\n return construct_run_url(workspace_host, experiment_id, run_id, workspace_id)\n\n def update_model_version(\n self, name: str, version: str, description: Optional[str] = None\n ) -> ModelVersion:\n \"\"\"\n Update metadata associated with a model version in backend.\n\n :param name: Name of the containing registered model.\n :param version: Version number of the model version.\n :param description: New description.\n\n :return: A single :py:class:`mlflow.entities.model_registry.ModelVersion` object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_model_version_info(mv):\n print(\"Name: {}\".format(mv.name))\n print(\"Version: {}\".format(mv.version))\n print(\"Description: {}\".format(mv.description))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n model_uri = \"runs:/{}/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id)\n print_model_version_info(mv)\n print(\"--\")\n\n # Update model version's description\n desc = \"A new version of the model using ensemble trees\"\n mv = client.update_model_version(name, mv.version, desc)\n print_model_version_info(mv)\n\n .. code-block:: text\n :caption: Output\n\n Name: RandomForestRegression\n Version: 1\n Description: None\n --\n Name: RandomForestRegression\n Version: 1\n Description: A new version of the model using ensemble trees\n \"\"\"\n if description is None:\n raise MlflowException(\"Attempting to update model version with no new field values.\")\n\n return self._get_registry_client().update_model_version(\n name=name, version=version, description=description\n )\n\n def transition_model_version_stage(\n self, name: str, version: str, stage: str, archive_existing_versions: bool = False\n ) -> ModelVersion:\n \"\"\"\n Update model version stage.\n\n :param name: Registered model name.\n :param version: Registered model version.\n :param stage: New desired stage for this model version.\n :param archive_existing_versions: If this flag is set to ``True``, all existing model\n versions in the stage will be automically moved to the \"archived\" stage. Only valid\n when ``stage`` is ``\"staging\"`` or ``\"production\"`` otherwise an error will be raised.\n\n :return: A single :py:class:`mlflow.entities.model_registry.ModelVersion` object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_model_version_info(mv):\n print(\"Name: {}\".format(mv.name))\n print(\"Version: {}\".format(mv.version))\n print(\"Description: {}\".format(mv.description))\n print(\"Stage: {}\".format(mv.current_stage))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n desc = \"A new version of the model using ensemble trees\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n model_uri = \"runs:/{}/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id, description=desc)\n print_model_version_info(mv)\n print(\"--\")\n\n # transition model version from None -> staging\n mv = client.transition_model_version_stage(name, mv.version, \"staging\")\n print_model_version_info(mv)\n\n .. code-block:: text\n :caption: Output\n\n Name: RandomForestRegression\n Version: 1\n Description: A new version of the model using ensemble trees\n Stage: None\n --\n Name: RandomForestRegression\n Version: 1\n Description: A new version of the model using ensemble trees\n Stage: Staging\n \"\"\"\n return self._get_registry_client().transition_model_version_stage(\n name, version, stage, archive_existing_versions\n )\n\n def delete_model_version(self, name: str, version: str) -> None:\n \"\"\"\n Delete model version in backend.\n\n :param name: Name of the containing registered model.\n :param version: Version number of the model version.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_models_info(mv):\n for m in mv:\n print(\"name: {}\".format(m.name))\n print(\"latest version: {}\".format(m.version))\n print(\"run_id: {}\".format(m.run_id))\n print(\"current_stage: {}\".format(m.current_stage))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n\n # Create two runs and log MLflow entities\n with mlflow.start_run() as run1:\n params = {\"n_estimators\": 3, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n with mlflow.start_run() as run2:\n params = {\"n_estimators\": 6, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n name = \"RandomForestRegression\"\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a two versions of the rfr model under the registered model name\n for run_id in [run1.info.run_id, run2.info.run_id]:\n model_uri = \"runs:/{}/sklearn-model\".format(run_id)\n mv = client.create_model_version(name, model_uri, run_id)\n print(\"model version {} created\".format(mv.version))\n\n print(\"--\")\n\n # Fetch latest version; this will be version 2\n models = client.get_latest_versions(name, stages=[\"None\"])\n print_models_info(models)\n print(\"--\")\n\n # Delete the latest model version 2\n print(\"Deleting model version {}\".format(mv.version))\n client.delete_model_version(name, mv.version)\n models = client.get_latest_versions(name, stages=[\"None\"])\n print_models_info(models)\n\n .. code-block:: text\n :caption: Output\n\n model version 1 created\n model version 2 created\n --\n name: RandomForestRegression\n latest version: 2\n run_id: 9881172ef10f4cb08df3ed452c0c362b\n current_stage: None\n --\n Deleting model version 2\n name: RandomForestRegression\n latest version: 1\n run_id: 9165d4f8aa0a4d069550824bdc55caaf\n current_stage: None\n \"\"\"\n self._get_registry_client().delete_model_version(name, version)\n\n def get_model_version(self, name: str, version: str) -> ModelVersion:\n \"\"\"\n :param name: Name of the containing registered model.\n :param version: Version number as an integer of the model version.\n :return: A single :py:class:`mlflow.entities.model_registry.ModelVersion` object.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n # Create two runs Log MLflow entities\n with mlflow.start_run() as run1:\n params = {\"n_estimators\": 3, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n with mlflow.start_run() as run2:\n params = {\"n_estimators\": 6, \"random_state\": 42}\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n name = \"RandomForestRegression\"\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a two versions of the rfr model under the registered model name\n for run_id in [run1.info.run_id, run2.info.run_id]:\n model_uri = \"runs:/{}/sklearn-model\".format(run_id)\n mv = client.create_model_version(name, model_uri, run_id)\n print(\"model version {} created\".format(mv.version))\n print(\"--\")\n\n # Fetch the last version; this will be version 2\n mv = client.get_model_version(name, mv.version)\n print_model_version_info(mv)\n\n .. code-block:: text\n :caption: Output\n\n model version 1 created\n model version 2 created\n --\n Name: RandomForestRegression\n Version: 2\n \"\"\"\n return self._get_registry_client().get_model_version(name, version)\n\n def get_model_version_download_uri(self, name: str, version: str) -> str:\n \"\"\"\n Get the download location in Model Registry for this model version.\n\n :param name: Name of the containing registered model.\n :param version: Version number as an integer of the model version.\n :return: A single URI location that allows reads for downloading.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"models/sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n model_uri = \"runs:/{}/models/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id)\n artifact_uri = client.get_model_version_download_uri(name, mv.version)\n print(\"Download URI: {}\".format(artifact_uri))\n\n .. code-block:: text\n :caption: Output\n\n Download URI: runs:/44e04097ac364cd895f2039eaccca9ac/models/sklearn-model\n \"\"\"\n return self._get_registry_client().get_model_version_download_uri(name, version)\n\n def search_model_versions(self, filter_string: str) -> PagedList[ModelVersion]:\n \"\"\"\n Search for model versions in backend that satisfy the filter criteria.\n\n :param filter_string: A filter string expression. Currently, it supports a single filter\n condition either a name of model like ``name = 'model_name'`` or\n ``run_id = '...'``.\n :return: PagedList of :py:class:`mlflow.entities.model_registry.ModelVersion` objects.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n from mlflow.tracking import MlflowClient\n\n client = MlflowClient()\n\n # Get all versions of the model filtered by name\n model_name = \"CordobaWeatherForecastModel\"\n filter_string = \"name='{}'\".format(model_name)\n results = client.search_model_versions(filter_string)\n print(\"-\" * 80)\n for res in results:\n print(\"name={}; run_id={}; version={}\".format(res.name, res.run_id, res.version))\n\n # Get the version of the model filtered by run_id\n run_id = \"e14afa2f47a040728060c1699968fd43\"\n filter_string = \"run_id='{}'\".format(run_id)\n results = client.search_model_versions(filter_string)\n print(\"-\" * 80)\n for res in results:\n print(\"name={}; run_id={}; version={}\".format(res.name, res.run_id, res.version))\n\n .. code-block:: text\n :caption: Output\n\n ------------------------------------------------------------------------------------\n name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1\n name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2\n ------------------------------------------------------------------------------------\n name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2\n \"\"\"\n return self._get_registry_client().search_model_versions(filter_string)\n\n def get_model_version_stages(\n self, name: str, version: str # pylint: disable=unused-argument\n ) -> List[str]:\n \"\"\"\n :return: A list of valid stages.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"models/sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n # fetch valid stages\n model_uri = \"runs:/{}/models/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id)\n stages = client.get_model_version_stages(name, mv.version)\n print(\"Model list of valid stages: {}\".format(stages))\n\n .. code-block:: text\n :caption: Output\n\n Model list of valid stages: ['None', 'Staging', 'Production', 'Archived']\n \"\"\"\n return ALL_STAGES\n\n def set_model_version_tag(self, name: str, version: str, key: str, value: Any) -> None:\n \"\"\"\n Set a tag for the model version.\n\n :param name: Registered model name.\n :param version: Registered model version.\n :param key: Tag key to log.\n :param value: Tag value to log.\n :return: None\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_model_version_info(mv):\n print(\"Name: {}\".format(mv.name))\n print(\"Version: {}\".format(mv.version))\n print(\"Tags: {}\".format(mv.tags))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n # and set a tag\n model_uri = \"runs:/{}/sklearn-model\".format(run.info.run_id)\n mv = client.create_model_version(name, model_uri, run.info.run_id)\n print_model_version_info(mv)\n print(\"--\")\n client.set_model_version_tag(name, mv.version, \"t\", \"1\")\n mv = client.get_model_version(name, mv.version)\n print_model_version_info(mv)\n\n .. code-block:: text\n :caption: Output\n\n Name: RandomForestRegression\n Version: 1\n Tags: {}\n --\n Name: RandomForestRegression\n Version: 1\n Tags: {'t': '1'}\n \"\"\"\n self._get_registry_client().set_model_version_tag(name, version, key, value)\n\n def delete_model_version_tag(self, name: str, version: str, key: str) -> None:\n \"\"\"\n Delete a tag associated with the model version.\n\n :param name: Registered model name.\n :param version: Registered model version.\n :param key: Tag key.\n :return: None\n\n .. code-block:: python\n :caption: Example\n\n import mlflow.sklearn\n from mlflow.tracking import MlflowClient\n from sklearn.ensemble import RandomForestRegressor\n\n def print_model_version_info(mv):\n print(\"Name: {}\".format(mv.name))\n print(\"Version: {}\".format(mv.version))\n print(\"Tags: {}\".format(mv.tags))\n\n mlflow.set_tracking_uri(\"sqlite:///mlruns.db\")\n params = {\"n_estimators\": 3, \"random_state\": 42}\n name = \"RandomForestRegression\"\n rfr = RandomForestRegressor(**params).fit([[0, 1]], [1])\n\n # Log MLflow entities\n with mlflow.start_run() as run:\n mlflow.log_params(params)\n mlflow.sklearn.log_model(rfr, artifact_path=\"sklearn-model\")\n\n # Register model name in the model registry\n client = MlflowClient()\n client.create_registered_model(name)\n\n # Create a new version of the rfr model under the registered model name\n # and delete a tag\n model_uri = \"runs:/{}/sklearn-model\".format(run.info.run_id)\n tags = {'t': \"t1\"}\n mv = client.create_model_version(name, model_uri, run.info.run_id, tags=tags)\n print_model_version_info(mv)\n print(\"--\")\n client.delete_model_version_tag(name, mv.version, \"t\")\n mv = client.get_model_version(name, mv.version)\n print_model_version_info(mv)\n\n .. code-block:: text\n :caption: Output\n\n Name: RandomForestRegression\n Version: 1\n Tags: {'t': 't1'}\n --\n Name: RandomForestRegression\n Version: 1\n Tags: {}\n \"\"\"\n self._get_registry_client().delete_model_version_tag(name, version, key)\n"
] |
[
[
"numpy.issubdtype",
"numpy.clip"
]
] |
Arnold-n/covid19
|
[
"4d3e5b288418ee40cd8a45f458662c46a22b1b2a"
] |
[
"process_casus_data.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"Script for casus analysis (using functions from casus_analysis.py).\"\"\"\n\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport pandas as pd\nimport numpy as np\nimport casus_analysis as ca\nimport urllib.request\nimport tools\n\ndef get_summary_df(maxageh=1, force_today=False):\n \"\"\"Get summary dataframe with cache handling and csv update.\"\"\"\n\n if ca.download_rivm_casus_files(force_today=force_today):\n # If there is new data, process it.\n # This is a bit slow. Someday, be smarter in merging.\n ca.create_merged_summary_csv()\n\n cache_fname = 'casus_summary_cache.pkl'\n df = ca.load_data_cache(cache_fname, maxageh=maxageh)\n if df is None:\n df = ca.load_merged_summary_csv() # (2020-08-01', '2020-10-01')\n df = ca.add_eDOO_to_summary(df)\n ca.save_data_cache(df, cache_fname)\n print('---snippet from summary dataframe df---')\n print(df)\n\n return df\n\n\ndef demo_dow_prediction(df, doo_corr, f_dow_corr, date_range, dows):\n \"\"\"Demonstrate DoW effect in plots.\n\n Parameters:\n\n - df: summary DataFrame with multi-index and eDOO column.\n - doo_corr: DOOCorrection (doocorr.G_dow_corr will be ignored.)\n - f_dow_corr: file day-of-week correction, (7, m) array.\n - date_range: (start_date, end_date) tuple (refers to Date_statistics).\n - dows: list of DoWs (0=Monday).\n\n This will generate two plots, with and without DoW correction enabled.\n one without. Report dates on selected DoWs will be shown.\n \"\"\"\n\n # Select file dates to plot (based on dows parameter).\n # The one with the final date is for the best case-number values.\n date_range = [pd.Timestamp(d) for d in date_range]\n print('demo_dow_prediction...')\n fdates = df.index.get_level_values('Date_file').unique().sort_values()\n fdates = fdates[(fdates >= date_range[0]) & (fdates <= date_range[1])]\n dows = set(dows)\n fdates_dow = [d for d in fdates if d.dayofweek in dows]\n if fdates_dow[-1] != fdates[-1]:\n fdates_dow.append(fdates[-1])\n\n # build list of dataframes for different file dates.\n df_list = [\n df.loc[fd, :] # result has single index: Date_statistics\n for fd in fdates_dow\n ]\n # trim old entries\n df_list = [\n d.loc[(d.index >= date_range[0]) & (d.index <= date_range[1])]\n for d in df_list\n ]\n\n doo_corr = deepcopy(doo_corr)\n dow_names = 'ma,di,wo,do,vr,za,zo'.split(',')\n dows_str = ', '.join([dow_names[i] for i in sorted(dows)]) # e.g. 'ma, wo'\n dows_str = f'rapportagedag {dows_str}' if len(dows)==1 else f'rapportagedagen {dows_str}'\n\n doo_corr.f_dow_corr[:, :] = 1.0\n doo_corr.plot_nDOO(df_list, title=f'Zonder weekdagcorrectie; {dows_str}')\n\n doo_corr.f_dow_corr[:, :] = f_dow_corr\n doo_corr.plot_nDOO(df_list, title=f'Met weekdagcorrectie; {dows_str}')\n\n\ndef demo_dow_prediction_202010(df):\n \"\"\"Demo DoW correction for OCt 2020, from full summary DataFrame.\"\"\"\n\n # Get DoW statistics (dow_corr)\n date_range_dow = ('2020-10-01', '2020-11-15')\n f_dow_corr = ca.DOOCorrection.calc_fdow_correction(\n df, m=18, date_range=date_range_dow)\n\n # Get and plot DOO correction\n doo_corr = ca.DOOCorrection.from_doo_df(\n df, m=18, f_dow_corr=f_dow_corr)\n doo_corr.plot_fdow_corr()\n\n plt.pause(0.5)\n # Show effect of DoW correction for Monday and Sunday\n for dow in [0, 6]:\n demo_dow_prediction(df, doo_corr, f_dow_corr=f_dow_corr,\n date_range=('2020-07-01', '2020-11-01'),\n dows=[dow])\n plt.pause(0.5)\n\ndef demo_fdow_corr(df, date_range, show=True, fname=None):\n\n f_dow_corr = ca.DOOCorrection.calc_fdow_correction(\n df, m=18, date_range=date_range)\n\n doo_corr = ca.DOOCorrection.from_doo_df(\n df, m=18, f_dow_corr=f_dow_corr)\n\n doo_corr.plot_fdow_corr(show=show, fname=fname)\n\n\ndef demo_prediction(df, m=12, fdate_range=('2020-10-22', '2020-11-21'),\n dow_extra=45, with_dc=True, show=True, fbname=None):\n \"\"\"Demo prediction for Nov 2020, from full summary DataFrame.\n\n Parameters:\n\n - m: number of days to wait until DOO reports are \"final\".\n - fdate_range: date range for calibrating DOOCorrection.\n (last date minus m days is the actual coverage).\n - dow_extra: number of extra days for calculating DoW correction,\n which needs a longer time interval.\n - with_dc: whether to enable DOO correction. Set to False\n to get uncorrected data.\n - show: whether to plot on-screen.\n - fbname: optional file basename (no suffix) for plot output.\n\n Show how well predicitions were in November.\n Correction factors based on data available in Sept/October.\n\n Parameters:\n \"\"\"\n\n fdra_lo = pd.to_datetime(fdate_range[0])\n fdra_hi = pd.to_datetime(fdate_range[1])\n fdra_lodow = fdra_lo - pd.Timedelta(dow_extra, 'd')\n\n # include data from mid-Aug for DoW effocts\n f_dow_corr = ca.DOOCorrection.calc_fdow_correction(\n df, date_range=(fdra_lodow, fdra_hi), m=m)\n s_dow_ce = ca.DOOCorrection.calc_sdow_correction(\n df, date_range=(fdra_lodow, fdra_hi), show=False)\n\n # Use data from mid-Sept for generic correction\n if with_dc:\n doo_corr = ca.DOOCorrection.from_doo_df(\n df, date_range=(fdra_lo, fdra_hi), m=m,\n f_dow_corr=f_dow_corr, s_dow_ce=s_dow_ce\n )\n else:\n doo_corr = ca.DOOCorrection(\n G=np.array([0]*3 + [1.0]*(m-3)),\n eG=np.zeros(m),\n date_range=(fdra_lo, fdra_lo),\n f_dow_corr=np.ones((7, m)),\n s_dow_ce=(np.ones(7), 0.0)\n )\n\n # Go back from today in steps of 4 days.\n fdates = df.index.get_level_values(0).unique().sort_values()\n fdates = fdates[fdates >= fdra_lodow]\n fdates = fdates[-1::-4]\n\n dfs_edoo = [\n df.loc[fdate].loc[fdra_lodow-pd.Timedelta(30, 'd'):]\n for fdate in fdates\n ]\n\n fdra_hi_m = fdra_hi - pd.Timedelta(m, 'd')\n if with_dc:\n title = ('Correctiefactor recente cijfers o.b.v.'\n f' {ca._ymd(fdra_lo)} .. {ca._ymd(fdra_hi_m)}.')\n else:\n title = 'Ruwe data eerste ziektedag.'\n doo_corr.plot_nDOO(dfs_edoo, title=title, show=show,\n fname=(fbname and f'{fbname}_ndoo.pdf'))\n\n if with_dc:\n doo_corr.plot(show=show, fname=f'{fbname}-doo_corr.pdf')\n\n\ndef demo_doo_correction_by_month(df, show=True, fname=None):\n\n dranges = [\n ('2020-07-01', '2020-08-18'),\n ('2020-08-01', '2020-09-18'),\n ('2020-09-01', '2020-10-18'),\n ('2020-10-01', '2020-11-18')\n ]\n\n dcs = [\n ca.DOOCorrection.from_doo_df(df, m=18, date_range=dr)\n for dr in dranges\n ]\n dcs[0].plot(dcs[1:], show=show, fname=fname)\n\ndef demo_sdow(df, fdate_range, m=14, show=True, fbname=None):\n \"\"\"Show statistics DoW effect.\"\"\"\n\n fd0, fd1 = [pd.to_datetime(d) for d in fdate_range]\n day = pd.Timedelta('1 d')\n f_dow_corr = ca.DOOCorrection.calc_fdow_correction(\n df, date_range=fdate_range, m=m)\n s_dow_ce = ca.DOOCorrection.calc_sdow_correction(\n df, date_range=fdate_range, show=show,\n fname=(fbname and f'{fbname}-sdow.png'))\n\n doo_corr = ca.DOOCorrection.from_doo_df(\n df, date_range=fdate_range, m=m,\n f_dow_corr=f_dow_corr, s_dow_ce=s_dow_ce\n )\n\n df_slice = df.loc[(fd1, slice(fd0-m*day, fd1)), :].reset_index(0)\n\n doo_corr.plot_nDOO(df_slice, kind='nDOO', show=show,\n fname=(fbname and f'{fbname}_nDOO.pdf'))\n doo_corr.plot_nDOO(df_slice, kind='ncDOO', show=show,\n fname=(fbname and f'{fbname}_ncDOO.pdf'))\n\ndef demo_corr_recom(df, n=120, m=18, show=True, fbname=None):\n \"\"\"Show recommended correction values based on latest data.\n\n Parameters:\n\n - df: full (multi-index) dataset with eDOO data.\n - n: number of days to go back (file dates)\n - m: number of days for DOO correction to stabilize.\n - fbname: file basename (no suffix) for output.\n \"\"\"\n\n fdates = df.index.get_level_values('Date_file').unique().sort_values()\n fdate_range = (fdates[-n], fdates[-1])\n f_dow_corr = ca.DOOCorrection.calc_fdow_correction(\n df, date_range=fdate_range, m=m)\n s_dow_ce = ca.DOOCorrection.calc_sdow_correction(\n df, date_range=fdate_range, show=False)\n\n doo_corr_bare = ca.DOOCorrection.from_doo_df(\n df, date_range=fdate_range, m=m,\n )\n\n fig, ax = plt.subplots(1, 1, tight_layout=True, figsize=(6, 4))\n ax2 = ax.twinx()\n\n ax.errorbar(np.arange(m), doo_corr_bare.iG, doo_corr_bare.eiG,\n fmt='bo-', capsize=10, label='Correctiefactor 1/G')\n ax2.plot(np.arange(m), 100*doo_corr_bare.eiG/doo_corr_bare.iG,\n 'r^-', label='Relatieve fout (%)')\n # ax.legend()\n ax.set_xlabel('Dagen geleden')\n ax.set_ylabel('Correctiefactor 1/G', color='blue')\n ax2.set_ylabel('Relatieve fout (%)', color='red')\n ax.legend(loc='upper right')\n ax2.legend(loc='center right')\n\n ax.set_ylim(1, 7)\n ax.set_xlim(0, m-0.9)\n ax2.set_ylim(0, 30)\n\n locator = matplotlib.ticker.MaxNLocator(steps=[1, 2, 5])\n ax.xaxis.set_major_locator(locator)\n\n ax.grid()\n ax.set_title(f'O.b.v. DOO {ca._ymd(fdates[-n])} .. {ca._ymd(fdates[-m])}')\n\n ca._show_save_fig(fig, show, (fbname and f'{fbname}_creco.pdf'))\n\ndef demo_fixed_j(df, fdate_range, ages=(5, 9, 14), stats_age=30, m=18, sdow=True,\n show=True, fname=None):\n \"\"\"Demonstrate case trends using fixed DOO ages.\n\n Parameters:\n\n - df: Dataframe with eDOO column and multi-index.\n - fdate_range: (fdate_lo, fdate_hi) tuple.\n - ages: sequence of case ages to consider.\n - stats_age: number of recent fdates not to consider in getting\n correction factors.\n - m: the 'm' parameter as usual.\n - sdow: whether to apply s_dow_corr correction.\n (counterproductive for small age values)\n - show: whether to show plot on-screen.\n - fname: optional filename for writing plot image.\n \"\"\"\n\n # Slice df dataframe to requested\n fdates = df.index.get_level_values('Date_file').unique().sort_values()\n fdates = fdates[(fdates >= fdate_range[0]) & (fdates <= fdate_range[1])]\n fdate_range = (fdates[0], fdates[-1])\n df = df.loc[fdates]\n\n # get statistics\n doo_corr = ca.DOOCorrection.from_doo_df(\n df, m=m,\n date_range=(fdate_range[0], fdates[-stats_age]),\n f_dow_corr='auto', s_dow_ce='auto')\n\n # list of nDOO series, one for each age\n ndoo_by_age = []\n for age in ages:\n sdates = fdates - pd.Timedelta(age, 'd')\n idx = list(zip(fdates, sdates))\n eDOOs = df.loc[idx].reset_index('Date_file')['eDOO'] # Series\n\n # Correct for G and DoW effects\n nDOOs = eDOOs * doo_corr.iG[age]\n if sdow:\n nDOOs *= doo_corr.s_dow_corr[eDOOs.index.dayofweek]\n nDOOs /= doo_corr.f_dow_corr[fdates.dayofweek, age]\n\n ndoo_by_age.append(nDOOs)\n\n # Plot 'm all\n fig, ax = plt.subplots(1, 1, figsize=(9, 5), tight_layout=True)\n for age, ndoo in zip(ages, ndoo_by_age):\n ax.semilogy(ndoo, label=f'j={age}')\n\n ti_sdate = ', sdate' if sdow else ''\n ax.set_title(f'Methode \"vaste j\"; Weekdagcorrectie (fdate{ti_sdate}) o.b.v. DOO '\n f'{ca._ymd(doo_corr.date_range[0])} .. {ca._ymd(doo_corr.date_range[1])}')\n ax.set_ylabel('Aantal per dag')\n ax.set_xlabel('Datum eerste ziektedag')\n ax.tick_params(axis='x', labelrotation=-20)\n for tl in ax.get_xticklabels():\n tl.set_ha('left')\n\n ax.legend()\n ax.grid()\n ax.grid(which='minor', axis='y')\n\n ca._show_save_fig(fig, show, fname)\n\n\ndef plots_for_report(plots='dcm,fdc,nnc,nc10,sdow,crecom,fixj1,fixj2',\n show=False):\n \"\"\"Generate plots to include in report.\n\n - show: whether to show plot on-screen. (always save)\n plots: comma-separated string, which things to plot:\n\n - dcm: correction factor for different months.\n - fdc: correction factor for file DoW.\n - nnc: new cases, no correction (with multiple file dates).\n - nc10: new cases, correction based on October\n - nc10b: new cases, correction based from late October\n - sdow: statistics DoW effect.\n - crecom: correction data recommendations.\n - fixj1, fixj2: fixed-j strategy (with/without sdow correction).\n \"\"\"\n df = get_summary_df()\n now = df.iloc[-1].name[0] # DateTime of most recent entry\n day = pd.Timedelta(1, 'd')\n\n plot_cases = dict(\n # Tuples: function name, args, kwargs\n dcm=(\n demo_doo_correction_by_month,\n (df,),\n dict(show=show, fname='output/casus_dcmonth.pdf')),\n fdc=(\n demo_fdow_corr,\n (df,),\n dict(date_range=(now-90*day, now),\n show=show, fname='output/casus_fdow_corr.png')),\n nnc=(\n demo_prediction,\n (df,),\n dict(with_dc=False, fdate_range=(now-60*day, now),\n show=show, fbname='output/casus_nnc')),\n nc10=(\n demo_prediction,\n (df,),\n dict(fdate_range=('2020-10-01', '2020-11-12'),\n m=12, show=show, fbname='output/casus_nc10')),\n nc10b=(\n demo_prediction,\n (df,),\n dict(fdate_range=('2020-10-22', '2020-11-21'),\n m=12, show=show, fbname='output/casus_nc10b')),\n sdow=(\n demo_sdow,\n (df,),\n dict(fdate_range=(now-90*day, now), m=18, show=show,\n fbname='output/casus_sdow')),\n crecom=(\n demo_corr_recom,\n (df,),\n dict(n=120, m=18, show=show, fbname='output/casus_crecom')),\n fixj1=(\n demo_fixed_j,\n (df,),\n dict(fdate_range=(now-90*day, now),\n ages=(5, 7, 9, 11, 17), stats_age=30, m=18, show=show,\n fname='output/casus_fixj1.pdf', sdow=False)),\n fixj2=(\n demo_fixed_j,\n (df,),\n dict(fdate_range=(now-90*day, now),\n ages=(5, 7, 9, 11, 17), stats_age=30, m=18, show=True,\n fname='output/casus_fixj2.pdf', sdow=False)),\n )\n\n\n if not plots:\n print('Nothing to plot.')\n return\n\n for plot in plots.split(','):\n func, args, kwargs = plot_cases[plot]\n print(f'Doing {plot} ...')\n func(*args, **kwargs)\n\n\n\n\nif __name__ == '__main__':\n pass\n\n # # Note, because of multiprocessing for data loading,\n # # avoid adding interactive/slow code outside the main block.\n\n plt.close('all')\n\n # Default is a larger font for the title, overrule this.\n plt.rcParams['axes.titlesize'] = plt.rcParams['xtick.labelsize']\n\n\n ## This will create all plots (both on-screen and stored as files).\n ## Warning: major screen clutter.\n # plots_for_report(show=True)\n\n ## This will create all plots as files.\n # plots_for_report(show=False)\n\n ## This will create and show one plot. See doc of plots_for_report.\n plots_for_report('fixj2', show=True)\n\n # pause (for command-line use)\n tools.pause_commandline('Press Enter to end.')\n"
] |
[
[
"pandas.to_datetime",
"numpy.arange",
"matplotlib.pyplot.subplots",
"pandas.Timedelta",
"numpy.ones",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.close",
"numpy.array",
"pandas.Timestamp",
"numpy.zeros",
"matplotlib.pyplot.pause"
]
] |
milutter/deep_differential_network
|
[
"b52d87b1ec22d1cb622647252455faac31eedfb7"
] |
[
"deep_differential_network/differential_network.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom deep_differential_network.activations import *\n\n\nclass DifferentialLayer(nn.Module):\n\n def __init__(self, input_size, output_size, activation=\"ReLu\"):\n super(DifferentialLayer, self).__init__()\n\n # Create layer weights and biases:\n self.n_output = output_size\n self.weight = nn.Parameter(torch.Tensor(output_size, input_size))\n self.bias = nn.Parameter(torch.Tensor(output_size))\n\n # Initialize activation function and its derivative:\n if activation == \"ReLu\":\n self.g = nn.ReLU()\n self.g_prime = ReLUDer()\n\n elif activation == \"SoftPlus\":\n self.softplus_beta = 1.0\n self.g = nn.Softplus(beta=self.softplus_beta)\n self.g_prime = SoftplusDer(beta=self.softplus_beta)\n\n elif activation == \"Cos\":\n self.g = Cos()\n self.g_prime = CosDer()\n\n elif activation == \"Linear\":\n self.g = Linear()\n self.g_prime = LinearDer()\n\n elif activation == \"Tanh\":\n self.g = Tanh()\n self.g_prime = TanhDer()\n\n else:\n raise ValueError(\"Activation Type must be in ['Linear', 'ReLu', 'SoftPlus', 'Cos'] but is {0}\".format(self.activation))\n\n def forward(self, x, der_prev):\n # Apply Affine Transformation:\n a = F.linear(x, self.weight, self.bias)\n out = self.g(a)\n der = torch.matmul(self.g_prime(a).view(-1, self.n_output, 1) * self.weight, der_prev)\n return out, der\n\n\nclass DifferentialNetwork(nn.Module):\n\n def __init__(self, n_input, **kwargs):\n super(DifferentialNetwork, self).__init__()\n\n # Read optional arguments:\n self.n_input = n_input\n self.n_width = kwargs.get(\"n_width\", 128)\n self.n_hidden = kwargs.get(\"n_depth\", 1)\n self.n_output = kwargs.get(\"n_output\", 1)\n non_linearity = kwargs.get(\"activation\", \"ReLu\")\n\n # Initialization of the layers:\n self._w_init = kwargs.get(\"w_init\", \"xavier_normal\")\n self._b0 = kwargs.get(\"b_init\", 0.1)\n self._g_hidden = kwargs.get(\"g_hidden\", np.sqrt(2.))\n self._g_output = kwargs.get(\"g_output\", 1.0)\n self._p_sparse = kwargs.get(\"p_sparse\", 0.2)\n\n # Construct Weight Initialization:\n if self._w_init == \"xavier_normal\":\n\n # Construct initialization function:\n def init_hidden(layer):\n\n # Set the Hidden Gain:\n if self._g_hidden <= 0.0: hidden_gain = torch.nn.init.calculate_gain('relu')\n else: hidden_gain = self._g_hidden\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.xavier_normal_(layer.weight, hidden_gain)\n\n with torch.no_grad():\n layer.weight = torch.nn.Parameter(layer.weight)\n\n def init_output(layer):\n # Set Output Gain:\n if self._g_output <= 0.0: output_gain = torch.nn.init.calculate_gain('linear')\n else: output_gain = self._g_output\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.xavier_normal_(layer.weight, output_gain)\n\n elif self._w_init == \"orthogonal\":\n\n # Construct initialization function:\n def init_hidden(layer):\n # Set the Hidden Gain:\n if self._g_hidden <= 0.0: hidden_gain = torch.nn.init.calculate_gain('relu')\n else: hidden_gain = self._g_hidden\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.orthogonal_(layer.weight, hidden_gain)\n\n def init_output(layer):\n # Set Output Gain:\n if self._g_output <= 0.0: output_gain = torch.nn.init.calculate_gain('linear')\n else: output_gain = self._g_output\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.orthogonal_(layer.weight, output_gain)\n\n elif self._w_init == \"sparse\":\n assert self._p_sparse < 1. and self._p_sparse >= 0.0\n\n # Construct initialization function:\n def init_hidden(layer):\n p_non_zero = self._p_sparse\n hidden_std = self._g_hidden\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.sparse_(layer.weight, p_non_zero, hidden_std)\n\n def init_output(layer):\n p_non_zero = self._p_sparse\n output_std = self._g_output\n\n torch.nn.init.constant_(layer.bias, self._b0)\n torch.nn.init.sparse_(layer.weight, p_non_zero, output_std)\n\n else:\n raise ValueError(\"Weight Initialization Type must be in ['xavier_normal', 'orthogonal', 'sparse'] \"\n \"but is {0}\".format(self._w_init))\n\n # Create Network:\n self.layers = nn.ModuleList()\n\n # Create Input Layer:\n self.layers.append(DifferentialLayer(self.n_input, self.n_width, activation=non_linearity))\n init_hidden(self.layers[-1])\n\n # Create Hidden Layer:\n for _ in range(1, self.n_hidden):\n self.layers.append(DifferentialLayer(self.n_width, self.n_width, activation=non_linearity))\n init_hidden(self.layers[-1])\n\n # Create output Layer:\n self.layers.append(DifferentialLayer(self.n_width, self.n_output, activation=\"Linear\"))\n init_output(self.layers[-1])\n\n self._eye = torch.eye(self.n_input).view(1, self.n_input, self.n_input)\n self.device = self._eye.device\n\n def forward(self, q):\n # Create initial derivative of dq/ dq.\n # qd_dq = self._eye.repeat(q.shape[0], 1, 1).type_as(q)\n qd_dq = self._eye.repeat(q.shape[0], 1, 1)\n\n # Compute the Network:\n qd, qd_dq = self.layers[0](q, qd_dq)\n for i in range(1, len(self.layers)):\n qd, qd_dq = self.layers[i](qd, qd_dq)\n\n return qd, qd_dq\n\n def cuda(self, device=None):\n\n # Move the Network to the GPU:\n super(DifferentialNetwork, self).cuda(device=device)\n\n # Move the eye matrix to the GPU:\n self._eye = self._eye.cuda()\n self.device = self._eye.device\n return self\n\n def cpu(self):\n\n # Move the Network to the CPU:\n super(DifferentialNetwork, self).cpu()\n\n # Move the eye matrix to the CPU:\n self._eye = self._eye.cpu()\n self.device = self._eye.device\n return self\n\n"
] |
[
[
"torch.nn.init.calculate_gain",
"torch.nn.Parameter",
"torch.nn.Softplus",
"numpy.sqrt",
"torch.Tensor",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.init.xavier_normal_",
"torch.eye",
"torch.no_grad",
"torch.nn.init.orthogonal_",
"torch.nn.init.sparse_",
"torch.nn.ReLU",
"torch.nn.functional.linear"
]
] |
TechieBoy/deepfake-detection
|
[
"5bc7164710a32a64a65dd55e09aa58a030e8d0ee",
"5bc7164710a32a64a65dd55e09aa58a030e8d0ee"
] |
[
"experiments/head_pose/extract_head_pose.py",
"scripts/seperate_audio.py"
] |
[
"import numpy as np\nfrom glob import glob\nimport os\nfrom concurrent.futures import ProcessPoolExecutor\nimport json\nfrom head_pose_estimator import HeadPoseEstimator\nfrom face import face_68_landmarks\nimport cv2\nfrom model_loader import get_points_from_landmarks, get_68_3d_model\n\ndataset_folder_fake = '../dataset/fake/'\ndataset_folder_real = '../dataset/real/'\n\n\ndef write_imgs_to_file(file_name, imgs):\n with open(file_name, 'ab') as bin_file:\n for img in imgs:\n feat = convert_image_to_head_pose_diff(img)\n if feat is None:\n continue\n np.savetxt(bin_file, feat, fmt='%.32f', delimiter=',', newline=' ')\n bin_file.write(os.linesep.encode('utf-8'))\n\n\ndef process_folder(f):\n print(f'Processing folder {f}')\n metafile = os.path.join(f, 'metadata.json')\n with open(metafile, 'r') as w:\n meta = json.load(w)\n for key, value in meta.items():\n folder_name = key.split('.')[0]\n vidFramesFolder = os.path.join(f, 'frames', folder_name)\n is_fake = True if value.get('label') == 'FAKE' else False\n imgs = glob(vidFramesFolder + \"/*\")\n folder = f.split('/')[-1]\n if is_fake:\n write_imgs_to_file(f'feat/fake_{folder}.txt', imgs)\n else:\n write_imgs_to_file(f'feat/real_{folder}.txt', imgs)\n\n\ndef convert_image_to_head_pose_diff(pic):\n pic = cv2.imread(pic)\n if pic is None:\n return None\n landmarks = face_68_landmarks(pic)\n height, width = pic.shape[:2]\n\n pose_estimator = HeadPoseEstimator(image_size=(height, width))\n try:\n marks = landmarks[0]\n except:\n return None\n image_points = get_points_from_landmarks(marks, \"whole_face\")\n ra, ta = pose_estimator.solve_pose(\"whole_face\", image_points)\n\n image_points = get_points_from_landmarks(marks, \"central_face\")\n rc, tc = pose_estimator.solve_pose(\"central_face\", image_points)\n r_diff = np.ravel(ra - rc)\n t_diff = np.ravel(ta - tc)\n\n feature = np.concatenate([r_diff, t_diff])\n # feat = np.ravel(scaler.fit_transform(feature.reshape(-1, 1)))\n return feature\n\n\ndef file_to_numpy_arrays(file_name):\n with open(file_name, 'r') as my_file:\n my_file = my_file.readlines()\n # Process pool here to read multiple arrays together\n for fk in my_file:\n a = np.fromstring(fk, dtype=np.float64, sep=' ')\n # Do something with a\n\n\n\nif __name__ == '__main__':\n file_list = glob('/home/teh_devs/deepfake/raw/*')\n with ProcessPoolExecutor() as executor:\n executor.map(process_folder, file_list)\n # move_frames('/home/teh_devs/deepfake/raw/dfdc_train_part_0')",
"import numpy as np\nfrom glob import glob\nimport subprocess\nimport os\nimport shutil\nimport json\nimport audiofile\nfrom concurrent.futures import ProcessPoolExecutor\n\n\"\"\"\nFFMPEG convert all mp4 to aac\nls *mp4 | parallel --dry-run \"ffmpeg -i {} -vn -acodec copy {/.}.aac\"\nDo above command parrallel for all folders\nfor f in *; do ls $f/*mp4 | parallel \"ffmpeg -i {} -vn -acodec copy $f/{/.}.aac\"; done \n\"\"\"\n\ndef seperate_real_and_fake_audio(f):\n metadata = os.path.join(f, 'metadata.json')\n os.makedirs(os.path.join(f, 'audio', 'real'), exist_ok=True)\n os.makedirs(os.path.join(f, 'audio', 'fake'), exist_ok=True)\n with open(metadata, 'r') as w:\n d = json.load(w)\n for key,value in d.items():\n original_video = value.get('original', None)\n if original_video:\n # get real audio stream\n real_audio_file = os.path.join(f, original_video.split('.')[0] + '.aac')\n rsig, rfs = audiofile.read(real_audio_file)\n # get fake audio stream\n fake_audio_file = os.path.join(f, key.split('.')[0] + '.aac')\n fsig, ffs = audiofile.read(fake_audio_file)\n # compare\n if not np.array_equal(rsig, fsig):\n if os.path.exists(fake_audio_file):\n shutil.move(fake_audio_file, os.path.join(f, 'audio', 'fake'))\n\n\n\n\nif __name__ == '__main__':\n fl = glob('../raw/*')\n with ProcessPoolExecutor(max_workers=60) as executor:\n executor.map(seperate_real_and_fake_audio, fl)\n\n\n"
] |
[
[
"numpy.concatenate",
"numpy.ravel",
"numpy.fromstring",
"numpy.savetxt"
],
[
"numpy.array_equal"
]
] |
haoranD/Human-Activity-Recognition-DL
|
[
"277206e27e320eeb7d97333b0f0e65b274325b5e"
] |
[
"Code/Generate_SingleModel_LSTM.py"
] |
[
"import torch\nfrom torch.autograd import Variable\nimport torch.functional as F\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import f1_score\n\nclass RNN(torch.nn.Module):\n def __init__(self, dim, dropout_keep_prob, rnn_size, number_of_layers, n_classes):\n super().__init__()\n self.number_of_layers = number_of_layers\n self.rnn_size = rnn_size\n self.rnn = torch.nn.LSTM(input_size=dim, hidden_size=rnn_size, num_layers=number_of_layers,\n dropout=dropout_keep_prob, batch_first=True)\n #self.linear1 = torch.nn.Linear(in_features=rnn_size, out_features=256)\n self.linear2 = torch.nn.Linear(in_features=rnn_size, out_features=n_classes)\n #self.relu = torch.nn.ReLU()\n\n def forward(self, x, nn_tuple_state):\n # output: [batch_size, time_step, hidden_size]\n # h_n: [num_layers,batch_size, hidden_size]\n x, (h_n, c_n) = self.rnn(x, nn_tuple_state)\n #x = self.linear1(x)\n #x = self.relu(x)\n x = self.linear2(x)\n #x = self.relu(x)\n return x, (h_n, c_n)\n\ndef compute_acc_loss(pred, truth, loss_F, return_pred_truth=False):\n\n # Get the batch size and current data size for each\n # pred,truth: [batch_size, win, n_classes]\n batch_size = pred.size()[0]\n win = pred.size()[1]\n\n #Use the contiguous() in order to use view\n #Use view to reshape the tensor and flattern it (-1)means automatically change the row\n pred = pred.contiguous().view(batch_size * win, -1)#[batch_size*win, n_classes]\n truth = truth.contiguous().view(batch_size * win, -1)#[batch_size*win, n_classes]\n\n #Make the max probability to be the class\n truth = torch.argmax(truth, 1)#[batch_size*win]\n\n #Calculate loss using loss function\n #.squeeze() delete the aittional dimension\n loss = loss_F(pred, truth.squeeze())\n pred_cls = torch.argmax(pred, 1)#[batch_size*win]\n pred1d = pred_cls.cpu()\n truth1d = truth.cpu()\n\n #Calculate the accuracy\n acc = (pred1d == truth1d).sum().numpy() / pred_cls.size()[0]\n if return_pred_truth:\n return acc, loss, pred1d, truth1d\n else:\n return acc, loss\n\n#Initial the necessary h0, c0 as rnn components\ndef state_ini(number_of_layers, batch_size, rnn_size):\n h0 = Variable(torch.zeros(number_of_layers, batch_size, rnn_size))\n c0 = Variable(torch.zeros(number_of_layers, batch_size, rnn_size))\n if torch.cuda.is_available():\n h0, c0 = h0.cuda(), c0.cuda()\n state = (h0, c0)\n return state\n\ndef validation(BatchDataset, model, win, loss_F):\n\n #The different of Validation from train is:\n #batch size equal to 1\n #Bigger fixed windows\n batch_size = 1\n with torch.no_grad():\n sample_sz, accuracy, loss, sz, pred, truth = 0, 0, 0, 0, [], []\n state = state_ini(model.number_of_layers, batch_size, model.rnn_size)\n num_val_process = BatchDataset.X_valid.shape[1] // win + 1\n for j in range(num_val_process):\n x, y = BatchDataset.next_valid_or_test_batch(j, win, 'valid')\n x = Variable(torch.Tensor(x))\n y = Variable(torch.LongTensor(y))\n if torch.cuda.is_available():\n x, y = x.cuda(), y.cuda()\n pred_y, _ = model(x, state)\n acc, loss, pred1d, truth1d = compute_acc_loss(pred_y, y, loss_F, True)\n sample_sz = batch_size * win\n accuracy += acc * sample_sz\n loss += loss * sample_sz\n sz += sample_sz\n pred.extend(pred1d)\n truth.extend(truth1d)\n valid_accuracy = accuracy / sz\n valid_loss = loss / sz\n valid_f1 = f1_score(truth, pred, average='macro')\n\n sample_sz, accuracy, loss, sz, pred, truth = 0, 0, 0, 0, [], []\n state = state_ini(model.number_of_layers, batch_size, model.rnn_size)\n num_val_process = BatchDataset.X_test.shape[1] // win + 1\n for j in range(num_val_process):\n x, y = BatchDataset.next_valid_or_test_batch(j, win, 'test')\n x = Variable(torch.Tensor(x))\n y = Variable(torch.LongTensor(y))\n if torch.cuda.is_available():\n x, y = x.cuda(), y.cuda()\n pred_y, _ = model(x, state)\n acc, loss, pred1d, truth1d = compute_acc_loss(pred_y, y, loss_F, True)\n sample_sz = batch_size * win\n accuracy += acc * sample_sz\n loss += loss * sample_sz\n sz += sample_sz\n pred.extend(pred1d)\n truth.extend(truth1d)\n test_accuracy = accuracy / sz\n test_loss = loss / sz\n test_f1 = f1_score(truth, pred, average='macro')\n\n return valid_accuracy, valid_loss, valid_f1, test_accuracy, test_loss, test_f1\n\ndef train(BatchDataset, model, opts, range_mb=(128, 256), range_win=(16, 32), model_name = ''):\n\n #Use the GPU\n if torch.cuda.is_available():\n print('speed up by cuda and cudnn')\n torch.backends.cudnn.benchmark = True\n model = model.cuda()\n else:\n print('Can not find the GPU')\n\n # Initial the necessary parameters\n # classes 100 256 2 0.5 79 5000\n n_classes, nm_epochs, rnn_size, number_of_layers, keep_rate, dim, win = opts\n history = np.empty([0, 6], dtype=np.float32)\n results = np.empty([0, 5], dtype=np.float32)\n\n #Initial the function of optimizer and losser\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n loss_F = torch.nn.CrossEntropyLoss()\n\n #100 epoches\n for epoch in range(nm_epochs):\n\n print('Start Training Epoch : {}'.format(epoch))\n\n #eg : batch_size = 18\n #X_train = [18,36165,79]\n #18 * 36165 = whole data one time\n train_loss, train_accuracy, train_sz, i, pos_end = 0, 0, 0, 0, 0\n batch_size = int(np.random.randint(low=range_mb[0], high=range_mb[1], size=1)[0])\n\n # train_x3D shape: [batch_size,train_len,dim]\n train_x3D, train_y3D, coverage = BatchDataset.next_train_batch(batch_size)\n train_len = BatchDataset.X_train.shape[0] // batch_size\n\n #initial the c,h\n #For each epoch, the state will transplante\n state = state_ini(number_of_layers, batch_size, rnn_size)\n\n #sub process : for each epoch : sub process has own model\n #states in sub process are sending between sub process\n while pos_end < train_len:\n\n pos_start = pos_end\n\n #randomly choose the current window length\n #Sum(different windows in all the times of the loop) = 36165(final pos_end)\n curr_win_len = int(np.random.randint(low=range_win[0], high=range_win[1], size=1)[0])\n pos_end += curr_win_len\n\n #[batch_size, curr_win_len, dim]\n #eg:[18, 20, 79]\n x = torch.Tensor(train_x3D[:, pos_start:pos_end, :])\n y = torch.LongTensor(train_y3D[:, pos_start:pos_end, :])\n\n if torch.cuda.is_available():\n x, y = x.cuda(), y.cuda()\n\n #Flattern and feed the data to model\n #[18*20,79]\n pred, state = model(x, state)\n acc, loss = compute_acc_loss(pred, y, loss_F)\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n #not use each point but use each sample\n sample_sz = batch_size * curr_win_len\n train_accuracy += float(acc) * sample_sz\n train_loss += float(loss) * sample_sz\n train_sz += sample_sz\n\n print(\"Traing %06i, Train Accuracy = %.2f, Train Loss = %.3f\" % (pos_end * batch_size, acc, loss))\n\n #use sample wise 2\n train_accuracy /= train_sz\n train_loss /= train_sz\n\n valid_accuracy, valid_loss, valid_f1, test_accuracy, test_loss, test_f1 = validation(BatchDataset, model, win, loss_F)\n print(\"Valid Accuracy = %.3f, Valid Loss = %.3f \\nTest Accuracy = %.3f, Test Loss = %.3f\"\n % (valid_accuracy, valid_loss, test_accuracy, test_loss))\n\n print('£££££££££££££££££££££££££££££££££££££££££££££££')\n print(valid_f1)\n\n epoch_history = np.array([train_accuracy, train_loss, valid_accuracy, valid_loss, test_accuracy, test_loss])\n history = np.float32(np.vstack((history, epoch_history)))\n epoch_wise_results = np.array([train_loss, valid_loss, test_loss, valid_f1, test_f1])\n results = np.float32(np.vstack((results, epoch_wise_results)))\n print('saving results ...')\n np.save('results/' + model_name + '_' + str(dim) + '.npy', results)\n\n #save model after 10 epoch\n if epoch >= 10:\n path = './model/{0}_{1}_{2}'.format(model_name, dim, epoch)\n torch.save(model, path)\n print(\"Model saved to %s\" % path)\n\n return history"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.LongTensor",
"torch.Tensor",
"torch.nn.LSTM",
"torch.zeros",
"numpy.vstack",
"torch.nn.Linear",
"torch.no_grad",
"torch.save",
"torch.cuda.is_available",
"numpy.random.randint",
"sklearn.metrics.f1_score",
"numpy.array",
"numpy.empty",
"torch.argmax"
]
] |
mkofinas/locs
|
[
"4cb0ab9e989ebfee42d1d2850bdf3360336b5c1c"
] |
[
"locs/models/dnri_dynamicvars.py"
] |
[
"import math\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import init\nimport torch.nn.functional as F\n\nimport locs.models.model_utils as model_utils\nfrom locs.models.model_utils import RefNRIMLP, encode_onehot, get_graph_info\n\n\nclass DNRIDynamicVars(nn.Module):\n def __init__(self, params):\n super().__init__()\n # Model Params\n self.encoder = DNRI_DynamicVars_Encoder(params)\n self.decoder = DNRI_DynamicVars_Decoder(params)\n self.num_edge_types = params.get('num_edge_types')\n\n # Training params\n self.gumbel_temp = params.get('gumbel_temp')\n self.train_hard_sample = params.get('train_hard_sample')\n self.teacher_forcing_steps = params.get('teacher_forcing_steps', -1)\n\n self.normalize_kl = params.get('normalize_kl', False)\n self.normalize_kl_per_var = params.get('normalize_kl_per_var', False)\n self.normalize_nll = params.get('normalize_nll', False)\n self.normalize_nll_per_var = params.get('normalize_nll_per_var', False)\n self.kl_coef = params.get('kl_coef', 1.)\n self.nll_loss_type = params.get('nll_loss_type', 'crossent')\n self.prior_variance = params.get('prior_variance')\n self.timesteps = params.get('timesteps', 0)\n\n self.burn_in_steps = params.get('train_burn_in_steps')\n self.no_prior = params.get('no_prior', False)\n self.avg_prior = params.get('avg_prior', False)\n self.learned_prior = params.get('use_learned_prior', False)\n self.anneal_teacher_forcing = params.get('anneal_teacher_forcing', False)\n self.teacher_forcing_prior = params.get('teacher_forcing_prior', False)\n self.steps = 0\n\n def get_graph_info(self, masks):\n num_vars = masks.size(-1)\n edges = torch.ones(num_vars, device=masks.device) - torch.eye(num_vars, device=masks.device)\n tmp = torch.where(edges)\n send_edges = tmp[0]\n recv_edges = tmp[1]\n tmp_inds = torch.tensor(list(range(num_vars)), device=masks.device, dtype=torch.long).unsqueeze_(1) #TODO: should initialize as long\n edge2node_inds = (tmp_inds == recv_edges.unsqueeze(0)).nonzero()[:, 1].contiguous().view(-1, num_vars-1)\n edge_masks = masks[:, :, send_edges]*masks[:, :, recv_edges] #TODO: gotta figure this one out still\n return send_edges, recv_edges, edge2node_inds, edge_masks\n\n def single_step_forward(self, inputs, node_masks, graph_info, decoder_hidden, edge_logits, hard_sample):\n old_shape = edge_logits.shape\n if edge_logits.nelement() != 0:\n edges = model_utils.gumbel_softmax(\n edge_logits.reshape(-1, self.num_edge_types),\n tau=self.gumbel_temp,\n hard=hard_sample).view(old_shape)\n else:\n edges = torch.empty_like(edge_logits)\n predictions, decoder_hidden = self.decoder(inputs, decoder_hidden, edges, node_masks, graph_info)\n return predictions, decoder_hidden, edges\n\n\n def normalize_inputs(self, inputs, node_masks):\n return self.encoder.normalize_inputs(inputs, node_masks)\n\n #@profile\n def calculate_loss(self, inputs, node_masks, node_inds, graph_info, is_train=False, teacher_forcing=True, return_edges=False, return_logits=False, use_prior_logits=False, normalized_inputs=None):\n decoder_hidden = self.decoder.get_initial_hidden(inputs)\n num_time_steps = inputs.size(1)\n all_edges = []\n all_predictions = []\n all_priors = []\n hard_sample = (not is_train) or self.train_hard_sample\n prior_logits, posterior_logits, _ = self.encoder(inputs[:, :-1], node_masks[:, :-1], node_inds, graph_info, normalized_inputs)\n if self.anneal_teacher_forcing:\n teacher_forcing_steps = math.ceil((1 - self.train_percent)*num_time_steps)\n else:\n teacher_forcing_steps = self.teacher_forcing_steps\n edge_ind = 0\n for step in range(num_time_steps-1):\n if (teacher_forcing and (teacher_forcing_steps == -1 or step < teacher_forcing_steps)) or step == 0:\n current_inputs = inputs[:, step]\n else:\n current_inputs = predictions\n current_node_masks = node_masks[:, step]\n node_inds = current_node_masks.nonzero()[:, -1]\n num_edges = len(node_inds)*(len(node_inds)-1)\n current_graph_info = graph_info[0][step]\n if not use_prior_logits:\n current_p_logits = posterior_logits[:, edge_ind:edge_ind+num_edges]\n else:\n current_p_logits = prior_logits[:, edge_ind:edge_ind+num_edges]\n current_p_logits = current_p_logits.cuda(non_blocking=True)\n edge_ind += num_edges\n predictions, decoder_hidden, edges = self.single_step_forward(current_inputs, current_node_masks, current_graph_info, decoder_hidden, current_p_logits, hard_sample)\n all_predictions.append(predictions)\n all_edges.append(edges)\n all_predictions = torch.stack(all_predictions, dim=1)\n target = inputs[:, 1:, :, :]\n target_masks = ((node_masks[:, :-1] == 1)*(node_masks[:, 1:] == 1)).float()\n loss_nll = self.nll(all_predictions, target, target_masks)\n prob = F.softmax(posterior_logits, dim=-1)\n loss_kl = self.kl_categorical_learned(prob.cuda(non_blocking=True), prior_logits.cuda(non_blocking=True))\n loss = loss_nll + self.kl_coef*loss_kl\n loss = loss.mean()\n if return_edges:\n return loss, loss_nll, loss_kl, edges\n elif return_logits:\n return loss, loss_nll, loss_kl, posterior_logits, all_predictions\n else:\n return loss, loss_nll, loss_kl\n\n def get_prior_posterior(self, inputs, student_force=False, burn_in_steps=None):\n self.eval()\n posterior_logits = self.encoder(inputs)\n posterior_probs = torch.softmax(posterior_logits, dim=-1)\n prior_hidden = self.prior_model.get_initial_hidden(inputs)\n all_logits = []\n if student_force:\n decoder_hidden = self.decoder.get_initial_hidden(inputs)\n for step in range(burn_in_steps):\n current_inputs= inputs[:, step]\n predictions, prior_hidden, decoder_hidden, _, prior_logits = self.single_step_forward(current_inputs, prior_hidden, decoder_hidden, None, True)\n all_logits.append(prior_logits)\n for step in range(inputs.size(1) - burn_in_steps):\n predictions, prior_hidden, decoder_hidden, _, prior_logits = self.single_step_forward(predictions, prior_hidden, decoder_hidden, None, True)\n all_logits.append(prior_logits)\n else:\n for step in range(inputs.size(1)):\n current_inputs = inputs[:, step]\n prior_logits, prior_hidden = self.prior_model(prior_hidden, current_inputs)\n all_logits.append(prior_logits)\n logits = torch.stack(all_logits, dim=1)\n prior_probs = torch.softmax(logits, dim=-1)\n return prior_probs, posterior_probs\n\n def get_edge_probs(self, inputs):\n self.eval()\n prior_hidden = self.prior_model.get_initial_hidden(inputs)\n all_logits = []\n for step in range(inputs.size(1)):\n current_inputs = inputs[:, step]\n prior_logits, prior_hidden = self.prior_model(prior_hidden, current_inputs)\n all_logits.append(prior_logits)\n logits = torch.stack(all_logits, dim=1)\n edge_probs = torch.softmax(logits, dim=-1)\n return edge_probs\n\n def predict_future(self, inputs, masks, node_inds, graph_info, burn_in_masks):\n '''\n Here, we assume the following:\n * inputs contains all of the gt inputs, including for the time steps we're predicting\n * masks keeps track of the variables that are being tracked\n * burn_in_masks is set to 1 whenever we're supposed to feed in that variable's state\n for a given time step\n '''\n total_timesteps = inputs.size(1)\n prior_hidden = self.encoder.get_initial_hidden(inputs)\n decoder_hidden = self.decoder.get_initial_hidden(inputs)\n predictions = inputs[:, 0]\n preds = []\n for step in range(total_timesteps-1):\n current_masks = masks[:, step]\n current_burn_in_masks = burn_in_masks[:, step].unsqueeze(-1).type(inputs.dtype)\n current_inps = inputs[:, step]\n current_node_inds = node_inds[0][step] #TODO: check what's passed in here\n current_graph_info = graph_info[0][step]\n encoder_inp = current_burn_in_masks*current_inps + (1-current_burn_in_masks)*predictions\n current_edge_logits, prior_hidden = self.encoder.single_step_forward(encoder_inp, current_masks, current_node_inds, current_graph_info, prior_hidden)\n predictions, decoder_hidden, _ = self.single_step_forward(encoder_inp, current_masks, current_graph_info, decoder_hidden, current_edge_logits, True)\n preds.append(predictions)\n return torch.stack(preds, dim=1)\n\n def copy_states(self, prior_state, decoder_state):\n if isinstance(prior_state, tuple) or isinstance(prior_state, list):\n current_prior_state = (prior_state[0].clone(), prior_state[1].clone())\n else:\n current_prior_state = prior_state.clone()\n if isinstance(decoder_state, tuple) or isinstance(decoder_state, list):\n current_decoder_state = (decoder_state[0].clone(), decoder_state[1].clone())\n else:\n current_decoder_state = decoder_state.clone()\n return current_prior_state, current_decoder_state\n\n def merge_hidden(self, hidden):\n if isinstance(hidden[0], tuple) or isinstance(hidden[0], list):\n result0 = torch.cat([x[0] for x in hidden], dim=0)\n result1 = torch.cat([x[1] for x in hidden], dim=0)\n return (result0, result1)\n else:\n return torch.cat(hidden, dim=0)\n\n def predict_future_fixedwindow(self, inputs, burn_in_steps, prediction_steps, batch_size):\n if self.fix_encoder_alignment:\n prior_logits, _, prior_hidden = self.encoder(inputs)\n else:\n prior_logits, _, prior_hidden = self.encoder(inputs[:, :-1])\n decoder_hidden = self.decoder.get_initial_hidden(inputs)\n for step in range(burn_in_steps-1):\n current_inputs = inputs[:, step]\n current_edge_logits = prior_logits[:, step]\n predictions, decoder_hidden, _ = self.single_step_forward(current_inputs, decoder_hidden, current_edge_logits, True)\n all_timestep_preds = []\n for window_ind in range(burn_in_steps - 1, inputs.size(1)-1, batch_size):\n current_batch_preds = []\n prior_states = []\n decoder_states = []\n for step in range(batch_size):\n if window_ind + step >= inputs.size(1):\n break\n predictions = inputs[:, window_ind + step]\n current_edge_logits, prior_hidden = self.encoder.single_step_forward(predictions, prior_hidden)\n predictions, decoder_hidden, _ = self.single_step_forward(predictions, decoder_hidden, current_edge_logits, True)\n current_batch_preds.append(predictions)\n tmp_prior, tmp_decoder = self.copy_states(prior_hidden, decoder_hidden)\n prior_states.append(tmp_prior)\n decoder_states.append(tmp_decoder)\n batch_prior_hidden = self.merge_hidden(prior_states)\n batch_decoder_hidden = self.merge_hidden(decoder_states)\n current_batch_preds = torch.cat(current_batch_preds, 0)\n current_timestep_preds = [current_batch_preds]\n for step in range(prediction_steps - 1):\n current_batch_edge_logits, batch_prior_hidden = self.encoder.single_step_forward(current_batch_preds, batch_prior_hidden)\n current_batch_preds, batch_decoder_hidden, _ = self.single_step_forward(current_batch_preds, batch_decoder_hidden, current_batch_edge_logits, True)\n current_timestep_preds.append(current_batch_preds)\n all_timestep_preds.append(torch.stack(current_timestep_preds, dim=1))\n result = torch.cat(all_timestep_preds, dim=0)\n return result.unsqueeze(0)\n\n def nll(self, preds, target, masks):\n if self.nll_loss_type == 'crossent':\n return self.nll_crossent(preds, target, masks)\n elif self.nll_loss_type == 'gaussian':\n return self.nll_gaussian(preds, target, masks)\n elif self.nll_loss_type == 'poisson':\n return self.nll_poisson(preds, target, masks)\n\n def nll_gaussian(self, preds, target, masks, add_const=False):\n neg_log_p = ((preds - target) ** 2 / (2 * self.prior_variance))*masks.unsqueeze(-1)\n const = 0.5 * np.log(2 * np.pi * self.prior_variance)\n #neg_log_p += const\n if self.normalize_nll_per_var:\n raise NotImplementedError()\n elif self.normalize_nll:\n return (neg_log_p.sum(-1) + const*masks).view(preds.size(0), -1).sum(dim=-1)/(masks.view(masks.size(0), -1).sum(dim=1)+1e-8)\n else:\n raise NotImplementedError()\n\n\n def nll_crossent(self, preds, target, masks):\n if self.normalize_nll:\n loss = nn.BCEWithLogitsLoss(reduction='none')(preds, target)\n return (loss*masks.unsqueeze(-1)).view(preds.size(0), -1).sum(dim=-1)/(masks.view(masks.size(0), -1).sum(dim=1))\n else:\n raise NotImplementedError()\n\n def nll_poisson(self, preds, target, masks):\n if self.normalize_nll:\n loss = nn.PoissonNLLLoss(reduction='none')(preds, target)\n return (loss*masks.unsqueeze(-1)).view(preds.size(0), -1).sum(dim=-1)/(masks.view(masks.size(0), -1).sum(dim=1))\n else:\n raise NotImplementedError()\n\n def kl_categorical_learned(self, preds, prior_logits):\n log_prior = nn.LogSoftmax(dim=-1)(prior_logits)\n kl_div = preds*(torch.log(preds + 1e-16) - log_prior)\n if self.normalize_kl:\n return kl_div.sum(-1).view(preds.size(0), -1).mean(dim=1)\n elif self.normalize_kl_per_var:\n raise NotImplementedError()\n else:\n raise NotImplementedError()\n\n def save(self, path):\n torch.save(self.state_dict(), path)\n\n def load(self, path):\n self.load_state_dict(torch.load(path))\n\n\nclass DNRI_DynamicVars_Encoder(nn.Module):\n # Here, encoder also produces prior\n def __init__(self, params):\n super(DNRI_DynamicVars_Encoder, self).__init__()\n self.num_edges = params['num_edge_types']\n self.smooth_graph = params.get('smooth_graph', False)\n self.gpu_parallel = params.get('gpu_parallel', False)\n self.pool_edges = params.get('pool_edges', False)\n self.separate_prior_encoder = params.get('separate_prior_encoder', False)\n no_bn = params['no_encoder_bn']\n dropout = params['encoder_dropout']\n\n hidden_size = params['encoder_hidden']\n self.rnn_hidden_size = rnn_hidden_size = params['encoder_rnn_hidden']\n rnn_type = params['encoder_rnn_type']\n inp_size = params['input_size']\n self.mlp1 = RefNRIMLP(inp_size, hidden_size, hidden_size, dropout, no_bn=no_bn)\n self.mlp2 = RefNRIMLP(hidden_size * 2, hidden_size, hidden_size, dropout, no_bn=no_bn)\n self.mlp3 = RefNRIMLP(hidden_size, hidden_size, hidden_size, dropout, no_bn=no_bn)\n self.mlp4 = RefNRIMLP(hidden_size * 3, hidden_size, hidden_size, dropout, no_bn=no_bn)\n self.train_data_len = params.get('train_data_len', -1)\n\n if rnn_hidden_size is None:\n rnn_hidden_size = hidden_size\n if rnn_type == 'lstm':\n self.forward_rnn = nn.LSTM(hidden_size, rnn_hidden_size, batch_first=True)\n self.reverse_rnn = nn.LSTM(hidden_size, rnn_hidden_size, batch_first=True)\n elif rnn_type == 'gru':\n self.forward_rnn = nn.GRU(hidden_size, rnn_hidden_size, batch_first=True)\n self.reverse_rnn = nn.GRU(hidden_size, rnn_hidden_size, batch_first=True)\n out_hidden_size = 2*rnn_hidden_size\n num_layers = params['encoder_mlp_num_layers']\n if num_layers == 1:\n self.encoder_fc_out = nn.Linear(out_hidden_size, self.num_edges)\n else:\n tmp_hidden_size = params['encoder_mlp_hidden']\n layers = [nn.Linear(out_hidden_size, tmp_hidden_size), nn.ELU(inplace=True)]\n for _ in range(num_layers - 2):\n layers.append(nn.Linear(tmp_hidden_size, tmp_hidden_size))\n layers.append(nn.ELU(inplace=True))\n layers.append(nn.Linear(tmp_hidden_size, self.num_edges))\n self.encoder_fc_out = nn.Sequential(*layers)\n\n num_layers = params['prior_num_layers']\n if num_layers == 1:\n self.prior_fc_out = nn.Linear(rnn_hidden_size, self.num_edges)\n else:\n tmp_hidden_size = params['prior_hidden_size']\n layers = [nn.Linear(rnn_hidden_size, tmp_hidden_size), nn.ELU(inplace=True)]\n for _ in range(num_layers - 2):\n layers.append(nn.Linear(tmp_hidden_size, tmp_hidden_size))\n layers.append(nn.ELU(inplace=True))\n layers.append(nn.Linear(tmp_hidden_size, self.num_edges))\n self.prior_fc_out = nn.Sequential(*layers)\n\n self.normalize_mode = params['encoder_normalize_mode']\n if self.normalize_mode == 'normalize_inp':\n self.bn = nn.BatchNorm1d(inp_size)\n # Possible options: None, 'normalize_inp', 'normalize_all'\n\n self.init_weights()\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_normal_(m.weight.data)\n m.bias.data.fill_(0.1)\n def node2edge(self, node_embeddings, send_edges, recv_edges):\n #node_embeddings: [batch, num_nodes, embed_size]\n send_embed = node_embeddings[:, send_edges, :]\n recv_embed = node_embeddings[:, recv_edges, :]\n return torch.cat([send_embed, recv_embed], dim=-1)\n\n def edge2node(self, edge_embeddings, edge2node_inds, num_vars):\n incoming = edge_embeddings[:, edge2node_inds[:, 0], :].clone()\n for i in range(1, edge2node_inds.size(1)):\n incoming += edge_embeddings[:, edge2node_inds[:, i]]\n return incoming/(num_vars-1)\n\n def get_initial_hidden(self, inputs):\n batch = inputs.size(0)*inputs.size(2)*(inputs.size(2)-1)\n hidden = torch.zeros(1, batch, self.rnn_hidden_size, device=inputs.device)\n cell = torch.zeros(1, batch, self.rnn_hidden_size, device=inputs.device)\n return hidden, cell\n\n def batch_node2edge(self, x, send_edges, recv_edges):\n send_embed = x[send_edges]\n recv_embed = x[recv_edges]\n return torch.cat([send_embed, recv_embed], dim=-1)\n\n def batch_edge2node(self, x, result_shape, recv_edges):\n result = torch.zeros(result_shape, device=x.device)\n result.index_add_(0, recv_edges, x)\n return result\n\n def normalize_inputs(self, inputs, node_masks):\n if self.normalize_mode == 'normalize_inp':\n raise NotImplementedError\n elif self.normalize_mode == 'normalize_all':\n result = self.compute_feat_transform(inputs, node_masks)\n return result\n\n def compute_feat_transform(self, inputs, node_masks):\n # The following is to ensure we don't run on a sequence that's too long at once\n if len(inputs.shape) == 3:\n inputs = inputs.unsqueeze(0)\n node_masks = node_masks.unsqueeze(0)\n inp_list = inputs.split(self.train_data_len, dim=1)\n node_masks_list = node_masks.split(self.train_data_len, dim=1)\n final_result = [[] for _ in range(inputs.size(0))]\n count = 0\n for inputs, node_masks in zip(inp_list, node_masks_list):\n if not self.training:\n #print(\"IND %d OF %d\"%(count, len(node_masks_list)))\n count += 1\n flat_masks = node_masks.nonzero(as_tuple=True)\n batch_num_vars = (node_masks != 0).sum(dim=-1)\n num_vars = batch_num_vars.view(-1)\n #TODO: is it faster to put this on cpu or gpu?\n edge_info = [torch.where(torch.ones(nvar, device=num_vars.device) - torch.eye(nvar, device=num_vars.device)) for nvar in num_vars]\n offsets = torch.cat([torch.tensor([0], dtype=torch.long, device=num_vars.device), num_vars.cumsum(0)[:-1]])\n send_edges = torch.cat([l[0] + offset for l,offset in zip(edge_info, offsets)])\n recv_edges = torch.cat([l[1] + offset for l, offset in zip(edge_info, offsets)])\n\n flat_inp = inputs[flat_masks]\n tmp_batch = flat_inp.size(0)\n x = self.mlp1(flat_inp)\n x = self.batch_node2edge(x, send_edges, recv_edges)\n x = self.mlp2(x)\n x_skip = x\n result_shape = (tmp_batch, x.size(-1))\n x = self.batch_edge2node(x, result_shape, recv_edges)\n x = self.mlp3(x)\n x = self.batch_node2edge(x, send_edges, recv_edges)\n x = torch.cat([x, x_skip], dim=-1)\n x = self.mlp4(x)\n # TODO: extract into batch-wise structure\n num_edges = batch_num_vars*(batch_num_vars-1)\n num_edges = num_edges.sum(dim=-1)\n #if not self.training:\n # x = x.cpu()\n batched_result = x.split(num_edges.tolist())\n for ind,tmp_result in enumerate(batched_result):\n final_result[ind].append(tmp_result)\n final_result = [torch.cat(tmp_result) for tmp_result in final_result]\n return final_result\n\n def forward(self, inputs, node_masks, all_node_inds, all_graph_info, normalized_inputs=None):\n if inputs.size(0) > 1:\n raise ValueError(\"Batching during forward not currently supported\")\n if self.normalize_mode == 'normalize_all':\n if normalized_inputs is not None:\n x = torch.cat(normalized_inputs, dim=0)\n else:\n x = torch.cat(self.normalize_inputs(inputs, node_masks), dim=0)\n else:\n # Right now, we'll always want to do this\n raise NotImplementedError\n # Inputs is shape [batch, num_timesteps, num_vars, input_size]\n num_timesteps = node_masks.size(1)\n max_num_vars = inputs.size(2)\n max_num_edges = max_num_vars*(max_num_vars-1)\n forward_state = (torch.zeros(1, max_num_edges, self.rnn_hidden_size, device=inputs.device),\n torch.zeros(1, max_num_edges, self.rnn_hidden_size, device=inputs.device))\n reverse_state = (torch.zeros(1, max_num_edges, self.rnn_hidden_size, device=inputs.device),\n torch.zeros(1, max_num_edges, self.rnn_hidden_size, device=inputs.device))\n all_x = []\n all_forward_states = []\n all_reverse_states = []\n prior_results = []\n x_ind = 0\n for timestep in range(num_timesteps):\n current_node_masks = node_masks[:, timestep]\n node_inds = all_node_inds[0][timestep].cuda(non_blocking=True)\n if len(node_inds) <= 1:\n all_forward_states.append(torch.empty(1, 0, self.rnn_hidden_size, device=inputs.device))\n all_x.append(None)\n continue\n send_edges, recv_edges, _ = all_graph_info[0][timestep]\n send_edges, recv_edges = send_edges.cuda(non_blocking=True), recv_edges.cuda(non_blocking=True)\n global_send_edges = node_inds[send_edges]\n global_recv_edges = node_inds[recv_edges]\n global_edge_inds = global_send_edges*(max_num_vars-1) + global_recv_edges - (global_recv_edges >= global_send_edges).long()\n current_x = x[x_ind:x_ind+len(global_send_edges)].cuda(non_blocking=True)\n x_ind += len(global_send_edges)\n\n old_shape = current_x.shape\n current_x = current_x.view(old_shape[-2], 1, old_shape[-1])\n current_state = (forward_state[0][:, global_edge_inds], forward_state[1][:, global_edge_inds])\n current_x, current_state = self.forward_rnn(current_x, current_state)\n tmp_state0 = forward_state[0].clone()\n tmp_state0[:, global_edge_inds] = current_state[0]\n tmp_state1 = forward_state[1].clone()\n tmp_state1[:, global_edge_inds] = current_state[1]\n all_forward_states.append(current_state[0])\n\n # Reverse pass\n encoder_results = []\n x_ind = x.size(0)\n for timestep in range(num_timesteps-1, -1, -1):\n current_node_masks = node_masks[:, timestep]\n node_inds = all_node_inds[0][timestep].cuda(non_blocking=True)\n\n if len(node_inds) <= 1:\n continue\n send_edges, recv_edges, _ = all_graph_info[0][timestep]\n send_edges, recv_edges = send_edges.cuda(non_blocking=True), recv_edges.cuda(non_blocking=True)\n global_send_edges = node_inds[send_edges]\n global_recv_edges = node_inds[recv_edges]\n global_edge_inds = global_send_edges*(max_num_vars-1) + global_recv_edges - (global_recv_edges >= global_send_edges).long()\n current_x = x[x_ind-len(global_send_edges):x_ind].cuda(non_blocking=True)\n x_ind -= len(global_send_edges)\n old_shape = current_x.shape\n current_x = current_x.view(old_shape[-2], 1, old_shape[-1])\n\n current_state = (reverse_state[0][:, global_edge_inds], reverse_state[1][:, global_edge_inds])\n tmp_state0 = reverse_state[0].clone()\n tmp_state0[:, global_edge_inds] = current_state[0]\n tmp_state1 = reverse_state[1].clone()\n tmp_state1[:, global_edge_inds] = current_state[1]\n all_reverse_states.append(current_state[0])\n all_forward_states = torch.cat(all_forward_states, dim=1)\n all_reverse_states = torch.cat(all_reverse_states, dim=1).flip(1)\n all_states = torch.cat([all_forward_states, all_reverse_states], dim=-1)\n prior_result = self.prior_fc_out(all_forward_states)\n encoder_result = self.encoder_fc_out(all_states)\n return prior_result, encoder_result, forward_state\n\n def single_step_forward(self, inputs, node_masks, node_inds, all_graph_info, forward_state):\n if self.normalize_mode == 'normalize_all':\n x = self.normalize_inputs(inputs, node_masks)[0]\n else:\n raise NotImplementedError\n # Inputs is shape [batch, num_vars, input_size]\n max_num_vars = inputs.size(1)\n max_num_edges = max_num_vars*(max_num_vars-1)\n if len(node_inds) > 1:\n send_edges, recv_edges, _ = all_graph_info\n global_send_edges = node_inds[send_edges]\n global_recv_edges = node_inds[recv_edges]\n global_edge_inds = global_send_edges*(max_num_vars-1) + global_recv_edges - (global_recv_edges >= global_send_edges).long()\n old_shape = x.shape\n x = x.view(old_shape[-2], 1, old_shape[-1])\n current_state = (forward_state[0][:, global_edge_inds], forward_state[1][:, global_edge_inds])\n x, current_state = self.forward_rnn(x, current_state)\n tmp_state0 = forward_state[0].clone()\n tmp_state0[:, global_edge_inds] = current_state[0]\n tmp_state1 = forward_state[1].clone()\n tmp_state1[:, global_edge_inds] = current_state[1]\n forward_state = (tmp_state0, tmp_state1)\n prior_result = self.prior_fc_out(current_state[0])\n else:\n prior_result = torch.empty(1, 0, self.num_edges)\n\n return prior_result, forward_state\n\n\nclass DNRI_DynamicVars_Decoder(nn.Module):\n def __init__(self, params):\n super(DNRI_DynamicVars_Decoder, self).__init__()\n input_size = params['input_size']\n self.gpu = params['gpu']\n n_hid = params['decoder_hidden']\n edge_types = params['num_edge_types']\n skip_first = params['skip_first']\n out_size = params['input_size']\n do_prob = params['decoder_dropout']\n\n self.msg_fc1 = nn.ModuleList(\n [nn.Linear(2*n_hid, n_hid) for _ in range(edge_types)]\n )\n self.msg_fc2 = nn.ModuleList(\n [nn.Linear(n_hid, n_hid) for _ in range(edge_types)]\n )\n self.msg_out_shape = n_hid\n self.skip_first_edge_type = skip_first\n\n self.hidden_r = nn.Linear(n_hid, n_hid, bias=False)\n self.hidden_i = nn.Linear(n_hid, n_hid, bias=False)\n self.hidden_h = nn.Linear(n_hid, n_hid, bias=False)\n\n self.input_r = nn.Linear(input_size, n_hid, bias=True)\n self.input_i = nn.Linear(input_size, n_hid, bias=True)\n self.input_n = nn.Linear(input_size, n_hid, bias=True)\n\n self.out_fc1 = nn.Linear(n_hid, n_hid)\n self.out_fc2 = nn.Linear(n_hid, n_hid)\n self.out_fc3 = nn.Linear(n_hid, out_size)\n\n print('Using learned recurrent interaction net decoder.')\n\n self.dropout_prob = do_prob\n\n def get_initial_hidden(self, inputs):\n return torch.zeros(inputs.size(0), inputs.size(2), self.msg_out_shape, device=inputs.device)\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_normal_(m.weight.data)\n m.bias.data.fill_(0.1)\n\n def forward(self, inputs, hidden, edges, node_masks, graph_info):\n # Input Size: [batch, num_vars, input_size]\n # Hidden Size: [batch, num_vars, rnn_hidden]\n # Edges size: [batch, current_num_edges, num_edge_types]\n\n max_num_vars = inputs.size(1)\n node_inds = node_masks.nonzero()[:, -1]\n\n current_hidden = hidden[:, node_inds]\n current_inputs = inputs[:, node_inds]\n num_vars = current_hidden.size(1)\n\n if num_vars > 1:\n send_edges, recv_edges, edge2node_inds = graph_info\n send_edges, recv_edges, edge2node_inds = send_edges.cuda(non_blocking=True), recv_edges.cuda(non_blocking=True), edge2node_inds.cuda(non_blocking=True)\n global_send_edges = node_inds[send_edges]\n global_recv_edges = node_inds[recv_edges]\n receivers = current_hidden[:, recv_edges]\n senders = current_hidden[:, send_edges]\n # pre_msg: [batch, num_edges, 2*msg_out]\n pre_msg = torch.cat([receivers, senders], dim=-1)\n\n all_msgs = torch.zeros(pre_msg.size(0), pre_msg.size(1),\n self.msg_out_shape, device=inputs.device)\n if self.skip_first_edge_type:\n start_idx = 1\n norm = float(len(self.msg_fc2)) - 1\n else:\n start_idx = 0\n norm = float(len(self.msg_fc2))\n\n # Run separate MLP for every edge type\n # NOTE: to exclude one edge type, simply offset range by 1\n for i in range(start_idx, len(self.msg_fc2)):\n msg = torch.tanh(self.msg_fc1[i](pre_msg))\n msg = F.dropout(msg, p=self.dropout_prob)\n msg = torch.tanh(self.msg_fc2[i](msg))\n msg = msg * edges[:, :, i:i+1]\n all_msgs += msg/norm\n\n incoming = all_msgs[:, edge2node_inds[:, 0], :].clone()\n for i in range(1, edge2node_inds.size(1)):\n incoming += all_msgs[:, edge2node_inds[:, i], :]\n agg_msgs = incoming/(num_vars-1)\n elif num_vars == 0:\n pred_all = torch.zeros(inputs.size(0), max_num_vars, inputs.size(-1), device=inputs.device)\n return pred_all, hidden\n else:\n agg_msgs = torch.zeros(current_inputs.size(0), num_vars, self.msg_out_shape, device=inputs.device)\n\n # GRU-style gated aggregation\n inp_r = self.input_r(current_inputs).view(current_inputs.size(0), num_vars, -1)\n inp_i = self.input_i(current_inputs).view(current_inputs.size(0), num_vars, -1)\n inp_n = self.input_n(current_inputs).view(current_inputs.size(0), num_vars, -1)\n r = torch.sigmoid(inp_r + self.hidden_r(agg_msgs))\n i = torch.sigmoid(inp_i + self.hidden_i(agg_msgs))\n n = torch.tanh(inp_n + r*self.hidden_h(agg_msgs))\n current_hidden = (1 - i)*n + i*current_hidden\n\n # Output MLP\n pred = F.dropout(F.relu(self.out_fc1(current_hidden)), p=self.dropout_prob)\n pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)\n pred = self.out_fc3(pred)\n\n pred = current_inputs + pred\n hidden = hidden.clone()\n hidden[:, node_inds] = current_hidden\n pred_all = torch.zeros(inputs.size(0), max_num_vars, inputs.size(-1), device=inputs.device)\n pred_all[0, node_inds] = pred\n\n return pred_all, hidden\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.zeros",
"torch.load",
"torch.nn.ELU",
"torch.nn.GRU",
"torch.nn.functional.dropout",
"torch.nn.BCEWithLogitsLoss",
"torch.where",
"torch.softmax",
"torch.ones",
"torch.eye",
"torch.tensor",
"torch.nn.Sequential",
"numpy.log",
"torch.empty_like",
"torch.nn.LogSoftmax",
"torch.empty",
"torch.nn.BatchNorm1d",
"torch.nn.init.xavier_normal_",
"torch.nn.Linear",
"torch.log",
"torch.stack",
"torch.nn.LSTM",
"torch.nn.PoissonNLLLoss"
]
] |
StateOfTheArt-quant/transformerquant
|
[
"f6775d7aa920b84908b0a09d9ba098b1fe87bdff"
] |
[
"transformerquant/featurizers/default_featurizer.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright StateOfTheArt.quant. \n#\n# * Commercial Usage: please contact allen.across@gmail.com\n# * Non-Commercial Usage:\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\nimport featurizer.functors.talib as talib\nfrom featurizer.functors.labeler import RegressionLabler\nimport featurizer.functors.volume_price as vp\nimport featurizer.functors.journalhub as jf\nimport featurizer.functors.time_series as tf\n\nclass DefaultFeaturizer(object):\n \n def __init__(self, fwd_returns_window=1, task=\"regression\"):\n #\n if task == \"regression\":\n self.labeler = RegressionLabler(window=fwd_returns_window)\n \n self.pct_change = tf.PctChange(window=1) \n #\n self.ROCP = talib.ROCP(timeperiod=1)\n self.MACD = talib.MACDRelated(fastperiod=12, slowperiod=26, signalperiod=9)\n self.RSI6 = talib.DemeanedRSI(timeperiod=6)\n self.RSI12 = talib.DemeanedRSI(timeperiod=12)\n self.RSI24 = talib.DemeanedRSI(timeperiod=24)\n \n self.RSIROCP6 = talib.RSIROCP(timeperiod=6)\n self.RSIROCP12 = talib.RSIROCP(timeperiod=12)\n self.RSIROCP24 = talib.RSIROCP(timeperiod=24)\n \n self.VROCP = talib.VolumeROCP()\n #BOLL\n self.BOLL = talib.BBANDS(timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)\n \n #MA\n self.MAROCP5 = talib.MAROCP(timeperiod=5)\n self.MAROCP10 = talib.MAROCP(timeperiod=10)\n self.MAROCP20 = talib.MAROCP(timeperiod=20)\n self.MAROCP30 = talib.MAROCP(timeperiod=30)\n self.MAROCP60 = talib.MAROCP(timeperiod=60)\n self.MAROCP90 = talib.MAROCP(timeperiod=90)\n\n \n #\n self.MARelative5 = talib.MARelative(timeperiod=5)\n self.MARelative10 = talib.MARelative(timeperiod=10)\n self.MARelative20 = talib.MARelative(timeperiod=20)\n self.MARelative30 = talib.MARelative(timeperiod=30)\n self.MARelative60 = talib.MARelative(timeperiod=60)\n self.MARelative90 = talib.MARelative(timeperiod=90)\n\n \n #VMA\n #\n self.VolumeRelative5 = talib.VolumeRelative(timeperiod=5)\n self.VolumeRelative10 = talib.VolumeRelative(timeperiod=10)\n self.VolumeRelative20 = talib.VolumeRelative(timeperiod=20)\n self.VolumeRelative30 = talib.VolumeRelative(timeperiod=30)\n self.VolumeRelative60 = talib.VolumeRelative(timeperiod=60)\n self.VolumeRelative90 = talib.VolumeRelative(timeperiod=90)\n \n \n # price-volume\n self.PriceVolume = talib.PriceVolume()\n \n \n # extra added\n self.KDJ = talib.KDJRelated(fastk_period=9, slowk_period=3, slowd_period=3)\n \n # journal\n self.ReturnsRollingStd4 = jf.ReturnsRollingStd(window=4)\n self.ReturnsRollingStd12 = jf.ReturnsRollingStd(window=12)\n self.ReturnsRollingStd22 = jf.ReturnsRollingStd(window=22)\n \n self.BackwardSharpRatio4 = jf.BackwardSharpRatio(window=4)\n self.BackwardSharpRatio12 = jf.BackwardSharpRatio(window=12)\n self.BackwardSharpRatio22 = jf.BackwardSharpRatio(window=22)\n self.BackwardSharpRatio36 = jf.BackwardSharpRatio(window=36)\n \n # trading factor\n self.VolumeReturnsCorr4 = vp.VolumeReturnsCorr(window=4)\n self.VolumeReturnsCorr12 = vp.VolumeReturnsCorr(window=12)\n self.VolumeReturnsCorr22 = vp.VolumeReturnsCorr(window=22)\n \n self.HighLowCorr4 = vp.HighLowCorr(window=4)\n self.HighLowCorr12 = vp.HighLowCorr(window=12)\n self.HighLowCorr22 = vp.HighLowCorr(window=22)\n \n \n self.VolumeVwapDeviation4 = vp.VolumeVwapDeviation(window=4)\n self.VolumeVwapDeviation12 = vp.VolumeVwapDeviation(window=12)\n self.VolumeVwapDeviation22 = vp.VolumeVwapDeviation(window=22)\n \n self.OpenJump = vp.OpenJump()\n self.AbnormalVolume4 = vp.AbnormalVolume(window=4)\n self.AbnormalVolume12 = vp.AbnormalVolume(window=12)\n self.AbnormalVolume22 = vp.AbnormalVolume(window=22)\n \n self.VolumeRangeDeviation4 = vp.VolumeRangeDeviation(window=4)\n self.VolumeRangeDeviation12 = vp.VolumeRangeDeviation(window=12)\n self.VolumeRangeDeviation22 = vp.VolumeRangeDeviation(window=22)\n \n def forward(self, open_ts, high_ts, low_ts, close_ts, volume_ts):\n feature_list = []\n \n # data\n returns_ts = self.pct_change(close_ts)\n # 4\n rocp = self.ROCP(close_ts)\n orocp = self.ROCP(open_ts)\n hrocp = self.ROCP(high_ts)\n lrocp = self.ROCP(low_ts)\n \n feature_list.extend([rocp, orocp, hrocp, lrocp])\n \n # 6\n norm_DIF, norm_DEA, norm_MACD, norm_DIF_diff, norm_DEA_diff, norm_MACD_diff = self.MACD(close_ts)\n feature_list.extend([norm_DIF, norm_DEA, norm_MACD, norm_DIF_diff, norm_DEA_diff, norm_MACD_diff])\n \n # 6\n RSI6 = self.RSI6(close_ts)\n RSI12 = self.RSI12(close_ts)\n RSI24 = self.RSI24(close_ts)\n \n RSIROCP6 = self.RSIROCP6(close_ts)\n RSIROCP12 = self.RSIROCP12(close_ts)\n RSIROCP24 = self.RSIROCP24(close_ts)\n feature_list.extend([RSI6,RSI12,RSI24,RSIROCP6,RSIROCP12,RSIROCP24])\n \n # 1\n VolumeROCP = self.VROCP(volume_ts)\n feature_list.extend([VolumeROCP])\n \n # 3\n upperband_relative_ts, middleband_relative_ts, lowerband_relative_ts = self.BOLL(close_ts)\n feature_list.extend([upperband_relative_ts, middleband_relative_ts, lowerband_relative_ts])\n \n # 10\n MAROCP5= self.MAROCP5(close_ts)\n MAROCP10= self.MAROCP10(close_ts)\n MAROCP20= self.MAROCP20(close_ts)\n MAROCP30= self.MAROCP30(close_ts)\n MAROCP60= self.MAROCP60(close_ts)\n MAROCP90= self.MAROCP90(close_ts)\n\n # 10\n MARelative5= self.MARelative5(close_ts)\n MARelative10= self.MARelative10(close_ts)\n MARelative20= self.MARelative20(close_ts)\n MARelative30= self.MARelative30(close_ts)\n MARelative60= self.MARelative60(close_ts)\n MARelative90= self.MARelative90(close_ts)\n\n \n feature_list.extend([MAROCP5,MAROCP10,MAROCP20,MAROCP30,MAROCP60,MAROCP90])\n feature_list.extend([MARelative5,MARelative10,MARelative20,MARelative30,MARelative60,MARelative90])\n \n # 10 VMAROCP\n VMAROCP5= self.MAROCP5(volume_ts)\n VMAROCP10= self.MAROCP10(volume_ts)\n VMAROCP20= self.MAROCP20(volume_ts)\n VMAROCP30= self.MAROCP30(volume_ts)\n VMAROCP60= self.MAROCP60(volume_ts)\n VMAROCP90= self.MAROCP90(volume_ts)\n\n # 10 Vma relative\n VolumeRelative5= self.VolumeRelative5(volume_ts)\n VolumeRelative10= self.VolumeRelative10(volume_ts)\n VolumeRelative20= self.VolumeRelative20(volume_ts)\n VolumeRelative30= self.VolumeRelative30(volume_ts)\n VolumeRelative60= self.VolumeRelative60(volume_ts)\n VolumeRelative90= self.VolumeRelative90(volume_ts)\n\n \n feature_list.extend([VMAROCP5,VMAROCP10,VMAROCP20,VMAROCP30,VMAROCP60,VMAROCP90])#, VMAROCP360, VMAROCP720])\n feature_list.extend([VolumeRelative5,VolumeRelative10,VolumeRelative20,VolumeRelative30,VolumeRelative60,VolumeRelative90])#, VolumeRelative360, VolumeRelative720])\n \n # price_volume\n PriceVolume = self.PriceVolume(close_ts, volume_ts)\n feature_list.extend([PriceVolume])\n \n # dkj\n RSV, K, D, J = self.KDJ(high_ts, low_ts, close_ts)\n feature_list.extend([RSV, K, D, J])\n \n # journalhub\n ReturnsRollingStd4 = self.ReturnsRollingStd4(returns_ts)\n ReturnsRollingStd12 = self.ReturnsRollingStd12(returns_ts)\n ReturnsRollingStd22 = self.ReturnsRollingStd22(returns_ts)\n \n BackwardSharpRatio4 = self.BackwardSharpRatio4(returns_ts)\n BackwardSharpRatio12 = self.BackwardSharpRatio12(returns_ts)\n BackwardSharpRatio22 = self.BackwardSharpRatio22(returns_ts)\n BackwardSharpRatio36 = self.BackwardSharpRatio36(returns_ts)\n \n feature_list.extend([ReturnsRollingStd4,ReturnsRollingStd12,ReturnsRollingStd22,BackwardSharpRatio4,BackwardSharpRatio12,BackwardSharpRatio22, BackwardSharpRatio36])\n #\n \n VolumeReturnsCorr4 = self.VolumeReturnsCorr4(volume_ts, returns_ts)\n VolumeReturnsCorr12 = self.VolumeReturnsCorr12(volume_ts, returns_ts)\n VolumeReturnsCorr22 = self.VolumeReturnsCorr22(volume_ts, returns_ts)\n \n HighLowCorr4 = self.HighLowCorr4(high_ts, low_ts)\n HighLowCorr12 = self.HighLowCorr12(high_ts, low_ts)\n HighLowCorr22 = self.HighLowCorr22(high_ts, low_ts)\n \n \n VolumeVwapDeviation4 = self.VolumeVwapDeviation4(close_ts, volume_ts)\n VolumeVwapDeviation12 = self.VolumeVwapDeviation12(close_ts, volume_ts)\n VolumeVwapDeviation22 = self.VolumeVwapDeviation22(close_ts, volume_ts)\n feature_list.extend([VolumeReturnsCorr4,VolumeReturnsCorr12,VolumeReturnsCorr22,HighLowCorr4,HighLowCorr12,HighLowCorr22,VolumeVwapDeviation4,VolumeVwapDeviation12,VolumeVwapDeviation22])\n \n OpenJump = self.OpenJump(open_ts, close_ts)\n feature_list.extend([OpenJump])\n \n AbnormalVolume4 = self.AbnormalVolume4(volume_ts)\n AbnormalVolume12 = self.AbnormalVolume12(volume_ts)\n AbnormalVolume22 = self.AbnormalVolume22(volume_ts)\n \n VolumeRangeDeviation4 = self.VolumeRangeDeviation4(high_ts,low_ts,volume_ts)\n VolumeRangeDeviation12 = self.VolumeRangeDeviation12(high_ts,low_ts,volume_ts)\n VolumeRangeDeviation22 = self.VolumeRangeDeviation22(high_ts,low_ts,volume_ts)\n feature_list.extend([AbnormalVolume4,AbnormalVolume12,AbnormalVolume22,VolumeRangeDeviation4,VolumeRangeDeviation12,VolumeRangeDeviation22])\n # label\n label = self.labeler(close_ts)\n feature_list.extend([label])\n return feature_list\n\nif __name__ == \"__main__\":\n import torch\n order_book_ids = 10\n sequence_len = 100\n \n open_ts = abs(torch.randn((sequence_len, order_book_ids)))\n high_ts = abs(torch.randn((sequence_len, order_book_ids)))\n low_ts = abs(torch.randn((sequence_len, order_book_ids)))\n close_ts = abs(torch.randn((sequence_len, order_book_ids)))\n volume_ts = abs(torch.randn((sequence_len, order_book_ids)))\n \n featurizer = DefaultFeaturizer()\n feature_list = featurizer.forward(open_ts, high_ts, low_ts, close_ts, volume_ts)\n print(len(feature_list))\n \n\n"
] |
[
[
"torch.randn"
]
] |
ZhaoZhibin/Physionet2020model
|
[
"ea7379bd1e4c145c84fd254faa0d5d1330cd2f6e"
] |
[
"datasets/ECG.py"
] |
[
"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nfrom datasets.ECGDatasets import dataset\nimport pandas as pd\nfrom datasets.sequence_aug import *\n\nnormlizetype = 'none'\nstart = 0\nseq_length = 4096\nsample_ratio = 0.5\ndata_transforms = {\n 'train': Compose([\n #Reshape(),\n #DownSample(sample_ratio),\n #ZerosPadding(len=seq_length),\n # ConstantStart(start=start, num=seq_length),\n RandomClip(len=seq_length),\n Normalize(normlizetype),\n # RandomAddGaussian(),\n # RandomScale(0.1),\n # RandomAmplify(),\n # Randomverflip(),\n # Randomshift(),\n # RandomStretch(0.02),\n # RandomCrop(),\n Retype()\n ]),\n 'val': Compose([\n #Reshape(),\n #DownSample(sample_ratio),\n #RandomClip(len=seq_length),\n ValClip(len=seq_length),\n #ZerosPadding(len=seq_length),\n # ConstantStart(start=start, num=seq_length),\n Normalize(normlizetype),\n Retype()\n ]),\n 'test': Compose([\n #Reshape(),\n #DownSample(sig_resample_len),\n ValClip(len=seq_length),\n Normalize(normlizetype),\n Retype()\n ])\n}\n\n\ndef load_and_clean_sub(path):\n label_test = pd.read_csv(path, sep=\"\\t\", names=list(range(0, 3)))\n label_test.columns = ['id', 'age', 'gender'] # 设置列名\n return label_test\n\n\n\n\nclass ECG(object):\n num_classes = 24\n inputchannel = 12\n\n\n def __init__(self, data_dir, split='0'):\n self.data_dir = data_dir\n self.split = split\n\n\n\n def data_preprare(self, test=False):\n if test:\n label_csv = load_and_clean_sub(self.data_dir)\n test_dataset = dataset(anno_pd=label_csv, test=True, transform=data_transforms['test'])\n return test_dataset\n else:\n train_path = './data_split/train_split' + self.split + '.csv'\n val_path = './data_split/test_split' + self.split + '.csv'\n train_pd = pd.read_csv(train_path)\n val_pd = pd.read_csv(val_path)\n\n train_dataset = dataset(anno_pd=train_pd, transform=data_transforms['train'], data_dir=self.data_dir)\n val_dataset = dataset(anno_pd=val_pd, transform=data_transforms['val'], data_dir=self.data_dir)\n return train_dataset, val_dataset\n\n\n\n\n"
] |
[
[
"pandas.read_csv"
]
] |
opentaps/eemeter
|
[
"e544a295c3ab8721e632b61510232454ea24932d"
] |
[
"eemeter/caltrack/usage_per_day.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\n Copyright 2014-2019 OpenEEmeter contributors\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\"\"\"\nfrom collections import Counter, namedtuple\nimport traceback\n\nimport numpy as np\nimport pandas as pd\nimport pytz\nimport statsmodels.formula.api as smf\n\nfrom ..exceptions import MissingModelParameterError, UnrecognizedModelTypeError\nfrom ..features import compute_temperature_features\nfrom ..metrics import ModelMetrics\nfrom ..transform import day_counts, overwrite_partial_rows_with_nan\nfrom ..warnings import EEMeterWarning\n\n\n__all__ = (\n \"CalTRACKUsagePerDayCandidateModel\",\n \"CalTRACKUsagePerDayModelResults\",\n \"DataSufficiency\",\n \"ModelPrediction\",\n \"fit_caltrack_usage_per_day_model\",\n \"caltrack_sufficiency_criteria\",\n \"caltrack_usage_per_day_predict\",\n \"plot_caltrack_candidate\",\n \"get_too_few_non_zero_degree_day_warning\",\n \"get_total_degree_day_too_low_warning\",\n \"get_parameter_negative_warning\",\n \"get_parameter_p_value_too_high_warning\",\n \"get_single_cdd_only_candidate_model\",\n \"get_single_hdd_only_candidate_model\",\n \"get_single_cdd_hdd_candidate_model\",\n \"get_intercept_only_candidate_models\",\n \"get_cdd_only_candidate_models\",\n \"get_hdd_only_candidate_models\",\n \"get_cdd_hdd_candidate_models\",\n \"select_best_candidate\",\n)\n\n\nModelPrediction = namedtuple(\"ModelPrediction\", [\"result\", \"design_matrix\", \"warnings\"])\n\n\ndef _noneify(value):\n if value is None:\n return None\n return None if np.isnan(value) else value\n\n\nclass CalTRACKUsagePerDayModelResults(object):\n \"\"\" Contains information about the chosen model.\n\n Attributes\n ----------\n status : :any:`str`\n A string indicating the status of this result. Possible statuses:\n\n - ``'NO DATA'``: No baseline data was available.\n - ``'NO MODEL'``: No candidate models qualified.\n - ``'SUCCESS'``: A qualified candidate model was chosen.\n\n method_name : :any:`str`\n The name of the method used to fit the baseline model.\n model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` or :any:`None`\n The selected candidate model, if any.\n r_squared_adj : :any:`float`\n The adjusted r-squared of the selected model.\n candidates : :any:`list` of :any:`eemeter.CalTRACKUsagePerDayCandidateModel`\n A list of any model candidates encountered during the model\n selection and fitting process.\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n A list of any warnings reported during the model selection and fitting\n process.\n metadata : :any:`dict`\n An arbitrary dictionary of metadata to be associated with this result.\n This can be used, for example, to tag the results with attributes like\n an ID::\n\n {\n 'id': 'METER_12345678',\n }\n\n settings : :any:`dict`\n A dictionary of settings used by the method.\n totals_metrics : :any:`ModelMetrics`\n A ModelMetrics object, if one is calculated and associated with this\n model. (This initializes to None.) The ModelMetrics object contains\n model fit information and descriptive statistics about the underlying data,\n with that data expressed as period totals.\n avgs_metrics : :any:`ModelMetrics`\n A ModelMetrics object, if one is calculated and associated with this\n model. (This initializes to None.) The ModelMetrics object contains\n model fit information and descriptive statistics about the underlying data,\n with that data expressed as daily averages.\n \"\"\"\n\n def __init__(\n self,\n status,\n method_name,\n interval=None,\n model=None,\n r_squared_adj=None,\n candidates=None,\n warnings=None,\n metadata=None,\n settings=None,\n ):\n self.status = status # NO DATA | NO MODEL | SUCCESS\n self.method_name = method_name\n\n self.interval = interval\n self.model = model\n self.r_squared_adj = r_squared_adj\n\n if candidates is None:\n candidates = []\n self.candidates = candidates\n\n if warnings is None:\n warnings = []\n self.warnings = warnings\n\n if metadata is None:\n metadata = {}\n self.metadata = metadata\n\n if settings is None:\n settings = {}\n self.settings = settings\n\n self.totals_metrics = None\n self.avgs_metrics = None\n\n def __repr__(self):\n return (\n \"CalTRACKUsagePerDayModelResults(status='{}', method_name='{}',\"\n \" r_squared_adj={})\".format(\n self.status, self.method_name, self.r_squared_adj\n )\n )\n\n def json(self, with_candidates=False):\n \"\"\" Return a JSON-serializable representation of this result.\n\n The output of this function can be converted to a serialized string\n with :any:`json.dumps`.\n \"\"\"\n\n def _json_or_none(obj):\n return None if obj is None else obj.json()\n\n data = {\n \"status\": self.status,\n \"method_name\": self.method_name,\n \"interval\": self.interval,\n \"model\": _json_or_none(self.model),\n \"r_squared_adj\": _noneify(self.r_squared_adj),\n \"warnings\": [w.json() for w in self.warnings],\n \"metadata\": self.metadata,\n \"settings\": self.settings,\n \"totals_metrics\": _json_or_none(self.totals_metrics),\n \"avgs_metrics\": _json_or_none(self.avgs_metrics),\n \"candidates\": None,\n }\n if with_candidates:\n data[\"candidates\"] = [candidate.json() for candidate in self.candidates]\n return data\n\n @classmethod\n def from_json(cls, data):\n \"\"\" Loads a JSON-serializable representation into the model state.\n\n The input of this function is a dict which can be the result\n of :any:`json.loads`.\n \"\"\"\n\n # \"model\" is a CalTRACKUsagePerDayCandidateModel that was serialized\n model = None\n d = data.get('model')\n if d:\n model = CalTRACKUsagePerDayCandidateModel.from_json(d)\n\n c = cls(\n data.get('status'),\n data.get('method_name'),\n interval=data.get('interval'),\n model=model,\n r_squared_adj=data.get('r_squared_adj'),\n candidates=data.get('candidates'),\n warnings=data.get('warnings'),\n metadata=data.get('metadata'),\n settings=data.get('settings'))\n\n # Note the metrics do not contain all the data needed\n # for reconstruction (like the input pandas) ...\n d = data.get('avgs_metrics')\n if d:\n c.avgs_metrics = ModelMetrics.from_json(d)\n d = data.get('totals_metrics')\n if d:\n c.totals_metrics = ModelMetrics.from_json(d)\n return c\n\n def predict(\n self,\n prediction_index,\n temperature_data,\n with_disaggregated=False,\n with_design_matrix=False,\n **kwargs\n ):\n return self.model.predict(\n prediction_index,\n temperature_data,\n with_disaggregated=with_disaggregated,\n with_design_matrix=with_design_matrix,\n **kwargs\n )\n\n def plot(\n self,\n ax=None,\n figure=None,\n title=None,\n figsize=None,\n with_candidates=False,\n candidate_alpha=None,\n temp_range=None,\n ):\n \"\"\" Plot a model fit.\n\n Parameters\n ----------\n ax : :any:`matplotlib.axes.Axes`, optional\n Existing axes to plot on.\n figure : :any:`matplotlib.figure`, optional\n Something that implements subplots, if left to None uses matplotlib.pyplot\n title : :any:`str`, optional\n Chart title.\n figsize : :any:`tuple`, optional\n (width, height) of chart.\n with_candidates : :any:`bool`\n If True, also plot candidate models.\n candidate_alpha : :any:`float` between 0 and 1\n Transparency at which to plot candidate models. 0 fully transparent,\n 1 fully opaque.\n\n Returns\n -------\n ax : :any:`matplotlib.axes.Axes`\n Matplotlib axes.\n \"\"\"\n\n # note: to avoid memeory leaks some application might prefer using matplotlib.figure\n # instead of matplotlib.pyplot\n if not figure:\n try:\n import matplotlib.pyplot as plt\n except ImportError: # pragma: no cover\n raise ImportError(\"matplotlib is required for plotting.\")\n\n if figsize is None:\n figsize = (10, 4)\n\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize)\n else:\n if ax is None:\n ax = figure.subplots()\n\n if temp_range is None:\n temp_range = (20, 90)\n\n if with_candidates:\n for candidate in self.candidates:\n candidate.plot(ax=ax, temp_range=temp_range, alpha=candidate_alpha)\n self.model.plot(ax=ax, best=True, temp_range=temp_range)\n\n if title is not None:\n ax.set_title(title)\n\n return ax\n\n\nclass CalTRACKUsagePerDayCandidateModel(object):\n \"\"\" Contains information about a candidate model.\n\n Attributes\n ----------\n model_type : :any:`str`\n The type of model, e..g., :code:`'hdd_only'`.\n formula : :any:`str`\n The R-style formula for the design matrix of this model, e.g., :code:`'meter_value ~ hdd_65'`.\n status : :any:`str`\n A string indicating the status of this model. Possible statuses:\n\n - ``'NOT ATTEMPTED'``: Candidate model not fitted due to an issue\n encountered in data before attempt.\n - ``'ERROR'``: A fatal error occurred during model fit process.\n - ``'DISQUALIFIED'``: The candidate model fit was disqualified\n from the model selection process because of a decision made after\n candidate model fit completed, e.g., a bad fit, or a parameter out\n of acceptable range.\n - ``'QUALIFIED'``: The candidate model fit is acceptable and can be\n considered during model selection.\n model_params : :any:`dict`, default :any:`None`\n A flat dictionary of model parameters which must be serializable\n using the :any:`json.dumps` method.\n model : :any:`object`\n The raw model (if any) used in fitting. Not serialized.\n result : :any:`object`\n The raw modeling result (if any) returned by the `model`. Not serialized.\n r_squared_adj : :any:`float`\n The adjusted r-squared of the candidate model.\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n A list of any warnings reported during creation of the candidate model.\n \"\"\"\n\n def __init__(\n self,\n model_type,\n formula,\n status,\n model_params=None,\n model=None,\n result=None,\n r_squared_adj=None,\n warnings=None,\n ):\n self.model_type = model_type\n self.formula = formula\n self.status = status # NOT ATTEMPTED | ERROR | QUALIFIED | DISQUALIFIED\n self.model = model\n self.result = result\n self.r_squared_adj = r_squared_adj\n\n if model_params is None:\n model_params = {}\n self.model_params = model_params\n\n if warnings is None:\n warnings = []\n self.warnings = warnings\n\n def __repr__(self):\n return (\n \"CalTRACKUsagePerDayCandidateModel(model_type='{}', formula='{}', status='{}',\"\n \" r_squared_adj={})\".format(\n self.model_type,\n self.formula,\n self.status,\n round(self.r_squared_adj, 3)\n if self.r_squared_adj is not None\n else None,\n )\n )\n\n def json(self):\n \"\"\" Return a JSON-serializable representation of this result.\n\n The output of this function can be converted to a serialized string\n with :any:`json.dumps`.\n \"\"\"\n return {\n \"model_type\": self.model_type,\n \"formula\": self.formula,\n \"status\": self.status,\n \"model_params\": self.model_params,\n \"r_squared_adj\": _noneify(self.r_squared_adj),\n \"warnings\": [w.json() for w in self.warnings],\n }\n\n @classmethod\n def from_json(cls, data):\n \"\"\" Loads a JSON-serializable representation into the model state.\n\n The input of this function is a dict which can be the result\n of :any:`json.loads`.\n \"\"\"\n\n c = cls(\n data.get('model_type'),\n data.get('formula'),\n data.get('status'),\n model_params=data.get('model_params'),\n r_squared_adj=data.get('r_squared_adj'),\n warnings=data.get('warnings'))\n\n return c\n\n def predict(\n self,\n prediction_index,\n temperature_data,\n with_disaggregated=False,\n with_design_matrix=False,\n **kwargs\n ):\n \"\"\" Predict\n \"\"\"\n return caltrack_usage_per_day_predict(\n self.model_type,\n self.model_params,\n prediction_index,\n temperature_data,\n with_disaggregated=with_disaggregated,\n with_design_matrix=with_design_matrix,\n **kwargs\n )\n\n def plot(\n self,\n best=False,\n ax=None,\n title=None,\n figsize=None,\n temp_range=None,\n alpha=None,\n **kwargs\n ):\n \"\"\" Plot\n \"\"\"\n return plot_caltrack_candidate(\n self,\n best=best,\n ax=ax,\n title=title,\n figsize=figsize,\n temp_range=temp_range,\n alpha=alpha,\n **kwargs\n )\n\n\nclass DataSufficiency(object):\n \"\"\" Contains the result of a data sufficiency check.\n\n Attributes\n ----------\n status : :any:`str`\n A string indicating the status of this result. Possible statuses:\n\n - ``'NO DATA'``: No baseline data was available.\n - ``'FAIL'``: Data did not meet criteria.\n - ``'PASS'``: Data met criteria.\n criteria_name : :any:`str`\n The name of the criteria method used to check for baseline data sufficiency.\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n A list of any warnings reported during the check for baseline data sufficiency.\n data : :any:`dict`\n A dictionary of data related to determining whether a warning should be generated.\n settings : :any:`dict`\n A dictionary of settings (keyword arguments) used.\n \"\"\"\n\n def __init__(self, status, criteria_name, warnings=None, data=None, settings=None):\n self.status = status # NO DATA | FAIL | PASS\n self.criteria_name = criteria_name\n\n if warnings is None:\n warnings = []\n self.warnings = warnings\n\n if data is None:\n data = {}\n self.data = data\n\n if settings is None:\n settings = {}\n self.settings = settings\n\n def __repr__(self):\n return (\n \"DataSufficiency(\"\n \"status='{status}', criteria_name='{criteria_name}')\".format(\n status=self.status, criteria_name=self.criteria_name\n )\n )\n\n def json(self):\n \"\"\" Return a JSON-serializable representation of this result.\n\n The output of this function can be converted to a serialized string\n with :any:`json.dumps`.\n \"\"\"\n return {\n \"status\": self.status,\n \"criteria_name\": self.criteria_name,\n \"warnings\": [w.json() for w in self.warnings],\n \"data\": self.data,\n \"settings\": self.settings,\n }\n\n\ndef _get_parameter_or_raise(model_type, model_params, param):\n try:\n return model_params[param]\n except KeyError:\n raise MissingModelParameterError(\n '\"{}\" parameter required for model_type: {}'.format(param, model_type)\n )\n\n\ndef _caltrack_predict_design_matrix(\n model_type,\n model_params,\n data,\n disaggregated=False,\n input_averages=False,\n output_averages=False,\n):\n \"\"\" An internal CalTRACK predict method for use with a design matrix of the form\n used in model fitting.\n\n Given a set model type, parameters, and daily temperatures, return model\n predictions.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n model_params : :any:`dict`\n Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCandidateModel.model_params`.\n data : :any:`pandas.DataFrame`\n Data over which to predict. Assumed to be like the format of the data used\n for fitting, although it need only have the columns. If not giving data\n with a `pandas.DatetimeIndex` it must have the column `n_days`,\n representing the number of days per prediction period (otherwise\n inferred from DatetimeIndex).\n disaggregated : :any:`bool`, optional\n If True, return results as a :any:`pandas.DataFrame` with columns\n ``'base_load'``, ``'heating_load'``, and ``'cooling_load'``\n input_averages : :any:`bool`, optional\n If HDD and CDD columns expressed as period totals, select False. If HDD\n and CDD columns expressed as period averages, select True. If prediction\n period is daily, results should be the same either way. Matters for billing.\n output_averages : :any:`bool`, optional\n If True, prediction returned as averages (not totals). If False, returned\n as totals.\n\n Returns\n -------\n prediction : :any:`pandas.Series` or :any:`pandas.DataFrame`\n Returns results as series unless ``disaggregated=True``.\n \"\"\"\n\n zeros = pd.Series(0, index=data.index)\n ones = zeros + 1\n\n if isinstance(data.index, pd.DatetimeIndex):\n days_per_period = day_counts(data.index)\n else:\n try:\n days_per_period = data[\"n_days\"]\n except KeyError:\n raise ValueError(\"Data needs DatetimeIndex or an n_days column.\")\n\n # TODO(philngo): handle different degree day methods and hourly temperatures\n if model_type in [\"intercept_only\", \"hdd_only\", \"cdd_only\", \"cdd_hdd\"]:\n intercept = _get_parameter_or_raise(model_type, model_params, \"intercept\")\n if output_averages == False:\n base_load = intercept * days_per_period\n else:\n base_load = intercept * ones\n elif model_type is None:\n raise ValueError(\"Model not valid for prediction: model_type=None\")\n else:\n raise UnrecognizedModelTypeError(\n \"invalid caltrack model type: {}\".format(model_type)\n )\n\n if model_type in [\"hdd_only\", \"cdd_hdd\"]:\n beta_hdd = _get_parameter_or_raise(model_type, model_params, \"beta_hdd\")\n heating_balance_point = _get_parameter_or_raise(\n model_type, model_params, \"heating_balance_point\"\n )\n hdd_column_name = \"hdd_%s\" % heating_balance_point\n hdd = data[hdd_column_name]\n if input_averages == True and output_averages == False:\n heating_load = hdd * beta_hdd * days_per_period\n elif input_averages == True and output_averages == True:\n heating_load = hdd * beta_hdd\n elif input_averages == False and output_averages == False:\n heating_load = hdd * beta_hdd\n else:\n heating_load = hdd * beta_hdd / days_per_period\n else:\n heating_load = zeros\n\n if model_type in [\"cdd_only\", \"cdd_hdd\"]:\n beta_cdd = _get_parameter_or_raise(model_type, model_params, \"beta_cdd\")\n cooling_balance_point = _get_parameter_or_raise(\n model_type, model_params, \"cooling_balance_point\"\n )\n cdd_column_name = \"cdd_%s\" % cooling_balance_point\n cdd = data[cdd_column_name]\n if input_averages == True and output_averages == False:\n cooling_load = cdd * beta_cdd * days_per_period\n elif input_averages == True and output_averages == True:\n cooling_load = cdd * beta_cdd\n elif input_averages == False and output_averages == False:\n cooling_load = cdd * beta_cdd\n else:\n cooling_load = cdd * beta_cdd / days_per_period\n else:\n cooling_load = zeros\n\n # If any of the rows of input data contained NaNs, restore the NaNs\n # Note: If data contains ANY NaNs at all, this declares the entire row a NaN.\n # TODO(philngo): Consider making this more nuanced.\n def _restore_nans(load):\n load = load[data.sum(axis=1, skipna=False).notnull()].reindex(data.index)\n return load\n\n base_load = _restore_nans(base_load)\n heating_load = _restore_nans(heating_load)\n cooling_load = _restore_nans(cooling_load)\n\n if disaggregated:\n return pd.DataFrame(\n {\n \"base_load\": base_load,\n \"heating_load\": heating_load,\n \"cooling_load\": cooling_load,\n }\n )\n else:\n return base_load + heating_load + cooling_load\n\n\ndef caltrack_usage_per_day_predict(\n model_type,\n model_params,\n prediction_index,\n temperature_data,\n degree_day_method=\"daily\",\n with_disaggregated=False,\n with_design_matrix=False,\n):\n \"\"\" CalTRACK predict method.\n\n Given a model type, parameters, hourly temperatures, a\n :any:`pandas.DatetimeIndex` index over which to predict meter usage,\n return model predictions as totals for the period (so billing period totals,\n daily totals, etc.). Optionally include the computed design matrix or\n disaggregated usage in the output dataframe.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n model_params : :any:`dict`\n Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCandidateModel.model_params`.\n temperature_data : :any:`pandas.DataFrame`\n Hourly temperature data to use for prediction. Time period should match\n the ``prediction_index`` argument.\n prediction_index : :any:`pandas.DatetimeIndex`\n Time period over which to predict.\n with_disaggregated : :any:`bool`, optional\n If True, return results as a :any:`pandas.DataFrame` with columns\n ``'base_load'``, ``'heating_load'``, and ``'cooling_load'``.\n with_design_matrix : :any:`bool`, optional\n If True, return results as a :any:`pandas.DataFrame` with columns\n ``'n_days'``, ``'n_days_dropped'``, ``n_days_kept``, and\n ``temperature_mean``.\n\n Returns\n -------\n prediction : :any:`pandas.DataFrame`\n Columns are as follows:\n\n - ``predicted_usage``: Predicted usage values computed to match\n ``prediction_index``.\n - ``base_load``: modeled base load (only for ``with_disaggregated=True``).\n - ``cooling_load``: modeled cooling load (only for ``with_disaggregated=True``).\n - ``heating_load``: modeled heating load (only for ``with_disaggregated=True``).\n - ``n_days``: number of days in period (only for ``with_design_matrix=True``).\n - ``n_days_dropped``: number of days dropped because of insufficient\n data (only for ``with_design_matrix=True``).\n - ``n_days_kept``: number of days kept because of sufficient data\n (only for ``with_design_matrix=True``).\n - ``temperature_mean``: mean temperature during given period.\n (only for ``with_design_matrix=True``).\n predict_warnings: :any: list of EEMeterWarning if any.\n \"\"\"\n if model_params is None:\n raise MissingModelParameterError(\"model_params is None.\")\n predict_warnings = []\n cooling_balance_points = []\n heating_balance_points = []\n\n if \"cooling_balance_point\" in model_params:\n cooling_balance_points.append(model_params[\"cooling_balance_point\"])\n if \"heating_balance_point\" in model_params:\n heating_balance_points.append(model_params[\"heating_balance_point\"])\n\n design_matrix = compute_temperature_features(\n prediction_index,\n temperature_data,\n heating_balance_points=heating_balance_points,\n cooling_balance_points=cooling_balance_points,\n degree_day_method=degree_day_method,\n use_mean_daily_values=False,\n )\n\n if degree_day_method == \"daily\":\n design_matrix[\"n_days\"] = (\n design_matrix.n_days_kept + design_matrix.n_days_dropped\n )\n else:\n design_matrix[\"n_days\"] = (\n design_matrix.n_hours_kept + design_matrix.n_hours_dropped\n ) / 24\n\n if design_matrix.dropna().empty:\n if with_disaggregated:\n empty_columns = {\n \"predicted_usage\": [],\n \"base_load\": [],\n \"heating_load\": [],\n \"cooling_load\": [],\n }\n else:\n empty_columns = {\"predicted_usage\": []}\n\n if with_design_matrix:\n empty_columns.update({col: [] for col in design_matrix.columns})\n\n predict_warnings.append(\n EEMeterWarning(\n qualified_name=(\"eemeter.caltrack.compute_temperature_features\"),\n description=(\n \"Design matrix empty, compute_temperature_features failed\"\n ),\n data={\"temperature_data\": temperature_data},\n )\n )\n\n return ModelPrediction(\n pd.DataFrame(empty_columns),\n design_matrix=pd.DataFrame(),\n warnings=predict_warnings,\n )\n\n results = _caltrack_predict_design_matrix(\n model_type,\n model_params,\n design_matrix,\n input_averages=False,\n output_averages=False,\n ).to_frame(\"predicted_usage\")\n\n if with_disaggregated:\n disaggregated = _caltrack_predict_design_matrix(\n model_type,\n model_params,\n design_matrix,\n disaggregated=True,\n input_averages=False,\n output_averages=False,\n )\n results = results.join(disaggregated)\n\n if with_design_matrix:\n results = results.join(design_matrix)\n\n return ModelPrediction(\n result=results, design_matrix=design_matrix, warnings=predict_warnings\n )\n\n\ndef get_too_few_non_zero_degree_day_warning(\n model_type, balance_point, degree_day_type, degree_days, minimum_non_zero\n):\n \"\"\" Return an empty list or a single warning wrapped in a list regarding\n non-zero degree days for a set of degree days.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n balance_point : :any:`float`\n The balance point in question.\n degree_day_type : :any:`str`\n The type of degree days (``'cdd'`` or ``'hdd'``).\n degree_days : :any:`pandas.Series`\n A series of degree day values.\n minimum_non_zero : :any:`int`\n Minimum allowable number of non-zero degree day values.\n\n Returns\n -------\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n Empty list or list of single warning.\n \"\"\"\n warnings = []\n n_non_zero = int((degree_days > 0).sum())\n if n_non_zero < minimum_non_zero:\n warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_daily.{model_type}.too_few_non_zero_{degree_day_type}\".format(\n model_type=model_type, degree_day_type=degree_day_type\n )\n ),\n description=(\n \"Number of non-zero daily {degree_day_type} values below accepted minimum.\"\n \" Candidate fit not attempted.\".format(\n degree_day_type=degree_day_type.upper()\n )\n ),\n data={\n \"n_non_zero_{degree_day_type}\".format(\n degree_day_type=degree_day_type\n ): n_non_zero,\n \"minimum_non_zero_{degree_day_type}\".format(\n degree_day_type=degree_day_type\n ): minimum_non_zero,\n \"{degree_day_type}_balance_point\".format(\n degree_day_type=degree_day_type\n ): balance_point,\n },\n )\n )\n return warnings\n\n\ndef get_total_degree_day_too_low_warning(\n model_type,\n balance_point,\n degree_day_type,\n avg_degree_days,\n period_days,\n minimum_total,\n):\n \"\"\" Return an empty list or a single warning wrapped in a list regarding\n the total summed degree day values.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n balance_point : :any:`float`\n The balance point in question.\n degree_day_type : :any:`str`\n The type of degree days (``'cdd'`` or ``'hdd'``).\n avg_degree_days : :any:`pandas.Series`\n A series of degree day values.\n period_days : :any:`pandas.Series`\n A series of containing day counts.\n minimum_total : :any:`float`\n Minimum allowable total sum of degree day values.\n\n Returns\n -------\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n Empty list or list of single warning.\n \"\"\"\n\n warnings = []\n total_degree_days = (avg_degree_days * period_days).sum()\n if total_degree_days < minimum_total:\n warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_daily.{model_type}.total_{degree_day_type}_too_low\".format(\n model_type=model_type, degree_day_type=degree_day_type\n )\n ),\n description=(\n \"Total {degree_day_type} below accepted minimum.\"\n \" Candidate fit not attempted.\".format(\n degree_day_type=degree_day_type.upper()\n )\n ),\n data={\n \"total_{degree_day_type}\".format(\n degree_day_type=degree_day_type\n ): total_degree_days,\n \"total_{degree_day_type}_minimum\".format(\n degree_day_type=degree_day_type\n ): minimum_total,\n \"{degree_day_type}_balance_point\".format(\n degree_day_type=degree_day_type\n ): balance_point,\n },\n )\n )\n return warnings\n\n\ndef get_parameter_negative_warning(model_type, model_params, parameter):\n \"\"\" Return an empty list or a single warning wrapped in a list indicating\n whether model parameter is negative.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n model_params : :any:`dict`\n Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCandidateModel.model_params`.\n parameter : :any:`str`\n The name of the parameter, e.g., ``'intercept'``.\n\n Returns\n -------\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n Empty list or list of single warning.\n \"\"\"\n warnings = []\n if model_params.get(parameter, 0) < 0:\n warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_daily.{model_type}.{parameter}_negative\".format(\n model_type=model_type, parameter=parameter\n )\n ),\n description=(\n \"Model fit {parameter} parameter is negative. Candidate model rejected.\".format(\n parameter=parameter\n )\n ),\n data=model_params,\n )\n )\n return warnings\n\n\ndef get_parameter_p_value_too_high_warning(\n model_type, model_params, parameter, p_value, maximum_p_value\n):\n \"\"\" Return an empty list or a single warning wrapped in a list indicating\n whether model parameter p-value is too high.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n model_params : :any:`dict`\n Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCandidateModel.model_params`.\n parameter : :any:`str`\n The name of the parameter, e.g., ``'intercept'``.\n p_value : :any:`float`\n The p-value of the parameter.\n maximum_p_value : :any:`float`\n The maximum allowable p-value of the parameter.\n\n Returns\n -------\n warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n Empty list or list of single warning.\n \"\"\"\n warnings = []\n if p_value > maximum_p_value:\n data = {\n \"{}_p_value\".format(parameter): p_value,\n \"{}_maximum_p_value\".format(parameter): maximum_p_value,\n }\n data.update(model_params)\n warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_daily.{model_type}.{parameter}_p_value_too_high\".format(\n model_type=model_type, parameter=parameter\n )\n ),\n description=(\n \"Model fit {parameter} p-value is too high. Candidate model rejected.\".format(\n parameter=parameter\n )\n ),\n data=data,\n )\n )\n return warnings\n\n\ndef get_fit_failed_candidate_model(model_type, formula):\n \"\"\" Return a Candidate model that indicates the fitting routine failed.\n\n Parameters\n ----------\n model_type : :any:`str`\n Model type (e.g., ``'cdd_hdd'``).\n formula : :any:`float`\n The candidate model formula.\n\n Returns\n -------\n candidate_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel`\n Candidate model instance with status ``'ERROR'``, and warning with\n traceback.\n \"\"\"\n warnings = [\n EEMeterWarning(\n qualified_name=\"eemeter.caltrack_daily.{}.model_results\".format(model_type),\n description=(\n \"Error encountered in statsmodels.formula.api.ols method. (Empty data?)\"\n ),\n data={\"traceback\": traceback.format_exc()},\n )\n ]\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type, formula=formula, status=\"ERROR\", warnings=warnings\n )\n\n\ndef get_intercept_only_candidate_models(data, weights_col):\n \"\"\" Return a list of a single candidate intercept-only model.\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value``.\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n\n Returns\n -------\n candidate_models : :any:`list` of :any:`CalTRACKUsagePerDayCandidateModel`\n List containing a single intercept-only candidate model.\n \"\"\"\n model_type = \"intercept_only\"\n formula = \"meter_value ~ 1\"\n\n if weights_col is None:\n weights = 1\n else:\n weights = data[weights_col]\n\n try:\n model = smf.wls(formula=formula, data=data, weights=weights)\n except Exception as e:\n return [get_fit_failed_candidate_model(model_type, formula)]\n\n result = model.fit()\n\n # CalTrack 3.3.1.3\n model_params = {\"intercept\": result.params[\"Intercept\"]}\n\n model_warnings = []\n\n # CalTrack 3.4.3.2\n for parameter in [\"intercept\"]:\n model_warnings.extend(\n get_parameter_negative_warning(model_type, model_params, parameter)\n )\n\n if len(model_warnings) > 0:\n status = \"DISQUALIFIED\"\n else:\n status = \"QUALIFIED\"\n\n return [\n CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=status,\n warnings=model_warnings,\n model_params=model_params,\n model=model,\n result=result,\n r_squared_adj=0,\n )\n ]\n\n\ndef get_single_cdd_only_candidate_model(\n data,\n minimum_non_zero_cdd,\n minimum_total_cdd,\n beta_cdd_maximum_p_value,\n weights_col,\n balance_point,\n):\n \"\"\" Return a single candidate cdd-only model for a particular balance\n point.\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and\n ``cdd_<balance_point>``\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_cdd : :any:`int`\n Minimum allowable number of non-zero cooling degree day values.\n minimum_total_cdd : :any:`float`\n Minimum allowable total sum of cooling degree day values.\n beta_cdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta cdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n balance_point : :any:`float`\n The cooling balance point for this model.\n\n Returns\n -------\n candidate_model : :any:`CalTRACKUsagePerDayCandidateModel`\n A single cdd-only candidate model, with any associated warnings.\n \"\"\"\n model_type = \"cdd_only\"\n cdd_column = \"cdd_%s\" % balance_point\n formula = \"meter_value ~ %s\" % cdd_column\n\n if weights_col is None:\n weights = 1\n else:\n weights = data[weights_col]\n\n period_days = weights\n\n degree_day_warnings = []\n degree_day_warnings.extend(\n get_total_degree_day_too_low_warning(\n model_type,\n balance_point,\n \"cdd\",\n data[cdd_column],\n period_days,\n minimum_total_cdd,\n )\n )\n degree_day_warnings.extend(\n get_too_few_non_zero_degree_day_warning(\n model_type, balance_point, \"cdd\", data[cdd_column], minimum_non_zero_cdd\n )\n )\n\n if len(degree_day_warnings) > 0:\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=\"NOT ATTEMPTED\",\n warnings=degree_day_warnings,\n )\n\n try:\n model = smf.wls(formula=formula, data=data, weights=weights)\n except Exception as e:\n return get_fit_failed_candidate_model(model_type, formula)\n\n result = model.fit()\n r_squared_adj = result.rsquared_adj\n beta_cdd_p_value = result.pvalues[cdd_column]\n\n # CalTrack 3.3.1.3\n model_params = {\n \"intercept\": result.params[\"Intercept\"],\n \"beta_cdd\": result.params[cdd_column],\n \"cooling_balance_point\": balance_point,\n }\n\n model_warnings = []\n\n # CalTrack 3.4.3.2\n for parameter in [\"intercept\", \"beta_cdd\"]:\n model_warnings.extend(\n get_parameter_negative_warning(model_type, model_params, parameter)\n )\n model_warnings.extend(\n get_parameter_p_value_too_high_warning(\n model_type,\n model_params,\n parameter,\n beta_cdd_p_value,\n beta_cdd_maximum_p_value,\n )\n )\n\n if len(model_warnings) > 0:\n status = \"DISQUALIFIED\"\n else:\n status = \"QUALIFIED\"\n\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=status,\n warnings=model_warnings,\n model_params=model_params,\n model=model,\n result=result,\n r_squared_adj=r_squared_adj,\n )\n\n\ndef get_cdd_only_candidate_models(\n data, minimum_non_zero_cdd, minimum_total_cdd, beta_cdd_maximum_p_value, weights_col\n):\n \"\"\" Return a list of all possible candidate cdd-only models.\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and 1 to n\n columns with names of the form ``cdd_<balance_point>``. All columns\n with names of this form will be used to fit a candidate model.\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_cdd : :any:`int`\n Minimum allowable number of non-zero cooling degree day values.\n minimum_total_cdd : :any:`float`\n Minimum allowable total sum of cooling degree day values.\n beta_cdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta cdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n\n Returns\n -------\n candidate_models : :any:`list` of :any:`CalTRACKUsagePerDayCandidateModel`\n A list of cdd-only candidate models, with any associated warnings.\n \"\"\"\n balance_points = [int(col[4:]) for col in data.columns if col.startswith(\"cdd\")]\n candidate_models = [\n get_single_cdd_only_candidate_model(\n data,\n minimum_non_zero_cdd,\n minimum_total_cdd,\n beta_cdd_maximum_p_value,\n weights_col,\n balance_point,\n )\n for balance_point in balance_points\n ]\n return candidate_models\n\n\ndef get_single_hdd_only_candidate_model(\n data,\n minimum_non_zero_hdd,\n minimum_total_hdd,\n beta_hdd_maximum_p_value,\n weights_col,\n balance_point,\n):\n \"\"\" Return a single candidate hdd-only model for a particular balance\n point.\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and\n ``hdd_<balance_point>``\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_hdd : :any:`int`\n Minimum allowable number of non-zero heating degree day values.\n minimum_total_hdd : :any:`float`\n Minimum allowable total sum of heating degree day values.\n beta_hdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta hdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n balance_point : :any:`float`\n The heating balance point for this model.\n\n Returns\n -------\n candidate_model : :any:`CalTRACKUsagePerDayCandidateModel`\n A single hdd-only candidate model, with any associated warnings.\n \"\"\"\n model_type = \"hdd_only\"\n hdd_column = \"hdd_%s\" % balance_point\n formula = \"meter_value ~ %s\" % hdd_column\n\n if weights_col is None:\n weights = 1\n else:\n weights = data[weights_col]\n\n period_days = weights\n\n degree_day_warnings = []\n degree_day_warnings.extend(\n get_total_degree_day_too_low_warning(\n model_type,\n balance_point,\n \"hdd\",\n data[hdd_column],\n period_days,\n minimum_total_hdd,\n )\n )\n degree_day_warnings.extend(\n get_too_few_non_zero_degree_day_warning(\n model_type, balance_point, \"hdd\", data[hdd_column], minimum_non_zero_hdd\n )\n )\n\n if len(degree_day_warnings) > 0:\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=\"NOT ATTEMPTED\",\n warnings=degree_day_warnings,\n )\n\n try:\n model = smf.wls(formula=formula, data=data, weights=weights)\n except Exception as e:\n return get_fit_failed_candidate_model(model_type, formula)\n\n result = model.fit()\n r_squared_adj = result.rsquared_adj\n beta_hdd_p_value = result.pvalues[hdd_column]\n\n # CalTrack 3.3.1.3\n model_params = {\n \"intercept\": result.params[\"Intercept\"],\n \"beta_hdd\": result.params[hdd_column],\n \"heating_balance_point\": balance_point,\n }\n\n model_warnings = []\n\n # CalTrack 3.4.3.2\n for parameter in [\"intercept\", \"beta_hdd\"]:\n model_warnings.extend(\n get_parameter_negative_warning(model_type, model_params, parameter)\n )\n model_warnings.extend(\n get_parameter_p_value_too_high_warning(\n model_type,\n model_params,\n parameter,\n beta_hdd_p_value,\n beta_hdd_maximum_p_value,\n )\n )\n\n if len(model_warnings) > 0:\n status = \"DISQUALIFIED\"\n else:\n status = \"QUALIFIED\"\n\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=status,\n warnings=model_warnings,\n model_params=model_params,\n model=model,\n result=result,\n r_squared_adj=r_squared_adj,\n )\n\n\ndef get_hdd_only_candidate_models(\n data, minimum_non_zero_hdd, minimum_total_hdd, beta_hdd_maximum_p_value, weights_col\n):\n \"\"\"\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and 1 to n\n columns with names of the form ``hdd_<balance_point>``. All columns\n with names of this form will be used to fit a candidate model.\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_hdd : :any:`int`\n Minimum allowable number of non-zero heating degree day values.\n minimum_total_hdd : :any:`float`\n Minimum allowable total sum of heating degree day values.\n beta_hdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta hdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n\n Returns\n -------\n candidate_models : :any:`list` of :any:`CalTRACKUsagePerDayCandidateModel`\n A list of hdd-only candidate models, with any associated warnings.\n \"\"\"\n\n balance_points = [int(col[4:]) for col in data.columns if col.startswith(\"hdd\")]\n\n candidate_models = [\n get_single_hdd_only_candidate_model(\n data,\n minimum_non_zero_hdd,\n minimum_total_hdd,\n beta_hdd_maximum_p_value,\n weights_col,\n balance_point,\n )\n for balance_point in balance_points\n ]\n return candidate_models\n\n\ndef get_single_cdd_hdd_candidate_model(\n data,\n minimum_non_zero_cdd,\n minimum_non_zero_hdd,\n minimum_total_cdd,\n minimum_total_hdd,\n beta_cdd_maximum_p_value,\n beta_hdd_maximum_p_value,\n weights_col,\n cooling_balance_point,\n heating_balance_point,\n):\n \"\"\" Return and fit a single candidate cdd_hdd model for a particular selection\n of cooling balance point and heating balance point\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and\n ``hdd_<heating_balance_point>`` and ``cdd_<cooling_balance_point>``\n DataFrames of this form can be made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_cdd : :any:`int`\n Minimum allowable number of non-zero cooling degree day values.\n minimum_non_zero_hdd : :any:`int`\n Minimum allowable number of non-zero heating degree day values.\n minimum_total_cdd : :any:`float`\n Minimum allowable total sum of cooling degree day values.\n minimum_total_hdd : :any:`float`\n Minimum allowable total sum of heating degree day values.\n beta_cdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta cdd parameter.\n beta_hdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta hdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n cooling_balance_point : :any:`float`\n The cooling balance point for this model.\n heating_balance_point : :any:`float`\n The heating balance point for this model.\n\n Returns\n -------\n candidate_model : :any:`CalTRACKUsagePerDayCandidateModel`\n A single cdd-hdd candidate model, with any associated warnings.\n \"\"\"\n model_type = \"cdd_hdd\"\n cdd_column = \"cdd_%s\" % cooling_balance_point\n hdd_column = \"hdd_%s\" % heating_balance_point\n formula = \"meter_value ~ %s + %s\" % (cdd_column, hdd_column)\n n_days_column = None\n\n if weights_col is None:\n weights = 1\n else:\n weights = data[weights_col]\n\n period_days = weights\n\n degree_day_warnings = []\n degree_day_warnings.extend(\n get_total_degree_day_too_low_warning(\n model_type,\n cooling_balance_point,\n \"cdd\",\n data[cdd_column],\n period_days,\n minimum_total_cdd,\n )\n )\n degree_day_warnings.extend(\n get_too_few_non_zero_degree_day_warning(\n model_type,\n cooling_balance_point,\n \"cdd\",\n data[cdd_column],\n minimum_non_zero_cdd,\n )\n )\n degree_day_warnings.extend(\n get_total_degree_day_too_low_warning(\n model_type,\n heating_balance_point,\n \"hdd\",\n data[hdd_column],\n period_days,\n minimum_total_hdd,\n )\n )\n degree_day_warnings.extend(\n get_too_few_non_zero_degree_day_warning(\n model_type,\n heating_balance_point,\n \"hdd\",\n data[hdd_column],\n minimum_non_zero_hdd,\n )\n )\n\n if len(degree_day_warnings) > 0:\n return CalTRACKUsagePerDayCandidateModel(\n model_type, formula, \"NOT ATTEMPTED\", warnings=degree_day_warnings\n )\n\n try:\n model = smf.wls(formula=formula, data=data, weights=weights)\n except Exception as e:\n return get_fit_failed_candidate_model(model_type, formula)\n\n result = model.fit()\n r_squared_adj = result.rsquared_adj\n beta_cdd_p_value = result.pvalues[cdd_column]\n beta_hdd_p_value = result.pvalues[hdd_column]\n\n # CalTrack 3.3.1.3\n model_params = {\n \"intercept\": result.params[\"Intercept\"],\n \"beta_cdd\": result.params[cdd_column],\n \"beta_hdd\": result.params[hdd_column],\n \"cooling_balance_point\": cooling_balance_point,\n \"heating_balance_point\": heating_balance_point,\n }\n\n model_warnings = []\n\n # CalTrack 3.4.3.2\n for parameter in [\"intercept\", \"beta_cdd\", \"beta_hdd\"]:\n model_warnings.extend(\n get_parameter_negative_warning(model_type, model_params, parameter)\n )\n model_warnings.extend(\n get_parameter_p_value_too_high_warning(\n model_type,\n model_params,\n parameter,\n beta_cdd_p_value,\n beta_cdd_maximum_p_value,\n )\n )\n model_warnings.extend(\n get_parameter_p_value_too_high_warning(\n model_type,\n model_params,\n parameter,\n beta_hdd_p_value,\n beta_hdd_maximum_p_value,\n )\n )\n\n if len(model_warnings) > 0:\n status = \"DISQUALIFIED\"\n else:\n status = \"QUALIFIED\"\n\n return CalTRACKUsagePerDayCandidateModel(\n model_type=model_type,\n formula=formula,\n status=status,\n warnings=model_warnings,\n model_params=model_params,\n model=model,\n result=result,\n r_squared_adj=r_squared_adj,\n )\n\n\ndef get_cdd_hdd_candidate_models(\n data,\n minimum_non_zero_cdd,\n minimum_non_zero_hdd,\n minimum_total_cdd,\n minimum_total_hdd,\n beta_cdd_maximum_p_value,\n beta_hdd_maximum_p_value,\n weights_col,\n):\n \"\"\" Return a list of candidate cdd_hdd models for a particular selection\n of cooling balance point and heating balance point\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and 1 to n\n columns each of the form ``hdd_<heating_balance_point>``\n and ``cdd_<cooling_balance_point>``. DataFrames of this form can be\n made using the\n :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n minimum_non_zero_cdd : :any:`int`\n Minimum allowable number of non-zero cooling degree day values.\n minimum_non_zero_hdd : :any:`int`\n Minimum allowable number of non-zero heating degree day values.\n minimum_total_cdd : :any:`float`\n Minimum allowable total sum of cooling degree day values.\n minimum_total_hdd : :any:`float`\n Minimum allowable total sum of heating degree day values.\n beta_cdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta cdd parameter.\n beta_hdd_maximum_p_value : :any:`float`\n The maximum allowable p-value of the beta hdd parameter.\n weights_col : :any:`str` or None\n The name of the column (if any) in ``data`` to use as weights.\n\n Returns\n -------\n candidate_models : :any:`list` of :any:`CalTRACKUsagePerDayCandidateModel`\n A list of cdd_hdd candidate models, with any associated warnings.\n \"\"\"\n\n cooling_balance_points = [\n int(col[4:]) for col in data.columns if col.startswith(\"cdd\")\n ]\n heating_balance_points = [\n int(col[4:]) for col in data.columns if col.startswith(\"hdd\")\n ]\n\n # CalTrack 3.2.2.1\n candidate_models = [\n get_single_cdd_hdd_candidate_model(\n data,\n minimum_non_zero_cdd,\n minimum_non_zero_hdd,\n minimum_total_cdd,\n minimum_total_hdd,\n beta_cdd_maximum_p_value,\n beta_hdd_maximum_p_value,\n weights_col,\n cooling_balance_point,\n heating_balance_point,\n )\n for cooling_balance_point in cooling_balance_points\n for heating_balance_point in heating_balance_points\n if heating_balance_point <= cooling_balance_point\n ]\n return candidate_models\n\n\ndef select_best_candidate(candidate_models):\n \"\"\" Select and return the best candidate model based on r-squared and\n qualification.\n\n Parameters\n ----------\n candidate_models : :any:`list` of :any:`eemeter.CalTRACKUsagePerDayCandidateModel`\n Candidate models to select from.\n\n Returns\n -------\n (best_candidate, warnings) : :any:`tuple` of :any:`eemeter.CalTRACKUsagePerDayCandidateModel` or :any:`None` and :any:`list` of `eemeter.EEMeterWarning`\n Return the candidate model with highest r-squared or None if none meet\n the requirements, and a list of warnings about this selection (or lack\n of selection).\n \"\"\"\n best_r_squared_adj = -np.inf\n best_candidate = None\n\n # CalTrack 3.4.3.3\n for candidate in candidate_models:\n if (\n candidate.status == \"QUALIFIED\"\n and candidate.r_squared_adj > best_r_squared_adj\n ):\n best_candidate = candidate\n best_r_squared_adj = candidate.r_squared_adj\n\n if best_candidate is None:\n warnings = [\n EEMeterWarning(\n qualified_name=\"eemeter.caltrack_daily.select_best_candidate.no_candidates\",\n description=\"No qualified model candidates available.\",\n data={\n \"status_count:{}\".format(status): count\n for status, count in Counter(\n [c.status for c in candidate_models]\n ).items()\n },\n )\n ]\n return None, warnings\n\n return best_candidate, []\n\n\ndef fit_caltrack_usage_per_day_model(\n data,\n fit_cdd=True,\n use_billing_presets=False,\n minimum_non_zero_cdd=10,\n minimum_non_zero_hdd=10,\n minimum_total_cdd=20,\n minimum_total_hdd=20,\n beta_cdd_maximum_p_value=1,\n beta_hdd_maximum_p_value=1,\n weights_col=None,\n fit_intercept_only=True,\n fit_cdd_only=True,\n fit_hdd_only=True,\n fit_cdd_hdd=True,\n):\n \"\"\" CalTRACK daily and billing methods using a usage-per-day modeling\n strategy.\n\n Parameters\n ----------\n data : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and 1 to n\n columns each of the form ``hdd_<heating_balance_point>``\n and ``cdd_<cooling_balance_point>``. DataFrames of this form can be\n made using the :any:`eemeter.create_caltrack_daily_design_matrix` or\n :any:`eemeter.create_caltrack_billing_design_matrix` methods.\n Should have a :any:`pandas.DatetimeIndex`.\n fit_cdd : :any:`bool`, optional\n If True, fit CDD models unless overridden by ``fit_cdd_only`` or\n ``fit_cdd_hdd`` flags. Should be set to ``False`` for gas meter data.\n use_billing_presets : :any:`bool`, optional\n Use presets appropriate for billing models. Otherwise defaults are\n appropriate for daily models.\n minimum_non_zero_cdd : :any:`int`, optional\n Minimum allowable number of non-zero cooling degree day values.\n minimum_non_zero_hdd : :any:`int`, optional\n Minimum allowable number of non-zero heating degree day values.\n minimum_total_cdd : :any:`float`, optional\n Minimum allowable total sum of cooling degree day values.\n minimum_total_hdd : :any:`float`, optional\n Minimum allowable total sum of heating degree day values.\n beta_cdd_maximum_p_value : :any:`float`, optional\n The maximum allowable p-value of the beta cdd parameter. The default\n value is the most permissive possible (i.e., 1). This is here\n for backwards compatibility with CalTRACK 1.0 methods.\n beta_hdd_maximum_p_value : :any:`float`, optional\n The maximum allowable p-value of the beta hdd parameter. The default\n value is the most permissive possible (i.e., 1). This is here\n for backwards compatibility with CalTRACK 1.0 methods.\n weights_col : :any:`str` or None, optional\n The name of the column (if any) in ``data`` to use as weights. Weight\n must be the number of days of data in the period.\n fit_intercept_only : :any:`bool`, optional\n If True, fit and consider intercept_only model candidates.\n fit_cdd_only : :any:`bool`, optional\n If True, fit and consider cdd_only model candidates. Ignored if\n ``fit_cdd=False``.\n fit_hdd_only : :any:`bool`, optional\n If True, fit and consider hdd_only model candidates.\n fit_cdd_hdd : :any:`bool`, optional\n If True, fit and consider cdd_hdd model candidates. Ignored if\n ``fit_cdd=False``.\n\n Returns\n -------\n model_results : :any:`eemeter.CalTRACKUsagePerDayModelResults`\n Results of running CalTRACK daily method. See :any:`eemeter.CalTRACKUsagePerDayModelResults`\n for more details.\n \"\"\"\n if use_billing_presets:\n # CalTrack 3.2.2.2.1\n minimum_non_zero_cdd = 0\n minimum_non_zero_hdd = 0\n # CalTrack 3.2.2.2.2\n minimum_total_cdd = 20\n minimum_total_hdd = 20\n # CalTrack 3.4.2\n if weights_col is None:\n raise ValueError(\n \"If using billing presets, the weights_col argument must be specified.\"\n )\n interval = \"billing\"\n else:\n interval = \"daily\"\n\n # cleans data to fully NaN rows that have missing temp or meter data\n data = overwrite_partial_rows_with_nan(data)\n\n if data.dropna().empty:\n return CalTRACKUsagePerDayModelResults(\n status=\"NO DATA\",\n method_name=\"caltrack_usage_per_day\",\n warnings=[\n EEMeterWarning(\n qualified_name=\"eemeter.caltrack_usage_per_day.no_data\",\n description=(\"No data available. Cannot fit model.\"),\n data={},\n )\n ],\n )\n\n # collect all candidate results, then validate all at once\n # CalTrack 3.4.3.1\n candidates = []\n\n if fit_intercept_only:\n candidates.extend(\n get_intercept_only_candidate_models(data, weights_col=weights_col)\n )\n\n if fit_hdd_only:\n candidates.extend(\n get_hdd_only_candidate_models(\n data=data,\n minimum_non_zero_hdd=minimum_non_zero_hdd,\n minimum_total_hdd=minimum_total_hdd,\n beta_hdd_maximum_p_value=beta_hdd_maximum_p_value,\n weights_col=weights_col,\n )\n )\n\n # cdd models ignored for gas\n if fit_cdd:\n if fit_cdd_only:\n candidates.extend(\n get_cdd_only_candidate_models(\n data=data,\n minimum_non_zero_cdd=minimum_non_zero_cdd,\n minimum_total_cdd=minimum_total_cdd,\n beta_cdd_maximum_p_value=beta_cdd_maximum_p_value,\n weights_col=weights_col,\n )\n )\n\n if fit_cdd_hdd:\n candidates.extend(\n get_cdd_hdd_candidate_models(\n data=data,\n minimum_non_zero_cdd=minimum_non_zero_cdd,\n minimum_non_zero_hdd=minimum_non_zero_hdd,\n minimum_total_cdd=minimum_total_cdd,\n minimum_total_hdd=minimum_total_hdd,\n beta_cdd_maximum_p_value=beta_cdd_maximum_p_value,\n beta_hdd_maximum_p_value=beta_hdd_maximum_p_value,\n weights_col=weights_col,\n )\n )\n\n # find best candidate result\n best_candidate, candidate_warnings = select_best_candidate(candidates)\n\n warnings = candidate_warnings\n\n if best_candidate is None:\n status = \"NO MODEL\"\n r_squared_adj = None\n else:\n status = \"SUCCESS\"\n r_squared_adj = best_candidate.r_squared_adj\n\n model_result = CalTRACKUsagePerDayModelResults(\n status=status,\n method_name=\"caltrack_usage_per_day\",\n interval=interval,\n model=best_candidate,\n candidates=candidates,\n r_squared_adj=r_squared_adj,\n warnings=warnings,\n settings={\n \"fit_cdd\": fit_cdd,\n \"minimum_non_zero_cdd\": minimum_non_zero_cdd,\n \"minimum_non_zero_hdd\": minimum_non_zero_hdd,\n \"minimum_total_cdd\": minimum_total_cdd,\n \"minimum_total_hdd\": minimum_total_hdd,\n \"beta_cdd_maximum_p_value\": beta_cdd_maximum_p_value,\n \"beta_hdd_maximum_p_value\": beta_hdd_maximum_p_value,\n },\n )\n\n if best_candidate is not None:\n if best_candidate.model_type in [\"cdd_hdd\"]:\n num_parameters = 2\n elif best_candidate.model_type in [\"hdd_only\", \"cdd_only\"]:\n num_parameters = 1\n else:\n num_parameters = 0\n\n predicted_avgs = _caltrack_predict_design_matrix(\n best_candidate.model_type,\n best_candidate.model_params,\n data,\n input_averages=True,\n output_averages=True,\n )\n model_result.avgs_metrics = ModelMetrics(\n data.meter_value, predicted_avgs, num_parameters\n )\n\n predicted_totals = _caltrack_predict_design_matrix(\n best_candidate.model_type,\n best_candidate.model_params,\n data,\n input_averages=True,\n output_averages=False,\n )\n\n days_per_period = day_counts(data.index)\n data_totals = data.meter_value * days_per_period\n model_result.totals_metrics = ModelMetrics(\n data_totals, predicted_totals, num_parameters\n )\n\n return model_result\n\n\ndef caltrack_sufficiency_criteria(\n data_quality,\n requested_start,\n requested_end,\n num_days=365,\n min_fraction_daily_coverage=0.9, # TODO: needs to be per year\n min_fraction_hourly_temperature_coverage_per_period=0.9,\n):\n \"\"\"CalTRACK daily data sufficiency criteria.\n\n .. note::\n\n For CalTRACK compliance, ``min_fraction_daily_coverage`` must be set\n at ``0.9`` (section 2.2.1.2), and requested_start and requested_end must\n not be None (section 2.2.4).\n\n\n Parameters\n ----------\n data_quality : :any:`pandas.DataFrame`\n A DataFrame containing at least the column ``meter_value`` and the two\n columns ``temperature_null``, containing a count of null hourly\n temperature values for each meter value, and ``temperature_not_null``,\n containing a count of not-null hourly temperature values for each\n meter value. Should have a :any:`pandas.DatetimeIndex`.\n requested_start : :any:`datetime.datetime`, timezone aware (or :any:`None`)\n The desired start of the period, if any, especially if this is\n different from the start of the data. If given, warnings\n are reported on the basis of this start date instead of data start\n date. Must be explicitly set to ``None`` in order to use data start date.\n requested_end : :any:`datetime.datetime`, timezone aware (or :any:`None`)\n The desired end of the period, if any, especially if this is\n different from the end of the data. If given, warnings\n are reported on the basis of this end date instead of data end date.\n Must be explicitly set to ``None`` in order to use data end date.\n num_days : :any:`int`, optional\n Exact number of days allowed in data, including extent given by\n ``requested_start`` or ``requested_end``, if given.\n min_fraction_daily_coverage : :any:, optional\n Minimum fraction of days of data in total data extent for which data\n must be available.\n min_fraction_hourly_temperature_coverage_per_period=0.9,\n Minimum fraction of hours of temperature data coverage in a particular\n period. Anything below this causes the whole period to be considered\n considered missing.\n\n Returns\n -------\n data_sufficiency : :any:`eemeter.DataSufficiency`\n The an object containing sufficiency status and warnings for this data.\n \"\"\"\n criteria_name = \"caltrack_sufficiency_criteria\"\n\n if data_quality.dropna().empty:\n return DataSufficiency(\n status=\"NO DATA\",\n criteria_name=criteria_name,\n warnings=[\n EEMeterWarning(\n qualified_name=\"eemeter.caltrack_sufficiency_criteria.no_data\",\n description=(\"No data available.\"),\n data={},\n )\n ],\n )\n\n data_start = data_quality.index.min().tz_convert(\"UTC\")\n data_end = data_quality.index.max().tz_convert(\"UTC\")\n n_days_data = (data_end - data_start).days\n\n if requested_start is not None:\n # check for gap at beginning\n requested_start = requested_start.astimezone(pytz.UTC)\n n_days_start_gap = (data_start - requested_start).days\n else:\n n_days_start_gap = 0\n\n if requested_end is not None:\n # check for gap at end\n requested_end = requested_end.astimezone(pytz.UTC)\n n_days_end_gap = (requested_end - data_end).days\n else:\n n_days_end_gap = 0\n\n critical_warnings = []\n\n if n_days_end_gap < 0:\n # CalTRACK 2.2.4\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".extra_data_after_requested_end_date\"\n ),\n description=(\"Extra data found after requested end date.\"),\n data={\n \"requested_end\": requested_end.isoformat(),\n \"data_end\": data_end.isoformat(),\n },\n )\n )\n n_days_end_gap = 0\n\n if n_days_start_gap < 0:\n # CalTRACK 2.2.4\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".extra_data_before_requested_start_date\"\n ),\n description=(\"Extra data found before requested start date.\"),\n data={\n \"requested_start\": requested_start.isoformat(),\n \"data_start\": data_start.isoformat(),\n },\n )\n )\n n_days_start_gap = 0\n\n n_days_total = n_days_data + n_days_start_gap + n_days_end_gap\n\n n_negative_meter_values = data_quality.meter_value[\n data_quality.meter_value < 0\n ].shape[0]\n\n if n_negative_meter_values > 0:\n # CalTrack 2.3.5\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\" \".negative_meter_values\"\n ),\n description=(\n \"Found negative meter data values, which may indicate presence\"\n \" of solar net metering.\"\n ),\n data={\"n_negative_meter_values\": n_negative_meter_values},\n )\n )\n\n # TODO(philngo): detect and report unsorted or repeated values.\n\n # create masks showing which daily or billing periods meet criteria\n valid_meter_value_rows = data_quality.meter_value.notnull()\n valid_temperature_rows = (\n data_quality.temperature_not_null\n / (data_quality.temperature_not_null + data_quality.temperature_null)\n ) > min_fraction_hourly_temperature_coverage_per_period\n valid_rows = valid_meter_value_rows & valid_temperature_rows\n\n # get number of days per period - for daily this should be a series of ones\n row_day_counts = day_counts(data_quality.index)\n\n # apply masks, giving total\n n_valid_meter_value_days = int((valid_meter_value_rows * row_day_counts).sum())\n n_valid_temperature_days = int((valid_temperature_rows * row_day_counts).sum())\n n_valid_days = int((valid_rows * row_day_counts).sum())\n\n median = data_quality.meter_value.median()\n upper_quantile = data_quality.meter_value.quantile(0.75)\n lower_quantile = data_quality.meter_value.quantile(0.25)\n iqr = upper_quantile - lower_quantile\n extreme_value_limit = median + (3 * iqr)\n n_extreme_values = data_quality.meter_value[\n data_quality.meter_value > extreme_value_limit\n ].shape[0]\n max_value = float(data_quality.meter_value.max())\n\n if n_days_total > 0:\n fraction_valid_meter_value_days = n_valid_meter_value_days / float(n_days_total)\n fraction_valid_temperature_days = n_valid_temperature_days / float(n_days_total)\n fraction_valid_days = n_valid_days / float(n_days_total)\n else:\n # unreachable, I think.\n fraction_valid_meter_value_days = 0\n fraction_valid_temperature_days = 0\n fraction_valid_days = 0\n\n if n_days_total != num_days:\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".incorrect_number_of_total_days\"\n ),\n description=(\"Total data span does not match the required value.\"),\n data={\"num_days\": num_days, \"n_days_total\": n_days_total},\n )\n )\n\n if fraction_valid_days < min_fraction_daily_coverage:\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".too_many_days_with_missing_data\"\n ),\n description=(\n \"Too many days in data have missing meter data or\"\n \" temperature data.\"\n ),\n data={\"n_valid_days\": n_valid_days, \"n_days_total\": n_days_total},\n )\n )\n\n if fraction_valid_meter_value_days < min_fraction_daily_coverage:\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".too_many_days_with_missing_meter_data\"\n ),\n description=(\"Too many days in data have missing meter data.\"),\n data={\n \"n_valid_meter_data_days\": n_valid_meter_value_days,\n \"n_days_total\": n_days_total,\n },\n )\n )\n\n if fraction_valid_temperature_days < min_fraction_daily_coverage:\n critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\"\n \".too_many_days_with_missing_temperature_data\"\n ),\n description=(\"Too many days in data have missing temperature data.\"),\n data={\n \"n_valid_temperature_data_days\": n_valid_temperature_days,\n \"n_days_total\": n_days_total,\n },\n )\n )\n\n if len(critical_warnings) > 0:\n status = \"FAIL\"\n else:\n status = \"PASS\"\n\n non_critical_warnings = []\n if n_extreme_values > 0:\n # CalTRACK 2.3.6\n non_critical_warnings.append(\n EEMeterWarning(\n qualified_name=(\n \"eemeter.caltrack_sufficiency_criteria\" \".extreme_values_detected\"\n ),\n description=(\n \"Extreme values (greater than (median + (3 * IQR)),\"\n \" must be flagged for manual review.\"\n ),\n data={\n \"n_extreme_values\": n_extreme_values,\n \"median\": median,\n \"upper_quantile\": upper_quantile,\n \"lower_quantile\": lower_quantile,\n \"extreme_value_limit\": extreme_value_limit,\n \"max_value\": max_value,\n },\n )\n )\n\n warnings = critical_warnings + non_critical_warnings\n sufficiency_data = {\n \"extra_data_after_requested_end_date\": {\n \"requested_end\": requested_end.isoformat() if requested_end else None,\n \"data_end\": data_end.isoformat(),\n \"n_days_end_gap\": n_days_end_gap,\n },\n \"extra_data_before_requested_start_date\": {\n \"requested_start\": requested_start.isoformat() if requested_start else None,\n \"data_start\": data_start.isoformat(),\n \"n_days_start_gap\": n_days_start_gap,\n },\n \"negative_meter_values\": {\"n_negative_meter_values\": n_negative_meter_values},\n \"incorrect_number_of_total_days\": {\n \"num_days\": num_days,\n \"n_days_total\": n_days_total,\n },\n \"too_many_days_with_missing_data\": {\n \"n_valid_days\": n_valid_days,\n \"n_days_total\": n_days_total,\n },\n \"too_many_days_with_missing_meter_data\": {\n \"n_valid_meter_data_days\": n_valid_meter_value_days,\n \"n_days_total\": n_days_total,\n },\n \"too_many_days_with_missing_temperature_data\": {\n \"n_valid_temperature_data_days\": n_valid_temperature_days,\n \"n_days_total\": n_days_total,\n },\n \"extreme_values_detected\": {\n \"n_extreme_values\": n_extreme_values,\n \"median\": median,\n \"upper_quantile\": upper_quantile,\n \"lower_quantile\": lower_quantile,\n \"extreme_value_limit\": extreme_value_limit,\n \"max_value\": max_value,\n },\n }\n\n return DataSufficiency(\n status=status,\n criteria_name=criteria_name,\n warnings=warnings,\n data=sufficiency_data,\n settings={\n \"num_days\": num_days,\n \"min_fraction_daily_coverage\": min_fraction_daily_coverage,\n \"min_fraction_hourly_temperature_coverage_per_period\": min_fraction_hourly_temperature_coverage_per_period,\n },\n )\n\n\ndef plot_caltrack_candidate(\n candidate,\n best=False,\n ax=None,\n title=None,\n figsize=None,\n temp_range=None,\n alpha=None,\n **kwargs\n):\n \"\"\" Plot a CalTRACK candidate model.\n\n Parameters\n ----------\n candidate : :any:`eemeter.CalTRACKUsagePerDayCandidateModel`\n A candidate model with a predict function.\n best : :any:`bool`, optional\n Whether this is the best candidate or not.\n ax : :any:`matplotlib.axes.Axes`, optional\n Existing axes to plot on.\n title : :any:`str`, optional\n Chart title.\n figsize : :any:`tuple`, optional\n (width, height) of chart.\n temp_range : :any:`tuple`, optional\n (min, max) temperatures to plot model.\n alpha : :any:`float` between 0 and 1, optional\n Transparency, 0 fully transparent, 1 fully opaque.\n **kwargs\n Keyword arguments for :any:`matplotlib.axes.Axes.plot`\n\n Returns\n -------\n ax : :any:`matplotlib.axes.Axes`\n Matplotlib axes.\n \"\"\"\n try:\n import matplotlib.pyplot as plt\n except ImportError: # pragma: no cover\n raise ImportError(\"matplotlib is required for plotting.\")\n\n if figsize is None:\n figsize = (10, 4)\n\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize)\n\n if candidate.status == \"QUALIFIED\":\n color = \"C2\"\n elif candidate.status == \"DISQUALIFIED\":\n color = \"C3\"\n else:\n return\n\n if best:\n color = \"C1\"\n alpha = 1\n\n temp_min, temp_max = (30, 90) if temp_range is None else temp_range\n\n temps = np.arange(temp_min, temp_max)\n\n data = {\"n_days\": np.ones(temps.shape)}\n\n prediction_index = pd.date_range(\n \"2017-01-01T00:00:00Z\", periods=len(temps), freq=\"D\"\n )\n\n temps_hourly = pd.Series(temps, index=prediction_index).resample(\"H\").ffill()\n\n prediction = candidate.predict(\n prediction_index, temps_hourly, \"daily\"\n ).result.predicted_usage\n\n plot_kwargs = {\"color\": color, \"alpha\": alpha or 0.3}\n plot_kwargs.update(kwargs)\n\n ax.plot(temps, prediction, **plot_kwargs)\n\n if title is not None:\n ax.set_title(title)\n\n return ax\n"
] |
[
[
"pandas.Series",
"numpy.isnan",
"numpy.arange",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"numpy.ones"
]
] |
Dianevera/heart-prediction
|
[
"c11e4ce92d501e1a398ee31b44d1552d8c6a29c5"
] |
[
"heartpredictions/LSTM/create_dataloaders.py"
] |
[
"import torch\n\ndef create_dataloaders(dataset, split_proportions, batch_size, display_informations=False):\n lengths = [round(len(dataset) * split) for split in split_proportions]\n r = 0\n for i in range(len(lengths)):\n r_tmp = lengths[i] % 3\n lengths[i] = lengths[i] - r_tmp\n r += r_tmp\n lengths[2] = lengths[2] + r\n\n\n #train_dataset, val_dataset, test_dataset = torch.utils.data.random_split(dataset, lengths=lengths, generator=torch.Generator().manual_seed(42))\n \n train_dataset = torch.utils.data.Subset(dataset, range(0, lengths[0]))\n val_dataset = torch.utils.data.Subset(dataset, range(lengths[0], lengths[0] + lengths[1]))\n test_dataset = torch.utils.data.Subset(dataset, range(lengths[0] + lengths[1], lengths[0] + lengths[1] + lengths[2]))\n print(\"lengths : \", lengths)\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=1,\n prefetch_factor=1,\n persistent_workers=False,\n pin_memory=True\n )\n\n val_dataloader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=4,\n prefetch_factor=2,\n persistent_workers=False,\n pin_memory=True\n )\n\n test_dataloader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=4,\n prefetch_factor=2,\n persistent_workers=False,\n pin_memory=True\n )\n\n if display_informations:\n print(f'Total dataset: {len(train_dataloader) + len(val_dataloader) + len(test_dataloader)}, '\n f'train dataset: {len(train_dataloader)}, val dataset: {len(val_dataloader)}, test_dataset: {len(test_dataloader)}')\n return train_dataloader, val_dataloader, test_dataloader\n\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
nlpaueb/GreekBERT
|
[
"2f0d84b65b77e8465bbbdbe77f9ec5a685b1ce15"
] |
[
"examples/xnli/bert/dataset.py"
] |
[
"import torch\nimport json\n\nfrom tqdm.auto import tqdm\nfrom torch.utils.data import Dataset\n\nfrom ...utils.sequences import pad_to_max\n\n\nclass XNLIBERTDataset(Dataset):\n L2I = {\n 'neutral': 0,\n 'contradiction': 1,\n 'contradictory': 1,\n 'entailment': 2\n }\n\n def __init__(self, file, tokenizer, preprocessing_function):\n self.ids = []\n self.texts = []\n self.texts_len = []\n self.targets = []\n\n for i, l in enumerate(tqdm(file)):\n ex = json.loads(l)\n cur_text, cur_len = self.process_example(\n ex,\n tokenizer,\n preprocessing_function\n )\n self.texts.append(cur_text)\n self.texts_len.append(cur_len)\n self.targets.append(self.L2I[ex['label']])\n self.ids.append(i)\n\n def __getitem__(self, index):\n return (\n self.ids[index],\n (self.texts[index], self.texts_len[index]),\n self.targets[index]\n )\n\n def __len__(self):\n return len(self.ids)\n\n @staticmethod\n def collate_fn(batch, pad_value):\n batch_zipped = list(zip(*batch))\n input_zipped = list(zip(*batch_zipped[1]))\n\n ids = batch_zipped[0]\n texts = torch.tensor(pad_to_max(input_zipped[0], pad_value=pad_value), dtype=torch.long)\n texts_len = torch.tensor(input_zipped[1], dtype=torch.int)\n\n target = torch.tensor(batch_zipped[2], dtype=torch.long)\n\n batch = {\n 'id': ids,\n 'input': [texts, texts_len],\n 'target': target\n }\n\n return batch\n\n @staticmethod\n def process_example(ex, tokenizer, preprocessing_function):\n tokens = tokenizer.encode(\n preprocessing_function(ex['prem']) if preprocessing_function else ex['prem'],\n text_pair=preprocessing_function(ex['hypo']) if preprocessing_function else ex['hypo'],\n add_special_tokens=True,\n max_length=512\n )\n\n return tokens, len(tokens)\n"
] |
[
[
"torch.tensor"
]
] |
MaximovaIrina/transformers
|
[
"185876392c0dcd4c4bb02f2750822144a3bee545"
] |
[
"src/transformers/models/detr/modeling_detr.py"
] |
[
"# coding=utf-8\n# Copyright 2021 Facebook AI Research The HuggingFace Inc. team. 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\"\"\" PyTorch DETR model. \"\"\"\n\n\nimport math\nimport random\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Tuple\n\nimport torch\nfrom torch import Tensor, nn\n\nfrom ...activations import ACT2FN\nfrom ...file_utils import (\n ModelOutput,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n is_scipy_available,\n is_timm_available,\n is_vision_available,\n replace_return_docstrings,\n requires_backends,\n)\nfrom ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput\nfrom ...modeling_utils import PreTrainedModel\nfrom ...utils import logging\nfrom .configuration_detr import DetrConfig\n\n\nif is_scipy_available():\n from scipy.optimize import linear_sum_assignment\n\nif is_vision_available():\n from .feature_extraction_detr import center_to_corners_format\n\nif is_timm_available():\n from timm import create_model\n\nlogger = logging.get_logger(__name__)\n\n_CONFIG_FOR_DOC = \"DetrConfig\"\n_CHECKPOINT_FOR_DOC = \"facebook/detr-resnet-50\"\n\nDETR_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"facebook/detr-resnet-50\",\n # See all DETR models at https://huggingface.co/models?filter=detr\n]\n\n\n@dataclass\nclass DetrDecoderOutput(BaseModelOutputWithCrossAttentions):\n \"\"\"\n Base class for outputs of the DETR decoder. This class adds one attribute to BaseModelOutputWithCrossAttentions,\n namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them\n gone through a layernorm. This is useful when training the model with auxiliary decoding losses.\n\n Args:\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of\n each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the\n weighted average in the self-attention heads.\n cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the\n attention softmax, used to compute the weighted average in the cross-attention heads.\n intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):\n Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a\n layernorm.\n \"\"\"\n\n intermediate_hidden_states: Optional[torch.FloatTensor] = None\n\n\n@dataclass\nclass DetrModelOutput(Seq2SeqModelOutput):\n \"\"\"\n Base class for outputs of the DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,\n namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them\n gone through a layernorm. This is useful when training the model with auxiliary decoding losses.\n\n Args:\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the decoder of the model.\n decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of\n each layer plus the initial embedding outputs.\n decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the\n attention softmax, used to compute the weighted average in the cross-attention heads.\n encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder of the model.\n encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of\n each layer plus the initial embedding outputs.\n encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):\n Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a\n layernorm.\n \"\"\"\n\n intermediate_hidden_states: Optional[torch.FloatTensor] = None\n\n\n@dataclass\nclass DetrObjectDetectionOutput(ModelOutput):\n \"\"\"\n Output type of [`DetrForObjectDetection`].\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):\n Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a\n bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized\n scale-invariant IoU loss.\n loss_dict (`Dict`, *optional*):\n A dictionary containing the individual losses. Useful for logging.\n logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):\n Classification logits (including no-object) for all queries.\n pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):\n Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These\n values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding\n possible padding). You can use [`~DetrFeatureExtractor.post_process`] to retrieve the\n unnormalized bounding boxes.\n auxiliary_outputs (`list[Dict]`, *optional*):\n Optional, only returned when auxilary losses are activated (i.e. `config.auxiliary_loss` is set to\n *True*) and labels are provided. It is a list of dictionaries containing the two above keys (`logits`\n and `pred_boxes`) for each decoder layer.\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the decoder of the model.\n decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of\n each layer plus the initial embedding outputs.\n decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the\n attention softmax, used to compute the weighted average in the cross-attention heads.\n encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder of the model.\n encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of\n each layer plus the initial embedding outputs.\n encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n loss_dict: Optional[Dict] = None\n logits: torch.FloatTensor = None\n pred_boxes: torch.FloatTensor = None\n auxiliary_outputs: Optional[List[Dict]] = None\n last_hidden_state: Optional[torch.FloatTensor] = None\n decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None\n cross_attentions: Optional[Tuple[torch.FloatTensor]] = None\n encoder_last_hidden_state: Optional[torch.FloatTensor] = None\n encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass DetrSegmentationOutput(ModelOutput):\n \"\"\"\n Output type of [`DetrForSegmentation`].\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):\n Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a\n bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized\n scale-invariant IoU loss.\n loss_dict (`Dict`, *optional*):\n A dictionary containing the individual losses. Useful for logging.\n logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):\n Classification logits (including no-object) for all queries.\n pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):\n Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These\n values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding\n possible padding). You can use [`~DetrFeatureExtractor.post_process`] to retrieve the\n unnormalized bounding boxes.\n pred_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`):\n Segmentation masks logits for all queries. See also\n [`~DetrFeatureExtractor.post_process_segmentation`] or\n [`~DetrFeatureExtractor.post_process_panoptic`] to evaluate instance and panoptic\n segmentation masks respectively.\n auxiliary_outputs (`list[Dict]`, *optional*):\n Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to\n *True*) and labels are provided. It is a list of dictionaries containing the two above keys (`logits`\n and `pred_boxes`) for each decoder layer.\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the decoder of the model.\n decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of\n each layer plus the initial embedding outputs.\n decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the\n attention softmax, used to compute the weighted average in the cross-attention heads.\n encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder of the model.\n encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of\n each layer plus the initial embedding outputs.\n encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to\n compute the weighted average in the self-attention heads.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n loss_dict: Optional[Dict] = None\n logits: torch.FloatTensor = None\n pred_boxes: torch.FloatTensor = None\n pred_masks: torch.FloatTensor = None\n auxiliary_outputs: Optional[List[Dict]] = None\n last_hidden_state: Optional[torch.FloatTensor] = None\n decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None\n cross_attentions: Optional[Tuple[torch.FloatTensor]] = None\n encoder_last_hidden_state: Optional[torch.FloatTensor] = None\n encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n# BELOW: utilities copied from\n# https://github.com/facebookresearch/detr/blob/master/backbone.py\nclass DetrFrozenBatchNorm2d(nn.Module):\n \"\"\"\n BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than\n torchvision.models.resnet[18,34,50,101] produce nans.\n \"\"\"\n\n def __init__(self, n):\n super(DetrFrozenBatchNorm2d, self).__init__()\n self.register_buffer(\"weight\", torch.ones(n))\n self.register_buffer(\"bias\", torch.zeros(n))\n self.register_buffer(\"running_mean\", torch.zeros(n))\n self.register_buffer(\"running_var\", torch.ones(n))\n\n def _load_from_state_dict(\n self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs\n ):\n num_batches_tracked_key = prefix + \"num_batches_tracked\"\n if num_batches_tracked_key in state_dict:\n del state_dict[num_batches_tracked_key]\n\n super(DetrFrozenBatchNorm2d, self)._load_from_state_dict(\n state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs\n )\n\n def forward(self, x):\n # move reshapes to the beginning\n # to make it user-friendly\n weight = self.weight.reshape(1, -1, 1, 1)\n bias = self.bias.reshape(1, -1, 1, 1)\n running_var = self.running_var.reshape(1, -1, 1, 1)\n running_mean = self.running_mean.reshape(1, -1, 1, 1)\n epsilon = 1e-5\n scale = weight * (running_var + epsilon).rsqrt()\n bias = bias - running_mean * scale\n return x * scale + bias\n\n\ndef replace_batch_norm(m, name=\"\"):\n for attr_str in dir(m):\n target_attr = getattr(m, attr_str)\n if isinstance(target_attr, nn.BatchNorm2d):\n frozen = DetrFrozenBatchNorm2d(target_attr.num_features)\n bn = getattr(m, attr_str)\n frozen.weight.data.copy_(bn.weight)\n frozen.bias.data.copy_(bn.bias)\n frozen.running_mean.data.copy_(bn.running_mean)\n frozen.running_var.data.copy_(bn.running_var)\n setattr(m, attr_str, frozen)\n for n, ch in m.named_children():\n replace_batch_norm(ch, n)\n\n\nclass DetrTimmConvEncoder(nn.Module):\n \"\"\"\n Convolutional encoder (backbone) from the timm library.\n\n nn.BatchNorm2d layers are replaced by DetrFrozenBatchNorm2d as defined above.\n\n \"\"\"\n\n def __init__(self, name: str, dilation: bool):\n super().__init__()\n\n kwargs = {}\n if dilation:\n kwargs[\"output_stride\"] = 16\n\n requires_backends(self, [\"timm\"])\n\n backbone = create_model(name, pretrained=True, features_only=True, out_indices=(1, 2, 3, 4), **kwargs)\n # replace batch norm by frozen batch norm\n with torch.no_grad():\n replace_batch_norm(backbone)\n self.model = backbone\n self.intermediate_channel_sizes = self.model.feature_info.channels()\n\n if \"resnet\" in name:\n for name, parameter in self.model.named_parameters():\n if \"layer2\" not in name and \"layer3\" not in name and \"layer4\" not in name:\n parameter.requires_grad_(False)\n\n def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):\n # send pixel_values through the model to get list of feature maps\n features = self.model(pixel_values)\n\n out = []\n for feature_map in features:\n # downsample pixel_mask to match shape of corresponding feature_map\n mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]\n out.append((feature_map, mask))\n return out\n\n\nclass DetrConvModel(nn.Module):\n \"\"\"\n This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.\n \"\"\"\n\n def __init__(self, conv_encoder, position_embedding):\n super().__init__()\n self.conv_encoder = conv_encoder\n self.position_embedding = position_embedding\n\n def forward(self, pixel_values, pixel_mask):\n # send pixel_values and pixel_mask through backbone to get list of (feature_map, pixel_mask) tuples\n out = self.conv_encoder(pixel_values, pixel_mask)\n pos = []\n for feature_map, mask in out:\n # position encoding\n pos.append(self.position_embedding(feature_map, mask).to(feature_map.dtype))\n\n return out, pos\n\n\ndef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):\n \"\"\"\n Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.\n \"\"\"\n bsz, src_len = mask.size()\n tgt_len = tgt_len if tgt_len is not None else src_len\n\n expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)\n\n inverted_mask = 1.0 - expanded_mask\n\n return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)\n\n\nclass DetrSinePositionEmbedding(nn.Module):\n \"\"\"\n This is a more standard version of the position embedding, very similar to the one used by the Attention is all you\n need paper, generalized to work on images.\n \"\"\"\n\n def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):\n super().__init__()\n self.embedding_dim = embedding_dim\n self.temperature = temperature\n self.normalize = normalize\n if scale is not None and normalize is False:\n raise ValueError(\"normalize should be True if scale is passed\")\n if scale is None:\n scale = 2 * math.pi\n self.scale = scale\n\n def forward(self, pixel_values, pixel_mask):\n assert pixel_mask is not None, \"No pixel mask provided\"\n y_embed = pixel_mask.cumsum(1, dtype=torch.float32)\n x_embed = pixel_mask.cumsum(2, dtype=torch.float32)\n if self.normalize:\n y_embed = y_embed / (y_embed[:, -1:, :] + 1e-6) * self.scale\n x_embed = x_embed / (x_embed[:, :, -1:] + 1e-6) * self.scale\n\n dim_t = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)\n dim_t = self.temperature ** (2 * (dim_t // 2) / self.embedding_dim)\n\n pos_x = x_embed[:, :, :, None] / dim_t\n pos_y = y_embed[:, :, :, None] / dim_t\n pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)\n pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)\n pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)\n return pos\n\n\nclass DetrLearnedPositionEmbedding(nn.Module):\n \"\"\"\n This module learns positional embeddings up to a fixed maximum size.\n \"\"\"\n\n def __init__(self, embedding_dim=256):\n super().__init__()\n self.row_embeddings = nn.Embedding(50, embedding_dim)\n self.column_embeddings = nn.Embedding(50, embedding_dim)\n\n def forward(self, pixel_values, pixel_mask=None):\n h, w = pixel_values.shape[-2:]\n i = torch.arange(w, device=pixel_values.device)\n j = torch.arange(h, device=pixel_values.device)\n x_emb = self.column_embeddings(i)\n y_emb = self.row_embeddings(j)\n pos = torch.cat([x_emb.unsqueeze(0).repeat(h, 1, 1), y_emb.unsqueeze(1).repeat(1, w, 1)], dim=-1)\n pos = pos.permute(2, 0, 1)\n pos = pos.unsqueeze(0)\n pos = pos.repeat(pixel_values.shape[0], 1, 1, 1)\n return pos\n\n\ndef build_position_encoding(config):\n n_steps = config.d_model // 2\n if config.position_embedding_type == \"sine\":\n # TODO find a better way of exposing other arguments\n position_embedding = DetrSinePositionEmbedding(n_steps, normalize=True)\n elif config.position_embedding_type == \"learned\":\n position_embedding = DetrLearnedPositionEmbedding(n_steps)\n else:\n raise ValueError(f\"Not supported {config.position_embedding_type}\")\n\n return position_embedding\n\n\nclass DetrAttention(nn.Module):\n \"\"\"\n Multi-headed attention from 'Attention Is All You Need' paper.\n\n Here, we add position embeddings to the queries and keys (as explained in the DETR paper).\n \"\"\"\n\n def __init__(\n self,\n embed_dim: int,\n num_heads: int,\n dropout: float = 0.0,\n is_decoder: bool = False,\n bias: bool = True,\n ):\n super().__init__()\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.head_dim = embed_dim // num_heads\n assert (\n self.head_dim * num_heads == self.embed_dim\n ), f\"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads}).\"\n self.scaling = self.head_dim ** -0.5\n\n self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n\n def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()\n\n def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):\n return tensor if position_embeddings is None else tensor + position_embeddings\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_embeddings: Optional[torch.Tensor] = None,\n key_value_states: Optional[torch.Tensor] = None,\n key_value_position_embeddings: Optional[torch.Tensor] = None,\n output_attentions: bool = False,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n \"\"\"Input shape: Batch x Time x Channel\"\"\"\n\n # if key_value_states are provided this layer is used as a cross-attention layer\n # for the decoder\n is_cross_attention = key_value_states is not None\n bsz, tgt_len, embed_dim = hidden_states.size()\n\n # add position embeddings to the hidden states before projecting to queries and keys\n if position_embeddings is not None:\n hidden_states_original = hidden_states\n hidden_states = self.with_pos_embed(hidden_states, position_embeddings)\n\n # add key-value position embeddings to the key value states\n if key_value_position_embeddings is not None:\n key_value_states_original = key_value_states\n key_value_states = self.with_pos_embed(key_value_states, key_value_position_embeddings)\n\n # get query proj\n query_states = self.q_proj(hidden_states) * self.scaling\n # get key, value proj\n if is_cross_attention:\n # cross_attentions\n key_states = self._shape(self.k_proj(key_value_states), -1, bsz)\n value_states = self._shape(self.v_proj(key_value_states_original), -1, bsz)\n else:\n # self_attention\n key_states = self._shape(self.k_proj(hidden_states), -1, bsz)\n value_states = self._shape(self.v_proj(hidden_states_original), -1, bsz)\n\n proj_shape = (bsz * self.num_heads, -1, self.head_dim)\n query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)\n key_states = key_states.view(*proj_shape)\n value_states = value_states.view(*proj_shape)\n\n src_len = key_states.size(1)\n\n attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))\n\n if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):\n raise ValueError(\n f\"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}\"\n )\n\n if attention_mask is not None:\n if attention_mask.size() != (bsz, 1, tgt_len, src_len):\n raise ValueError(\n f\"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}\"\n )\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n attn_weights = nn.functional.softmax(attn_weights, dim=-1)\n\n if output_attentions:\n # this operation is a bit awkward, but it's required to\n # make sure that attn_weights keeps its gradient.\n # In order to do so, attn_weights have to reshaped\n # twice and have to be reused in the following\n attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)\n else:\n attn_weights_reshaped = None\n\n attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)\n\n attn_output = torch.bmm(attn_probs, value_states)\n\n if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):\n raise ValueError(\n f\"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}\"\n )\n\n attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)\n attn_output = attn_output.transpose(1, 2)\n attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)\n\n attn_output = self.out_proj(attn_output)\n\n return attn_output, attn_weights_reshaped\n\n\nclass DetrEncoderLayer(nn.Module):\n def __init__(self, config: DetrConfig):\n super().__init__()\n self.embed_dim = config.d_model\n self.self_attn = DetrAttention(\n embed_dim=self.embed_dim,\n num_heads=config.encoder_attention_heads,\n dropout=config.attention_dropout,\n )\n self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)\n self.dropout = config.dropout\n self.activation_fn = ACT2FN[config.activation_function]\n self.activation_dropout = config.activation_dropout\n self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)\n self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)\n self.final_layer_norm = nn.LayerNorm(self.embed_dim)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: torch.Tensor,\n position_embeddings: torch.Tensor = None,\n output_attentions: bool = False,\n ):\n \"\"\"\n Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`\n attention_mask (`torch.FloatTensor`): attention mask of size\n `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n position_embeddings (`torch.FloatTensor`, *optional*): position embeddings, to be added to hidden_states.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n \"\"\"\n residual = hidden_states\n hidden_states, attn_weights = self.self_attn(\n hidden_states=hidden_states,\n attention_mask=attention_mask,\n position_embeddings=position_embeddings,\n output_attentions=output_attentions,\n )\n\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)\n\n hidden_states = self.fc2(hidden_states)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n\n if self.training:\n if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():\n clamp_value = torch.finfo(hidden_states.dtype).max - 1000\n hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\nclass DetrDecoderLayer(nn.Module):\n def __init__(self, config: DetrConfig):\n super().__init__()\n self.embed_dim = config.d_model\n\n self.self_attn = DetrAttention(\n embed_dim=self.embed_dim,\n num_heads=config.decoder_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=True,\n )\n self.dropout = config.dropout\n self.activation_fn = ACT2FN[config.activation_function]\n self.activation_dropout = config.activation_dropout\n\n self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)\n self.encoder_attn = DetrAttention(\n self.embed_dim,\n config.decoder_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=True,\n )\n self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)\n self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)\n self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)\n self.final_layer_norm = nn.LayerNorm(self.embed_dim)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_embeddings: Optional[torch.Tensor] = None,\n query_position_embeddings: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = False,\n ):\n \"\"\"\n Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`\n attention_mask (`torch.FloatTensor`): attention mask of size\n `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n position_embeddings (`torch.FloatTensor`, *optional*): position embeddings that are added to the queries and keys\n in the cross-attention layer.\n query_position_embeddings (`torch.FloatTensor`, *optional*): position embeddings that are added to the queries and keys\n in the self-attention layer.\n encoder_hidden_states (`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size\n `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n \"\"\"\n residual = hidden_states\n\n # Self Attention\n hidden_states, self_attn_weights = self.self_attn(\n hidden_states=hidden_states,\n position_embeddings=query_position_embeddings,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n )\n\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n\n # Cross-Attention Block\n cross_attn_weights = None\n if encoder_hidden_states is not None:\n residual = hidden_states\n\n hidden_states, cross_attn_weights = self.encoder_attn(\n hidden_states=hidden_states,\n position_embeddings=query_position_embeddings,\n key_value_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n key_value_position_embeddings=position_embeddings,\n output_attentions=output_attentions,\n )\n\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.encoder_attn_layer_norm(hidden_states)\n\n # Fully Connected\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)\n hidden_states = self.fc2(hidden_states)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (self_attn_weights, cross_attn_weights)\n\n return outputs\n\n\nclass DetrClassificationHead(nn.Module):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, input_dim: int, inner_dim: int, num_classes: int, pooler_dropout: float):\n super().__init__()\n self.dense = nn.Linear(input_dim, inner_dim)\n self.dropout = nn.Dropout(p=pooler_dropout)\n self.out_proj = nn.Linear(inner_dim, num_classes)\n\n def forward(self, hidden_states: torch.Tensor):\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.dense(hidden_states)\n hidden_states = torch.tanh(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.out_proj(hidden_states)\n return hidden_states\n\n\nclass DetrPreTrainedModel(PreTrainedModel):\n config_class = DetrConfig\n base_model_prefix = \"model\"\n main_input_name = \"pixel_values\"\n\n def _init_weights(self, module):\n std = self.config.init_std\n xavier_std = self.config.init_xavier_std\n\n if isinstance(module, DetrMHAttentionMap):\n nn.init.zeros_(module.k_linear.bias)\n nn.init.zeros_(module.q_linear.bias)\n nn.init.xavier_uniform_(module.k_linear.weight, gain=xavier_std)\n nn.init.xavier_uniform_(module.q_linear.weight, gain=xavier_std)\n elif isinstance(module, DetrLearnedPositionEmbedding):\n nn.init.uniform_(module.row_embeddings.weight)\n nn.init.uniform_(module.column_embeddings.weight)\n if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=std)\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=std)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, DetrDecoder):\n module.gradient_checkpointing = value\n\n\nDETR_START_DOCSTRING = r\"\"\"\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic\n methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,\n pruning heads etc.)\n\n This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to\n general usage and behavior.\n\n Parameters:\n config ([`DetrConfig`]):\n Model configuration class with all the parameters of the model. Initializing with a config file does not\n load the weights associated with the model, only the configuration. Check out the\n [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nDETR_INPUTS_DOCSTRING = r\"\"\"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it.\n\n Pixel values can be obtained using [`DetrFeatureExtractor`]. See\n [`DetrFeatureExtractor.__call__`] for details.\n\n pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):\n Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:\n\n - 1 for pixels that are real (i.e. **not masked**),\n - 0 for pixels that are padding (i.e. **masked**).\n\n [What are attention masks?](../glossary#attention-mask)\n\n decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, num_queries)`, *optional*):\n Not used by default. Can be used to mask object queries.\n encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):\n Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:\n `attentions`) `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`,\n *optional*) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the\n cross-attention of the decoder.\n inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you\n can choose to directly pass a flattened representation of an image.\n decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):\n Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an\n embedded representation.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\nclass DetrEncoder(DetrPreTrainedModel):\n \"\"\"\n Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a\n [`DetrEncoderLayer`].\n\n The encoder updates the flattened feature map through multiple self-attention layers.\n\n Small tweak for DETR:\n\n - position_embeddings are added to the forward pass.\n\n Args:\n config: DetrConfig\n \"\"\"\n\n def __init__(self, config: DetrConfig):\n super().__init__(config)\n\n self.dropout = config.dropout\n self.layerdrop = config.encoder_layerdrop\n\n self.layers = nn.ModuleList([DetrEncoderLayer(config) for _ in range(config.encoder_layers)])\n\n # in the original DETR, no layernorm is used at the end of the encoder, as \"normalize_before\" is set to False by default\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(\n self,\n inputs_embeds=None,\n attention_mask=None,\n position_embeddings=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n Args:\n inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.\n\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:\n\n - 1 for pixel features that are real (i.e. **not masked**),\n - 0 for pixel features that are padding (i.e. **masked**).\n\n [What are attention masks?](../glossary#attention-mask)\n\n position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Position embeddings that are added to the queries and keys in each self-attention layer.\n\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n hidden_states = inputs_embeds\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n # expand attention_mask\n if attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)\n\n encoder_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n for i, encoder_layer in enumerate(self.layers):\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = random.uniform(0, 1)\n if self.training and (dropout_probability < self.layerdrop): # skip the layer\n layer_outputs = (None, None)\n else:\n # we add position_embeddings as extra input to the encoder_layer\n layer_outputs = encoder_layer(\n hidden_states,\n attention_mask,\n position_embeddings=position_embeddings,\n output_attentions=output_attentions,\n )\n\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions\n )\n\n\nclass DetrDecoder(DetrPreTrainedModel):\n \"\"\"\n Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DetrDecoderLayer`].\n\n The decoder updates the query embeddings through multiple self-attention and cross-attention layers.\n\n Some small tweaks for DETR:\n\n - position_embeddings and query_position_embeddings are added to the forward pass.\n - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.\n\n Args:\n config: DetrConfig\n \"\"\"\n\n def __init__(self, config: DetrConfig):\n super().__init__(config)\n self.dropout = config.dropout\n self.layerdrop = config.decoder_layerdrop\n\n self.layers = nn.ModuleList([DetrDecoderLayer(config) for _ in range(config.decoder_layers)])\n # in DETR, the decoder uses layernorm after the last decoder layer output\n self.layernorm = nn.LayerNorm(config.d_model)\n\n self.gradient_checkpointing = False\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(\n self,\n inputs_embeds=None,\n attention_mask=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n position_embeddings=None,\n query_position_embeddings=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n Args:\n inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n The query embeddings that are passed into the decoder.\n\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:\n\n - 1 for queries that are **not masked**,\n - 0 for queries that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention\n of the decoder.\n encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):\n Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected\n in `[0, 1]`:\n\n - 1 for pixels that are real (i.e. **not masked**),\n - 0 for pixels that are padding (i.e. **masked**).\n\n position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Position embeddings that are added to the queries and keys in each cross-attention layer.\n query_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):, *optional*):\n Position embeddings that are added to the queries and keys in each self-attention layer.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if inputs_embeds is not None:\n hidden_states = inputs_embeds\n input_shape = inputs_embeds.size()[:-1]\n\n combined_attention_mask = None\n\n if attention_mask is not None and combined_attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n combined_attention_mask = combined_attention_mask + _expand_mask(\n attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]\n )\n\n # expand encoder attention mask\n if encoder_hidden_states is not None and encoder_attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])\n\n # optional intermediate hidden states\n intermediate = () if self.config.auxiliary_loss else None\n\n # decoder layers\n all_hidden_states = () if output_hidden_states else None\n all_self_attns = () if output_attentions else None\n all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None\n\n for idx, decoder_layer in enumerate(self.layers):\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n dropout_probability = random.uniform(0, 1)\n if self.training and (dropout_probability < self.layerdrop):\n continue\n\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(decoder_layer),\n hidden_states,\n combined_attention_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n None,\n )\n else:\n layer_outputs = decoder_layer(\n hidden_states,\n attention_mask=combined_attention_mask,\n position_embeddings=position_embeddings,\n query_position_embeddings=query_position_embeddings,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n output_attentions=output_attentions,\n )\n\n hidden_states = layer_outputs[0]\n\n if self.config.auxiliary_loss:\n hidden_states = self.layernorm(hidden_states)\n intermediate += (hidden_states,)\n\n if output_attentions:\n all_self_attns += (layer_outputs[1],)\n\n if encoder_hidden_states is not None:\n all_cross_attentions += (layer_outputs[2],)\n\n # finally, apply layernorm\n hidden_states = self.layernorm(hidden_states)\n\n # add hidden states from the last decoder layer\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n # stack intermediate decoder activations\n if self.config.auxiliary_loss:\n intermediate = torch.stack(intermediate)\n\n if not return_dict:\n return tuple(\n v\n for v in [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions, intermediate]\n if v is not None\n )\n return DetrDecoderOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attns,\n cross_attentions=all_cross_attentions,\n intermediate_hidden_states=intermediate,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n The bare DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without\n any specific head on top.\n \"\"\",\n DETR_START_DOCSTRING,\n)\nclass DetrModel(DetrPreTrainedModel):\n def __init__(self, config: DetrConfig):\n super().__init__(config)\n\n # Create backbone + positional encoding\n backbone = DetrTimmConvEncoder(config.backbone, config.dilation)\n position_embeddings = build_position_encoding(config)\n self.backbone = DetrConvModel(backbone, position_embeddings)\n\n # Create projection layer\n self.input_projection = nn.Conv2d(backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)\n\n self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)\n\n self.encoder = DetrEncoder(config)\n self.decoder = DetrDecoder(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_encoder(self):\n return self.encoder\n\n def get_decoder(self):\n return self.decoder\n\n def freeze_backbone(self):\n for name, param in self.backbone.conv_encoder.model.named_parameters():\n param.requires_grad_(False)\n\n def unfreeze_backbone(self):\n for name, param in self.backbone.conv_encoder.model.named_parameters():\n param.requires_grad_(True)\n\n @add_start_docstrings_to_model_forward(DETR_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=DetrModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n pixel_values,\n pixel_mask=None,\n decoder_attention_mask=None,\n encoder_outputs=None,\n inputs_embeds=None,\n decoder_inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n Returns:\n\n Examples::\n\n >>> from transformers import DetrFeatureExtractor, DetrModel\n >>> from PIL import Image\n >>> import requests\n\n >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg'\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = DetrFeatureExtractor.from_pretrained('facebook/detr-resnet-50')\n >>> model = DetrModel.from_pretrained('facebook/detr-resnet-50')\n >>> inputs = feature_extractor(images=image, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> last_hidden_states = outputs.last_hidden_state\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n batch_size, num_channels, height, width = pixel_values.shape\n device = pixel_values.device\n\n if pixel_mask is None:\n pixel_mask = torch.ones(((batch_size, height, width)), device=device)\n\n # First, sent pixel_values + pixel_mask through Backbone to obtain the features\n # pixel_values should be of shape (batch_size, num_channels, height, width)\n # pixel_mask should be of shape (batch_size, height, width)\n features, position_embeddings_list = self.backbone(pixel_values, pixel_mask)\n\n # get final feature map and downsampled mask\n feature_map, mask = features[-1]\n\n assert mask is not None, \"Backbone does not return downsampled pixel mask\"\n\n # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)\n projected_feature_map = self.input_projection(feature_map)\n\n # Third, flatten the feature map + position embeddings of shape NxCxHxW to NxCxHW, and permute it to NxHWxC\n # In other words, turn their shape into (batch_size, sequence_length, hidden_size)\n flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)\n position_embeddings = position_embeddings_list[-1].flatten(2).permute(0, 2, 1)\n\n flattened_mask = mask.flatten(1)\n\n # Fourth, sent flattened_features + flattened_mask + position embeddings through encoder\n # flattened_features is a Tensor of shape (batch_size, heigth*width, hidden_size)\n # flattened_mask is a Tensor of shape (batch_size, heigth*width)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n inputs_embeds=flattened_features,\n attention_mask=flattened_mask,\n position_embeddings=position_embeddings,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # Fifth, sent query embeddings + position embeddings through the decoder (which is conditioned on the encoder output)\n query_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)\n queries = torch.zeros_like(query_position_embeddings)\n\n # decoder outputs consists of (dec_features, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n inputs_embeds=queries,\n attention_mask=None,\n position_embeddings=position_embeddings,\n query_position_embeddings=query_position_embeddings,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=flattened_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return DetrModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks\n such as COCO detection.\n \"\"\",\n DETR_START_DOCSTRING,\n)\nclass DetrForObjectDetection(DetrPreTrainedModel):\n def __init__(self, config: DetrConfig):\n super().__init__(config)\n\n # DETR encoder-decoder model\n self.model = DetrModel(config)\n\n # Object detection heads\n self.class_labels_classifier = nn.Linear(\n config.d_model, config.num_labels + 1\n ) # We add one for the \"no object\" class\n self.bbox_predictor = DetrMLPPredictionHead(\n input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n # taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py\n @torch.jit.unused\n def _set_aux_loss(self, outputs_class, outputs_coord):\n # this is a workaround to make torchscript happy, as torchscript\n # doesn't support dictionary with non-homogeneous values, such\n # as a dict having both a Tensor and a list.\n return [{\"logits\": a, \"pred_boxes\": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]\n\n @add_start_docstrings_to_model_forward(DETR_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=DetrObjectDetectionOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n pixel_values,\n pixel_mask=None,\n decoder_attention_mask=None,\n encoder_outputs=None,\n inputs_embeds=None,\n decoder_inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (`List[Dict]` of len `(batch_size,)`, *optional*):\n Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the\n following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch\n respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import DetrFeatureExtractor, DetrForObjectDetection\n >>> from PIL import Image\n >>> import requests\n\n >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg'\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = DetrFeatureExtractor.from_pretrained('facebook/detr-resnet-50')\n >>> model = DetrForObjectDetection.from_pretrained('facebook/detr-resnet-50')\n\n >>> inputs = feature_extractor(images=image, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> # model predicts bounding boxes and corresponding COCO classes\n >>> logits = outputs.logits\n >>> bboxes = outputs.pred_boxes\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # First, sent images through DETR base model to obtain encoder + decoder outputs\n outputs = self.model(\n pixel_values,\n pixel_mask=pixel_mask,\n decoder_attention_mask=decoder_attention_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n # class logits + predicted bounding boxes\n logits = self.class_labels_classifier(sequence_output)\n pred_boxes = self.bbox_predictor(sequence_output).sigmoid()\n\n loss, loss_dict, auxiliary_outputs = None, None, None\n if labels is not None:\n # First: create the matcher\n matcher = DetrHungarianMatcher(\n class_cost=self.config.class_cost, bbox_cost=self.config.bbox_cost, giou_cost=self.config.giou_cost\n )\n # Second: create the criterion\n losses = [\"labels\", \"boxes\", \"cardinality\"]\n criterion = DetrLoss(\n matcher=matcher,\n num_classes=self.config.num_labels,\n eos_coef=self.config.eos_coefficient,\n losses=losses,\n )\n criterion.to(self.device)\n # Third: compute the losses, based on outputs and labels\n outputs_loss = {}\n outputs_loss[\"logits\"] = logits\n outputs_loss[\"pred_boxes\"] = pred_boxes\n if self.config.auxiliary_loss:\n intermediate = outputs.intermediate_hidden_states if return_dict else outputs[4]\n outputs_class = self.class_labels_classifier(intermediate)\n outputs_coord = self.bbox_predictor(intermediate).sigmoid()\n auxiliary_outputs = self._set_aux_loss(outputs_class, outputs_coord)\n outputs_loss[\"auxiliary_outputs\"] = auxiliary_outputs\n\n loss_dict = criterion(outputs_loss, labels)\n # Fourth: compute total loss, as a weighted sum of the various losses\n weight_dict = {\"loss_ce\": 1, \"loss_bbox\": self.config.bbox_loss_coefficient}\n weight_dict[\"loss_giou\"] = self.config.giou_loss_coefficient\n if self.config.auxiliary_loss:\n aux_weight_dict = {}\n for i in range(self.config.decoder_layers - 1):\n aux_weight_dict.update({k + f\"_{i}\": v for k, v in weight_dict.items()})\n weight_dict.update(aux_weight_dict)\n loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n\n if not return_dict:\n if auxiliary_outputs is not None:\n output = (logits, pred_boxes) + auxiliary_outputs + outputs\n else:\n output = (logits, pred_boxes) + outputs\n return ((loss, loss_dict) + output) if loss is not None else output\n\n return DetrObjectDetectionOutput(\n loss=loss,\n loss_dict=loss_dict,\n logits=logits,\n pred_boxes=pred_boxes,\n auxiliary_outputs=auxiliary_outputs,\n last_hidden_state=outputs.last_hidden_state,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks\n such as COCO panoptic.\n\n \"\"\",\n DETR_START_DOCSTRING,\n)\nclass DetrForSegmentation(DetrPreTrainedModel):\n def __init__(self, config: DetrConfig):\n super().__init__(config)\n\n # object detection model\n self.detr = DetrForObjectDetection(config)\n\n # segmentation head\n hidden_size, number_of_heads = config.d_model, config.encoder_attention_heads\n intermediate_channel_sizes = self.detr.model.backbone.conv_encoder.intermediate_channel_sizes\n\n self.mask_head = DetrMaskHeadSmallConv(\n hidden_size + number_of_heads, intermediate_channel_sizes[::-1][-3:], hidden_size\n )\n\n self.bbox_attention = DetrMHAttentionMap(\n hidden_size, hidden_size, number_of_heads, dropout=0.0, std=config.init_xavier_std\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(DETR_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=DetrSegmentationOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n pixel_values,\n pixel_mask=None,\n decoder_attention_mask=None,\n encoder_outputs=None,\n inputs_embeds=None,\n decoder_inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (`List[Dict]` of len `(batch_size,)`, *optional*):\n Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each\n dictionary containing at least the following 3 keys: 'class_labels', 'boxes' and 'masks' (the class labels,\n bounding boxes and segmentation masks of an image in the batch respectively). The class labels themselves\n should be a `torch.LongTensor` of len `(number of bounding boxes in the image,)`, the boxes a\n `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a\n `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import DetrFeatureExtractor, DetrForSegmentation\n >>> from PIL import Image\n >>> import requests\n\n >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg'\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = DetrFeatureExtractor.from_pretrained('facebook/detr-resnet-50-panoptic')\n >>> model = DetrForSegmentation.from_pretrained('facebook/detr-resnet-50-panoptic')\n\n >>> inputs = feature_extractor(images=image, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> # model predicts COCO classes, bounding boxes, and masks\n >>> logits = outputs.logits\n >>> bboxes = outputs.pred_boxes\n >>> masks = outputs.pred_masks\n ```\"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n batch_size, num_channels, height, width = pixel_values.shape\n device = pixel_values.device\n\n if pixel_mask is None:\n pixel_mask = torch.ones((batch_size, height, width), device=device)\n\n # First, get list of feature maps and position embeddings\n features, position_embeddings_list = self.detr.model.backbone(pixel_values, pixel_mask=pixel_mask)\n\n # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)\n feature_map, mask = features[-1]\n batch_size, num_channels, height, width = feature_map.shape\n projected_feature_map = self.detr.model.input_projection(feature_map)\n\n # Third, flatten the feature map + position embeddings of shape NxCxHxW to NxCxHW, and permute it to NxHWxC\n # In other words, turn their shape into (batch_size, sequence_length, hidden_size)\n flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)\n position_embeddings = position_embeddings_list[-1].flatten(2).permute(0, 2, 1)\n\n flattened_mask = mask.flatten(1)\n\n # Fourth, sent flattened_features + flattened_mask + position embeddings through encoder\n # flattened_features is a Tensor of shape (batch_size, heigth*width, hidden_size)\n # flattened_mask is a Tensor of shape (batch_size, heigth*width)\n if encoder_outputs is None:\n encoder_outputs = self.detr.model.encoder(\n inputs_embeds=flattened_features,\n attention_mask=flattened_mask,\n position_embeddings=position_embeddings,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # Fifth, sent query embeddings + position embeddings through the decoder (which is conditioned on the encoder output)\n query_position_embeddings = self.detr.model.query_position_embeddings.weight.unsqueeze(0).repeat(\n batch_size, 1, 1\n )\n queries = torch.zeros_like(query_position_embeddings)\n\n # decoder outputs consists of (dec_features, dec_hidden, dec_attn)\n decoder_outputs = self.detr.model.decoder(\n inputs_embeds=queries,\n attention_mask=None,\n position_embeddings=position_embeddings,\n query_position_embeddings=query_position_embeddings,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=flattened_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n # Sixth, compute logits, pred_boxes and pred_masks\n logits = self.detr.class_labels_classifier(sequence_output)\n pred_boxes = self.detr.bbox_predictor(sequence_output).sigmoid()\n\n memory = encoder_outputs[0].permute(0, 2, 1).view(batch_size, self.config.d_model, height, width)\n mask = flattened_mask.view(batch_size, height, width)\n\n # FIXME h_boxes takes the last one computed, keep this in mind\n # important: we need to reverse the mask, since in the original implementation the mask works reversed\n # bbox_mask is of shape (batch_size, num_queries, number_of_attention_heads in bbox_attention, height/32, width/32)\n bbox_mask = self.bbox_attention(sequence_output, memory, mask=~mask)\n\n seg_masks = self.mask_head(projected_feature_map, bbox_mask, [features[2][0], features[1][0], features[0][0]])\n\n pred_masks = seg_masks.view(batch_size, self.detr.config.num_queries, seg_masks.shape[-2], seg_masks.shape[-1])\n\n loss, loss_dict, auxiliary_outputs = None, None, None\n if labels is not None:\n # First: create the matcher\n matcher = DetrHungarianMatcher(\n class_cost=self.config.class_cost, bbox_cost=self.config.bbox_cost, giou_cost=self.config.giou_cost\n )\n # Second: create the criterion\n losses = [\"labels\", \"boxes\", \"cardinality\", \"masks\"]\n criterion = DetrLoss(\n matcher=matcher,\n num_classes=self.config.num_labels,\n eos_coef=self.config.eos_coefficient,\n losses=losses,\n )\n criterion.to(self.device)\n # Third: compute the losses, based on outputs and labels\n outputs_loss = {}\n outputs_loss[\"logits\"] = logits\n outputs_loss[\"pred_boxes\"] = pred_boxes\n outputs_loss[\"pred_masks\"] = pred_masks\n if self.config.auxiliary_loss:\n intermediate = decoder_outputs.intermediate_hidden_states if return_dict else decoder_outputs[-1]\n outputs_class = self.class_labels_classifier(intermediate)\n outputs_coord = self.bbox_predictor(intermediate).sigmoid()\n auxiliary_outputs = self._set_aux_loss(outputs_class, outputs_coord)\n outputs_loss[\"auxiliary_outputs\"] = auxiliary_outputs\n\n loss_dict = criterion(outputs_loss, labels)\n # Fourth: compute total loss, as a weighted sum of the various losses\n weight_dict = {\"loss_ce\": 1, \"loss_bbox\": self.config.bbox_loss_coefficient}\n weight_dict[\"loss_giou\"] = self.config.giou_loss_coefficient\n weight_dict[\"loss_mask\"] = self.config.mask_loss_coefficient\n weight_dict[\"loss_dice\"] = self.config.dice_loss_coefficient\n if self.config.auxiliary_loss:\n aux_weight_dict = {}\n for i in range(self.config.decoder_layers - 1):\n aux_weight_dict.update({k + f\"_{i}\": v for k, v in weight_dict.items()})\n weight_dict.update(aux_weight_dict)\n loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n\n if not return_dict:\n if auxiliary_outputs is not None:\n output = (logits, pred_boxes, pred_masks) + auxiliary_outputs + decoder_outputs + encoder_outputs\n else:\n output = (logits, pred_boxes, pred_masks) + decoder_outputs + encoder_outputs\n return ((loss, loss_dict) + output) if loss is not None else output\n\n return DetrSegmentationOutput(\n loss=loss,\n loss_dict=loss_dict,\n logits=logits,\n pred_boxes=pred_boxes,\n pred_masks=pred_masks,\n auxiliary_outputs=auxiliary_outputs,\n last_hidden_state=decoder_outputs.last_hidden_state,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )\n\n\ndef _expand(tensor, length: int):\n return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)\n\n\n# taken from https://github.com/facebookresearch/detr/blob/master/models/segmentation.py\nclass DetrMaskHeadSmallConv(nn.Module):\n \"\"\"\n Simple convolutional head, using group norm. Upsampling is done using a FPN approach\n \"\"\"\n\n def __init__(self, dim, fpn_dims, context_dim):\n super().__init__()\n\n assert (\n dim % 8 == 0\n ), \"The hidden_size + number of attention heads must be divisible by 8 as the number of groups in GroupNorm is set to 8\"\n\n inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64]\n\n self.lay1 = nn.Conv2d(dim, dim, 3, padding=1)\n self.gn1 = nn.GroupNorm(8, dim)\n self.lay2 = nn.Conv2d(dim, inter_dims[1], 3, padding=1)\n self.gn2 = nn.GroupNorm(8, inter_dims[1])\n self.lay3 = nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1)\n self.gn3 = nn.GroupNorm(8, inter_dims[2])\n self.lay4 = nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1)\n self.gn4 = nn.GroupNorm(8, inter_dims[3])\n self.lay5 = nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1)\n self.gn5 = nn.GroupNorm(8, inter_dims[4])\n self.out_lay = nn.Conv2d(inter_dims[4], 1, 3, padding=1)\n\n self.dim = dim\n\n self.adapter1 = nn.Conv2d(fpn_dims[0], inter_dims[1], 1)\n self.adapter2 = nn.Conv2d(fpn_dims[1], inter_dims[2], 1)\n self.adapter3 = nn.Conv2d(fpn_dims[2], inter_dims[3], 1)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_uniform_(m.weight, a=1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x: Tensor, bbox_mask: Tensor, fpns: List[Tensor]):\n # here we concatenate x, the projected feature map, of shape (batch_size, d_model, heigth/32, width/32) with\n # the bbox_mask = the attention maps of shape (batch_size, n_queries, n_heads, height/32, width/32).\n # We expand the projected feature map to match the number of heads.\n x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1)\n\n x = self.lay1(x)\n x = self.gn1(x)\n x = nn.functional.relu(x)\n x = self.lay2(x)\n x = self.gn2(x)\n x = nn.functional.relu(x)\n\n cur_fpn = self.adapter1(fpns[0])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay3(x)\n x = self.gn3(x)\n x = nn.functional.relu(x)\n\n cur_fpn = self.adapter2(fpns[1])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay4(x)\n x = self.gn4(x)\n x = nn.functional.relu(x)\n\n cur_fpn = self.adapter3(fpns[2])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay5(x)\n x = self.gn5(x)\n x = nn.functional.relu(x)\n\n x = self.out_lay(x)\n return x\n\n\nclass DetrMHAttentionMap(nn.Module):\n \"\"\"This is a 2D attention module, which only returns the attention softmax (no multiplication by value)\"\"\"\n\n def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):\n super().__init__()\n self.num_heads = num_heads\n self.hidden_dim = hidden_dim\n self.dropout = nn.Dropout(dropout)\n\n self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n\n self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5\n\n def forward(self, q, k, mask: Optional[Tensor] = None):\n q = self.q_linear(q)\n k = nn.functional.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)\n queries_per_head = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)\n keys_per_head = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])\n weights = torch.einsum(\"bqnc,bnchw->bqnhw\", queries_per_head * self.normalize_fact, keys_per_head)\n\n if mask is not None:\n weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float(\"-inf\"))\n weights = nn.functional.softmax(weights.flatten(2), dim=-1).view(weights.size())\n weights = self.dropout(weights)\n return weights\n\n\ndef dice_loss(inputs, targets, num_boxes):\n \"\"\"\n Compute the DICE loss, similar to generalized IOU for masks\n\n Args:\n inputs: A float tensor of arbitrary shape.\n The predictions for each example.\n targets: A float tensor with the same shape as inputs. Stores the binary\n classification label for each element in inputs (0 for the negative class and 1 for the positive\n class).\n \"\"\"\n inputs = inputs.sigmoid()\n inputs = inputs.flatten(1)\n numerator = 2 * (inputs * targets).sum(1)\n denominator = inputs.sum(-1) + targets.sum(-1)\n loss = 1 - (numerator + 1) / (denominator + 1)\n return loss.sum() / num_boxes\n\n\ndef sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):\n \"\"\"\n Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.\n\n Args:\n inputs: A float tensor of arbitrary shape.\n The predictions for each example.\n targets: A float tensor with the same shape as inputs. Stores the binary\n classification label for each element in inputs (0 for the negative class and 1 for the positive\n class).\n alpha: (optional) Weighting factor in range (0,1) to balance\n positive vs negative examples. Default = -1 (no weighting).\n gamma: Exponent of the modulating factor (1 - p_t) to\n balance easy vs hard examples.\n\n Returns:\n Loss tensor\n \"\"\"\n prob = inputs.sigmoid()\n ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction=\"none\")\n p_t = prob * targets + (1 - prob) * (1 - targets)\n loss = ce_loss * ((1 - p_t) ** gamma)\n\n if alpha >= 0:\n alpha_t = alpha * targets + (1 - alpha) * (1 - targets)\n loss = alpha_t * loss\n\n return loss.mean(1).sum() / num_boxes\n\n\n# taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py\nclass DetrLoss(nn.Module):\n \"\"\"\n This class computes the losses for DetrForObjectDetection/DetrForSegmentation. The process happens in two steps: 1)\n we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair\n of matched ground-truth / prediction (supervise class and box)\n \"\"\"\n\n def __init__(self, matcher, num_classes, eos_coef, losses):\n \"\"\"\n Create the criterion.\n\n A note on the num_classes parameter (copied from original repo in detr.py): \"the naming of the `num_classes`\n parameter of the criterion is somewhat misleading. it indeed corresponds to `max_obj_id + 1`, where max_obj_id\n is the maximum id for a class in your dataset. For example, COCO has a max_obj_id of 90, so we pass\n `num_classes` to be 91. As another example, for a dataset that has a single class with id 1, you should pass\n `num_classes` to be 2 (max_obj_id + 1). For more details on this, check the following discussion\n https://github.com/facebookresearch/detr/issues/108#issuecomment-650269223\"\n\n Parameters:\n matcher: module able to compute a matching between targets and proposals.\n num_classes: number of object categories, omitting the special no-object category.\n weight_dict: dict containing as key the names of the losses and as values their relative weight.\n eos_coef: relative classification weight applied to the no-object category.\n losses: list of all the losses to be applied. See get_loss for list of available losses.\n \"\"\"\n super().__init__()\n self.num_classes = num_classes\n self.matcher = matcher\n self.eos_coef = eos_coef\n self.losses = losses\n empty_weight = torch.ones(self.num_classes + 1)\n empty_weight[-1] = self.eos_coef\n self.register_buffer(\"empty_weight\", empty_weight)\n\n # removed logging parameter, which was part of the original implementation\n def loss_labels(self, outputs, targets, indices, num_boxes):\n \"\"\"\n Classification loss (NLL) targets dicts must contain the key \"class_labels\" containing a tensor of dim\n [nb_target_boxes]\n \"\"\"\n assert \"logits\" in outputs, \"No logits were found in the outputs\"\n src_logits = outputs[\"logits\"]\n\n idx = self._get_src_permutation_idx(indices)\n target_classes_o = torch.cat([t[\"class_labels\"][J] for t, (_, J) in zip(targets, indices)])\n target_classes = torch.full(\n src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device\n )\n target_classes[idx] = target_classes_o\n\n loss_ce = nn.functional.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)\n losses = {\"loss_ce\": loss_ce}\n\n return losses\n\n @torch.no_grad()\n def loss_cardinality(self, outputs, targets, indices, num_boxes):\n \"\"\"\n Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes.\n\n This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients.\n \"\"\"\n logits = outputs[\"logits\"]\n device = logits.device\n tgt_lengths = torch.as_tensor([len(v[\"class_labels\"]) for v in targets], device=device)\n # Count the number of predictions that are NOT \"no-object\" (which is the last class)\n card_pred = (logits.argmax(-1) != logits.shape[-1] - 1).sum(1)\n card_err = nn.functional.l1_loss(card_pred.float(), tgt_lengths.float())\n losses = {\"cardinality_error\": card_err}\n return losses\n\n def loss_boxes(self, outputs, targets, indices, num_boxes):\n \"\"\"\n Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss.\n\n Targets dicts must contain the key \"boxes\" containing a tensor of dim [nb_target_boxes, 4]. The target boxes\n are expected in format (center_x, center_y, w, h), normalized by the image size.\n \"\"\"\n assert \"pred_boxes\" in outputs, \"No predicted boxes found in outputs\"\n idx = self._get_src_permutation_idx(indices)\n src_boxes = outputs[\"pred_boxes\"][idx]\n target_boxes = torch.cat([t[\"boxes\"][i] for t, (_, i) in zip(targets, indices)], dim=0)\n\n loss_bbox = nn.functional.l1_loss(src_boxes, target_boxes, reduction=\"none\")\n\n losses = {}\n losses[\"loss_bbox\"] = loss_bbox.sum() / num_boxes\n\n loss_giou = 1 - torch.diag(\n generalized_box_iou(center_to_corners_format(src_boxes), center_to_corners_format(target_boxes))\n )\n losses[\"loss_giou\"] = loss_giou.sum() / num_boxes\n return losses\n\n def loss_masks(self, outputs, targets, indices, num_boxes):\n \"\"\"\n Compute the losses related to the masks: the focal loss and the dice loss.\n\n Targets dicts must contain the key \"masks\" containing a tensor of dim [nb_target_boxes, h, w].\n \"\"\"\n assert \"pred_masks\" in outputs, \"No predicted masks found in outputs\"\n\n src_idx = self._get_src_permutation_idx(indices)\n tgt_idx = self._get_tgt_permutation_idx(indices)\n src_masks = outputs[\"pred_masks\"]\n src_masks = src_masks[src_idx]\n masks = [t[\"masks\"] for t in targets]\n # TODO use valid to mask invalid areas due to padding in loss\n target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()\n target_masks = target_masks.to(src_masks)\n target_masks = target_masks[tgt_idx]\n\n # upsample predictions to the target size\n src_masks = nn.functional.interpolate(\n src_masks[:, None], size=target_masks.shape[-2:], mode=\"bilinear\", align_corners=False\n )\n src_masks = src_masks[:, 0].flatten(1)\n\n target_masks = target_masks.flatten(1)\n target_masks = target_masks.view(src_masks.shape)\n losses = {\n \"loss_mask\": sigmoid_focal_loss(src_masks, target_masks, num_boxes),\n \"loss_dice\": dice_loss(src_masks, target_masks, num_boxes),\n }\n return losses\n\n def _get_src_permutation_idx(self, indices):\n # permute predictions following indices\n batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])\n src_idx = torch.cat([src for (src, _) in indices])\n return batch_idx, src_idx\n\n def _get_tgt_permutation_idx(self, indices):\n # permute targets following indices\n batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])\n tgt_idx = torch.cat([tgt for (_, tgt) in indices])\n return batch_idx, tgt_idx\n\n def get_loss(self, loss, outputs, targets, indices, num_boxes):\n loss_map = {\n \"labels\": self.loss_labels,\n \"cardinality\": self.loss_cardinality,\n \"boxes\": self.loss_boxes,\n \"masks\": self.loss_masks,\n }\n assert loss in loss_map, f\"Loss {loss} not supported\"\n return loss_map[loss](outputs, targets, indices, num_boxes)\n\n def forward(self, outputs, targets):\n \"\"\"\n This performs the loss computation.\n\n Parameters:\n outputs: dict of tensors, see the output specification of the model for the format\n targets: list of dicts, such that len(targets) == batch_size.\n The expected keys in each dict depends on the losses applied, see each loss' doc\n \"\"\"\n outputs_without_aux = {k: v for k, v in outputs.items() if k != \"auxiliary_outputs\"}\n\n # Retrieve the matching between the outputs of the last layer and the targets\n indices = self.matcher(outputs_without_aux, targets)\n\n # Compute the average number of target boxes accross all nodes, for normalization purposes\n num_boxes = sum(len(t[\"class_labels\"]) for t in targets)\n num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)\n # (Niels): comment out function below, distributed training to be added\n # if is_dist_avail_and_initialized():\n # torch.distributed.all_reduce(num_boxes)\n # (Niels) in original implementation, num_boxes is divided by get_world_size()\n num_boxes = torch.clamp(num_boxes, min=1).item()\n\n # Compute all the requested losses\n losses = {}\n for loss in self.losses:\n losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))\n\n # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.\n if \"auxiliary_outputs\" in outputs:\n for i, auxiliary_outputs in enumerate(outputs[\"auxiliary_outputs\"]):\n indices = self.matcher(auxiliary_outputs, targets)\n for loss in self.losses:\n if loss == \"masks\":\n # Intermediate masks losses are too costly to compute, we ignore them.\n continue\n l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)\n l_dict = {k + f\"_{i}\": v for k, v in l_dict.items()}\n losses.update(l_dict)\n\n return losses\n\n\n# taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py\nclass DetrMLPPredictionHead(nn.Module):\n \"\"\"\n Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,\n height and width of a bounding box w.r.t. an image.\n\n Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py\n\n \"\"\"\n\n def __init__(self, input_dim, hidden_dim, output_dim, num_layers):\n super().__init__()\n self.num_layers = num_layers\n h = [hidden_dim] * (num_layers - 1)\n self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n\n def forward(self, x):\n for i, layer in enumerate(self.layers):\n x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n return x\n\n\n# taken from https://github.com/facebookresearch/detr/blob/master/models/matcher.py\nclass DetrHungarianMatcher(nn.Module):\n \"\"\"\n This class computes an assignment between the targets and the predictions of the network.\n\n For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more\n predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are\n un-matched (and thus treated as non-objects).\n \"\"\"\n\n def __init__(self, class_cost: float = 1, bbox_cost: float = 1, giou_cost: float = 1):\n \"\"\"\n Creates the matcher.\n\n Params:\n class_cost: This is the relative weight of the classification error in the matching cost\n bbox_cost: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost\n giou_cost: This is the relative weight of the giou loss of the bounding box in the matching cost\n \"\"\"\n super().__init__()\n\n requires_backends(self, [\"scipy\"])\n\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n assert class_cost != 0 or bbox_cost != 0 or giou_cost != 0, \"All costs of the Matcher can't be 0\"\n\n @torch.no_grad()\n def forward(self, outputs, targets):\n \"\"\"\n Performs the matching.\n\n Params:\n outputs: This is a dict that contains at least these entries:\n \"logits\": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits\n \"pred_boxes\": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates\n targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:\n \"class_labels\": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth\n objects in the target) containing the class labels \"boxes\": Tensor of dim [num_target_boxes, 4]\n containing the target box coordinates\n\n Returns:\n A list of size batch_size, containing tuples of (index_i, index_j) where:\n\n - index_i is the indices of the selected predictions (in order)\n - index_j is the indices of the corresponding selected targets (in order)\n For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes)\n \"\"\"\n bs, num_queries = outputs[\"logits\"].shape[:2]\n\n # We flatten to compute the cost matrices in a batch\n out_prob = outputs[\"logits\"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes]\n out_bbox = outputs[\"pred_boxes\"].flatten(0, 1) # [batch_size * num_queries, 4]\n\n # Also concat the target labels and boxes\n tgt_ids = torch.cat([v[\"class_labels\"] for v in targets])\n tgt_bbox = torch.cat([v[\"boxes\"] for v in targets])\n\n # Compute the classification cost. Contrary to the loss, we don't use the NLL,\n # but approximate it in 1 - proba[target class].\n # The 1 is a constant that doesn't change the matching, it can be ommitted.\n class_cost = -out_prob[:, tgt_ids]\n\n # Compute the L1 cost between boxes\n bbox_cost = torch.cdist(out_bbox, tgt_bbox, p=1)\n\n # Compute the giou cost between boxes\n giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(tgt_bbox))\n\n # Final cost matrix\n cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost\n cost_matrix = cost_matrix.view(bs, num_queries, -1).cpu()\n\n sizes = [len(v[\"boxes\"]) for v in targets]\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\n\n# below: bounding box utilities taken from https://github.com/facebookresearch/detr/blob/master/util/box_ops.py\n\n\ndef _upcast(t: Tensor) -> Tensor:\n # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type\n if t.is_floating_point():\n return t if t.dtype in (torch.float32, torch.float64) else t.float()\n else:\n return t if t.dtype in (torch.int32, torch.int64) else t.int()\n\n\ndef box_area(boxes: Tensor) -> Tensor:\n \"\"\"\n Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.\n\n Args:\n boxes (Tensor[N, 4]): boxes for which the area will be computed. They\n are expected to be in (x1, y1, x2, y2) format with `0 <= x1 < x2` and `0 <= y1 < y2`.\n\n Returns:\n area (Tensor[N]): area for each box\n \"\"\"\n boxes = _upcast(boxes)\n return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])\n\n\n# modified from torchvision to also return the union\ndef box_iou(boxes1, boxes2):\n area1 = box_area(boxes1)\n area2 = box_area(boxes2)\n\n lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]\n rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]\n\n wh = (rb - lt).clamp(min=0) # [N,M,2]\n inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]\n\n union = area1[:, None] + area2 - inter\n\n iou = inter / union\n return iou, union\n\n\ndef generalized_box_iou(boxes1, boxes2):\n \"\"\"\n Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.\n\n Returns:\n a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)\n \"\"\"\n # degenerate boxes gives inf / nan results\n # so do an early check\n assert (boxes1[:, 2:] >= boxes1[:, :2]).all()\n assert (boxes2[:, 2:] >= boxes2[:, :2]).all()\n iou, union = box_iou(boxes1, boxes2)\n\n lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])\n rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])\n\n wh = (rb - lt).clamp(min=0) # [N,M,2]\n area = wh[:, :, 0] * wh[:, :, 1]\n\n return iou - (area - union) / area\n\n\n# below: taken from https://github.com/facebookresearch/detr/blob/master/util/misc.py#L306\n\n\ndef _max_by_axis(the_list):\n # type: (List[List[int]]) -> List[int]\n maxes = the_list[0]\n for sublist in the_list[1:]:\n for index, item in enumerate(sublist):\n maxes[index] = max(maxes[index], item)\n return maxes\n\n\nclass NestedTensor(object):\n def __init__(self, tensors, mask: Optional[Tensor]):\n self.tensors = tensors\n self.mask = mask\n\n def to(self, device):\n # type: (Device) -> NestedTensor # noqa\n cast_tensor = self.tensors.to(device)\n mask = self.mask\n if mask is not None:\n cast_mask = mask.to(device)\n else:\n cast_mask = None\n return NestedTensor(cast_tensor, cast_mask)\n\n def decompose(self):\n return self.tensors, self.mask\n\n def __repr__(self):\n return str(self.tensors)\n\n\ndef nested_tensor_from_tensor_list(tensor_list: List[Tensor]):\n if tensor_list[0].ndim == 3:\n max_size = _max_by_axis([list(img.shape) for img in tensor_list])\n batch_shape = [len(tensor_list)] + max_size\n b, c, h, w = batch_shape\n dtype = tensor_list[0].dtype\n device = tensor_list[0].device\n tensor = torch.zeros(batch_shape, dtype=dtype, device=device)\n mask = torch.ones((b, h, w), dtype=torch.bool, device=device)\n for img, pad_img, m in zip(tensor_list, tensor, mask):\n pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n m[: img.shape[1], : img.shape[2]] = False\n else:\n raise ValueError(\"Only 3-dimensional tensors are supported\")\n return NestedTensor(tensor, mask)\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.nn.init.uniform_",
"torch.max",
"torch.nn.functional.l1_loss",
"torch.nn.functional.dropout",
"torch.cat",
"torch.zeros",
"torch.nn.Embedding",
"torch.tanh",
"torch.cdist",
"torch.no_grad",
"torch.nn.functional.interpolate",
"torch.finfo",
"torch.full_like",
"scipy.optimize.linear_sum_assignment",
"torch.nn.Dropout",
"torch.ones",
"torch.einsum",
"torch.nn.functional.relu",
"torch.bmm",
"torch.arange",
"torch.nn.GroupNorm",
"torch.isinf",
"torch.full",
"torch.nn.init.constant_",
"torch.min",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.nn.Linear",
"torch.nn.init.zeros_",
"torch.stack",
"torch.as_tensor",
"torch.isnan",
"torch.nn.LayerNorm",
"torch.nn.init.kaiming_uniform_",
"torch.nn.init.xavier_uniform_",
"torch.clamp"
]
] |
krishanr/geo-deep-learning
|
[
"990ca1799dfeef317fe7438ec2f3eba9dfad70d5"
] |
[
"utils/augmentation.py"
] |
[
"# WARNING: data being augmented may be scaled to (0,1) rather, for example, (0,255). Therefore, implementing radiometric\n# augmentations (ex.: changing hue, saturation, brightness, contrast) may give undesired results.\n# Scaling process is done in images_to_samples.py l.215\nimport numbers\nimport warnings\nfrom typing import Sequence\n\nimport torch\n# import torch should be first. Unclear issue, mentioned here: https://github.com/pytorch/pytorch/issues/2083\nimport random\nimport numpy as np\nfrom skimage import transform, exposure\nfrom torchvision import transforms\n\nfrom utils.utils import get_key_def, pad, minmax_scale, BGR_to_RGB\n\n\ndef compose_transforms(params, dataset, type='', ignore_index=None):\n \"\"\"\n Function to compose the transformations to be applied on every batches.\n :param params: (dict) Parameters found in the yaml config file\n :param dataset: (str) One of 'trn', 'val', 'tst'\n :param type: (str) One of 'geometric', 'radiometric'\n :return: (obj) PyTorch's compose object of the transformations to be applied.\n \"\"\"\n lst_trans = []\n input_space = get_key_def('BGR_to_RGB', params['global'], False)\n scale = get_key_def('scale_data', params['global'], None)\n norm_mean = get_key_def('mean', params['training']['normalization'])\n norm_std = get_key_def('std', params['training']['normalization'])\n random_radiom_trim_range = get_key_def('random_radiom_trim_range', params['training']['augmentation'], None)\n\n if dataset == 'trn':\n\n if type == 'radiometric':\n noise = get_key_def('noise', params['training']['augmentation'], None)\n\n if random_radiom_trim_range: # Contrast stretching\n lst_trans.append(RadiometricTrim(random_range=random_radiom_trim_range)) # FIXME: test this. Assure compatibility with CRIM devs (don't trim metadata)\n\n if noise:\n raise NotImplementedError\n\n elif type == 'geometric':\n geom_scale_range = get_key_def('geom_scale_range', params['training']['augmentation'], None)\n hflip = get_key_def('hflip_prob', params['training']['augmentation'], None)\n rotate_prob = get_key_def('rotate_prob', params['training']['augmentation'], None)\n rotate_limit = get_key_def('rotate_limit', params['training']['augmentation'], None)\n crop_size = get_key_def('target_size', params['training'], None)\n\n if geom_scale_range: # TODO: test this.\n lst_trans.append(GeometricScale(range=geom_scale_range))\n\n if hflip:\n lst_trans.append(HorizontalFlip(prob=params['training']['augmentation']['hflip_prob']))\n\n if rotate_limit and rotate_prob:\n lst_trans.append(RandomRotationTarget(limit=rotate_limit, prob=rotate_prob, ignore_index=ignore_index))\n\n if crop_size:\n lst_trans.append(RandomCrop(sample_size=crop_size, ignore_index=ignore_index))\n\n if type == 'totensor':\n if not dataset == 'trn' and random_radiom_trim_range: # Contrast stretching at eval. Use mean of provided range\n RadiometricTrim.input_checker(random_radiom_trim_range) # Assert range is number or 2 element sequence\n if isinstance(random_radiom_trim_range, numbers.Number):\n trim_at_eval = random_radiom_trim_range\n else:\n trim_at_eval = round((random_radiom_trim_range[-1] - random_radiom_trim_range[0]) / 2, 1)\n lst_trans.append(RadiometricTrim(random_range=[trim_at_eval, trim_at_eval]))\n\n if input_space:\n lst_trans.append(BgrToRgb(input_space))\n\n if scale:\n lst_trans.append(Scale(scale)) # TODO: assert coherence with below normalization\n\n if norm_mean and norm_std:\n lst_trans.append(Normalize(mean=params['training']['normalization']['mean'],\n std=params['training']['normalization']['std']))\n\n lst_trans.append(ToTensorTarget()) # Send channels first, convert numpy array to torch tensor\n\n return transforms.Compose(lst_trans)\n\n\nclass RadiometricTrim(object):\n \"\"\"Trims values left and right of the raster's histogram. Also called linear scaling or enhancement.\n Percentile, chosen randomly based on inputted range, applies to both left and right sides of the histogram.\n Ex.: Values below the 1.7th and above the 98.3th percentile will be trimmed if random value is 1.7\"\"\"\n def __init__(self, random_range):\n \"\"\"\n @param random_range: numbers.Number (float or int) or Sequence (list or tuple) with length of 2\n \"\"\"\n random_range = self.input_checker(random_range)\n self.range = random_range\n \n @staticmethod\n def input_checker(input_param):\n if not isinstance(input_param, (numbers.Number, Sequence)):\n raise TypeError('Got inappropriate range arg')\n\n if isinstance(input_param, Sequence) and len(input_param) != 2:\n raise ValueError(f\"Range must be an int or a 2 element tuple or list, \"\n f\"not a {len(input_param)} element {type(input_param)}.\")\n\n if isinstance(input_param, numbers.Number):\n input_param = [input_param, input_param]\n return input_param\n\n def __call__(self, sample):\n # Choose trimming percentile withing inputted range\n trim = round(random.uniform(self.range[0], self.range[-1]), 1)\n # Determine output range from datatype\n out_dtype = sample['metadata']['dtype']\n # Create empty array with shape of input image\n rescaled_sat_img = np.empty(sample['sat_img'].shape, dtype=sample['sat_img'].dtype)\n # Loop through bands\n for band_idx in range(sample['sat_img'].shape[2]):\n band = sample['sat_img'][:, :, band_idx]\n band_histogram = sample['metadata']['source_raster_bincount'][f'band{band_idx}']\n # Determine what is the index of nonzero pixel corresponding to left and right trim percentile\n sum_nonzero_pix_per_band = sum(band_histogram)\n left_pixel_idx = round(sum_nonzero_pix_per_band / 100 * trim)\n right_pixel_idx = round(sum_nonzero_pix_per_band / 100 * (100-trim))\n cumulative_pixel_count = 0\n # TODO: can this for loop be optimized? Also, this hasn't been tested with non 8-bit data. Should be fine though.\n # Loop through pixel values of given histogram\n for pixel_val, count_per_pix_val in enumerate(band_histogram):\n lower_limit = cumulative_pixel_count\n upper_limit = cumulative_pixel_count + count_per_pix_val\n # Check if left and right pixel indices are contained in current lower and upper pixels count limits\n if lower_limit <= left_pixel_idx <= upper_limit:\n left_pix_val = pixel_val\n if lower_limit <= right_pixel_idx <= upper_limit:\n right_pix_val = pixel_val\n cumulative_pixel_count += count_per_pix_val\n # Enhance using above left and right pixel values as in_range\n rescaled_band = exposure.rescale_intensity(band, in_range=(left_pix_val, right_pix_val), out_range=out_dtype)\n # Write each enhanced band to empty array\n rescaled_sat_img[:, :, band_idx] = rescaled_band\n sample['sat_img'] = rescaled_sat_img\n return sample\n\n\nclass Scale(object):\n \"\"\"\n Scale array values from range [0,255] or [0,65535] to values in config ([0,1] or [-1, 1])\n Guidelines for pre-processing: http://cs231n.github.io/neural-networks-2/#datapre\n \"\"\"\n def __init__(self, range):\n if isinstance(range, Sequence) and len(range) == 2:\n self.sc_min = range[0]\n self.sc_max = range[1]\n else:\n raise TypeError('Got inappropriate scale arg')\n\n @staticmethod\n def range_values_raster(raster, dtype):\n min_val, max_val = np.nanmin(raster), np.nanmax(raster)\n if 'int' in dtype:\n orig_range = (np.iinfo(dtype).min, np.iinfo(dtype).max)\n elif min_val >= 0 and max_val <= 255:\n orig_range = (0, 255)\n warnings.warn(f\"Values in input image of shape {raster.shape} \"\n f\"range from {min_val} to {max_val}.\"\n f\"Image will be considered 8 bit for scaling.\")\n elif min_val >= 0 and max_val <= 65535:\n orig_range = (0, 65535)\n warnings.warn(f\"Values in input image of shape {raster.shape} \"\n f\"range from {min_val} to {max_val}.\"\n f\"Image will be considered 16 bit for scaling.\")\n else:\n raise ValueError(f\"Invalid values in input image. They should range from 0 to 255 or 65535, not\"\n f\"{min_val} to {max_val}.\")\n return orig_range\n\n\n def __call__(self, sample):\n \"\"\"\n Args:\n sample (ndarray): Image to be scaled.\n\n Returns:\n ndarray: Scaled image.\n \"\"\"\n out_dtype = sample['metadata']['dtype']\n orig_range = self.range_values_raster(sample['sat_img'], out_dtype)\n sample['sat_img'] = minmax_scale(img=sample['sat_img'], orig_range=orig_range, scale_range=(self.sc_min, self.sc_max))\n\n return sample\n\n\nclass GeometricScale(object):\n \"\"\"Randomly resize image according to a certain range.\"\"\"\n def __init__(self, range):\n self.range = range\n\n def __call__(self, sample):\n scale_factor = round(random.uniform(range[0], range[-1]), 1)\n output_width = sample['sat_img'].shape[0] * scale_factor\n output_height = sample['sat_img'].shape[1] * scale_factor\n sat_img = transform.resize(sample['sat_img'], output_shape=(output_height, output_width))\n map_img = transform.resize(sample['map_img'], output_shape=(output_height, output_width))\n sample['sat_img'] = sat_img\n sample['map_img'] = map_img\n return sample\n\n\nclass RandomRotationTarget(object):\n \"\"\"Rotate the image and target randomly.\"\"\"\n def __init__(self, limit, prob, ignore_index):\n self.limit = limit\n self.prob = prob\n self.ignore_index = ignore_index\n\n def __call__(self, sample):\n if random.random() < self.prob:\n angle = np.random.uniform(-self.limit, self.limit)\n sat_img = transform.rotate(sample['sat_img'], angle, preserve_range=True, cval=np.nan)\n map_img = transform.rotate(sample['map_img'], angle, preserve_range=True, order=0, cval=self.ignore_index)\n sample['sat_img'] = sat_img\n sample['map_img'] = map_img\n return sample\n else:\n return sample\n\n\nclass HorizontalFlip(object):\n \"\"\"Flip the input image and reference map horizontally, with a probability.\"\"\"\n def __init__(self, prob):\n self.prob = prob\n\n def __call__(self, sample):\n if random.random() < self.prob:\n sat_img = np.ascontiguousarray(sample['sat_img'][:, ::-1, ...])\n map_img = np.ascontiguousarray(sample['map_img'][:, ::-1, ...])\n sample['sat_img'] = sat_img\n sample['map_img'] = map_img\n return sample\n\n\nclass RandomCrop(object): # TODO: what to do with overlap in samples_prep (images_to_samples, l.106)? overlap doesn't need to be larger than, say, 5%\n \"\"\"Randomly crop image according to a certain dimension.\n Adapted from https://pytorch.org/docs/stable/_modules/torchvision/transforms/transforms.html#RandomCrop\n to support >3 band images (not currently supported by PIL)\"\"\"\n def __init__(self, sample_size, padding=3, pad_if_needed=True, ignore_index=0):\n if isinstance(sample_size, numbers.Number):\n self.size = (int(sample_size), int(sample_size))\n else:\n self.size = sample_size\n self.padding = padding\n self.pad_if_needed = pad_if_needed\n self.ignore_index = ignore_index\n\n @staticmethod\n def get_params(img, output_size):\n \"\"\"Get parameters for ``crop`` for a random crop.\n\n Args:\n img (ndarray): Image to be cropped.\n output_size (tuple): Expected output size of the crop.\n\n Returns:\n tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.\n \"\"\"\n h, w = img.shape[:2]\n th, tw = output_size\n if w == tw and h == th:\n return 0, 0, h, w\n\n i = random.randint(0, h - th)\n j = random.randint(0, w - tw)\n return i, j, th, tw\n\n def __call__(self, sample):\n \"\"\"\n Args:\n sample (ndarray): Image to be cropped.\n\n Returns:\n ndarray: Cropped image.\n \"\"\"\n sat_img = sample['sat_img']\n map_img = sample['map_img']\n\n if self.padding is not None:\n sat_img = pad(sat_img, self.padding, np.nan) # Pad with nan values for sat_img\n map_img = pad(map_img, self.padding, self.ignore_index) # Pad with dontcare values for map_img\n\n # pad the height if needed\n if self.pad_if_needed and sat_img.shape[0] < self.size[0]:\n sat_img = pad(sat_img, (0, self.size[0] - sat_img.shape[0]), np.nan)\n # pad the width if needed\n if self.pad_if_needed and sat_img.shape[1] < self.size[1]:\n sample = pad(sat_img, (self.size[1] - sat_img.shape[1], 0), np.nan)\n\n # pad the height if needed\n if self.pad_if_needed and map_img.shape[0] < self.size[0]:\n map_img = pad(map_img, (0, self.size[0] - map_img.shape[0]), self.ignore_index)\n # pad the width if needed\n if self.pad_if_needed and map_img.shape[1] < self.size[1]:\n map_img = pad(map_img, (self.size[1] - map_img.shape[1], 0), self.ignore_index)\n\n i, j, h, w = self.get_params(sat_img, self.size)\n\n sat_img = sat_img[i:i + h, j:j + w]\n map_img = map_img[i:i + h, j:j + w]\n\n sample['sat_img'] = sat_img\n sample['map_img'] = map_img\n return sample\n\n def __repr__(self):\n return self.__class__.__name__ + '(size={0}, padding={1})'.format(self.size, self.padding)\n\n\nclass Normalize(object):\n \"\"\"Normalize Image with Mean and STD and similar to Pytorch(transform.Normalize) function \"\"\"\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, sample):\n if self.mean or self.std != []:\n sat_img = (sample['sat_img'] - self.mean) / self.std\n sample['sat_img'] = sat_img\n return sample\n else:\n return sample\n\nclass BgrToRgb(object):\n \"\"\"Normalize Image with Mean and STD and similar to Pytorch(transform.Normalize) function \"\"\"\n\n def __init__(self, bgr_to_rgb):\n self.bgr_to_rgb = bgr_to_rgb\n\n def __call__(self, sample):\n sat_img = BGR_to_RGB(sample['sat_img']) if self.bgr_to_rgb else sample['sat_img']\n sample['sat_img'] = sat_img\n\n return sample\n\n\nclass ToTensorTarget(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n def __call__(self, sample):\n sat_img = np.nan_to_num(sample['sat_img'], copy=False)\n sat_img = np.float32(np.transpose(sat_img, (2, 0, 1)))\n sat_img = torch.from_numpy(sat_img)\n\n map_img = None\n if 'map_img' in sample.keys(): # This can also be used in inference.\n map_img = np.int64(sample['map_img'])\n map_img = torch.from_numpy(map_img)\n return {'sat_img': sat_img, 'map_img': map_img}\n\n\n"
] |
[
[
"numpy.nanmax",
"numpy.ascontiguousarray",
"numpy.nanmin",
"torch.from_numpy",
"numpy.nan_to_num",
"numpy.int64",
"numpy.iinfo",
"numpy.transpose",
"numpy.random.uniform",
"numpy.empty"
]
] |
TDHolmes/Harma
|
[
"6ebdc2f3d8c2f9df5319495bb0201b94b86c02f4"
] |
[
"Pensel/scripts/save_sensor_data.py"
] |
[
"#! /usr/bin/env python3\nimport time\nimport struct\nimport matplotlib.pyplot as plt\n\nimport pensel_utils as pu\n\n\nclass LSM303DLHC_Parser(object):\n SAMPLES_PER_SECOND = 100 # conservative\n\n def __init__(self, port, baudrate, verbose=0):\n self.verbose = verbose\n self.port = port\n self.baudrate = baudrate\n\n def post_plot(self, num_samples=100, save_mag=True, save_accel=True):\n \"\"\"\n \"\"\"\n # get the packets\n accel_packets = []\n mag_packets = []\n accel_done = False if save_accel else True\n mag_done = False if save_mag else True\n\n end_time = (num_samples / self.SAMPLES_PER_SECOND) * 1.2 + time.time()\n\n with pu.Pensel(self.port, None, self.verbose) as pi:\n\n # turn on accel & mag streaming\n pi.log(\"Turning on input streaming...\")\n # retval, response = pi.send_report(0x20, payload=[0xc])\n pi.log(\"Gathering packets...\")\n try:\n while time.time() < end_time:\n packet = pi.get_packet()\n if packet:\n report, retval, payload = packet\n if report == 0x83 and retval == 0 and save_accel: # accel\n packed_data = struct.pack(\"B\" * len(payload), *payload)\n pkt = pi.parse_accel_packet(packed_data)\n accel_packets.append(pkt)\n if self.verbose:\n pi.log(\"Got Accel packet# {}\".format(pkt.frame_num))\n\n elif report == 0x84 and retval == 0 and save_mag: # mag\n packed_data = struct.pack(\"B\" * len(payload), *payload)\n pkt = pi.parse_mag_packet(packed_data)\n mag_packets.append(pkt)\n if self.verbose:\n pi.log(\"Got Mag packet# {}\".format(pkt.frame_num))\n\n if len(accel_packets) >= num_samples:\n accel_done = True\n if len(mag_packets) >= num_samples:\n mag_done = True\n\n # check if we're done!\n if accel_done and mag_done:\n pi.log(\"Done collecting data!\")\n break\n except KeyboardInterrupt:\n print(\"Keyboard interrupt! Swallowing...\")\n\n if accel_done is False or mag_done is False:\n print(\"WARNING: Timed out before getting enough packets.\")\n\n # Markers: S, 8, >, <, ^, v, o, X, P, d\n fig, ax = plt.subplots()\n\n if save_accel:\n with open(\"accel.csv\", \"w\") as f:\n for pkt in accel_packets:\n f.write(\"{},{},{}\\n\".format(pkt.x, pkt.y, pkt.z))\n\n if save_mag:\n with open(\"mag.csv\", \"w\") as f:\n for pkt in mag_packets:\n f.write(\"{},{},{}\\n\".format(pkt.x, pkt.y, pkt.z))\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Plot sensor data from the Pensel.')\n # parser.add_argument('file', type=str,\n # help='Filename to playback recorded data.')\n parser.add_argument('--mag', action=\"store_true\",\n help='Determine whether or not to plot mag.')\n parser.add_argument('--accel', action=\"store_true\",\n help='Determine whether or not to plot accel.')\n\n parser.add_argument('--verbose', action=\"store_true\",\n help='Verbose output toggle.')\n parser.add_argument('--samples', type=int, default=100,\n help='number of samples to aquire before plotting')\n parser.add_argument('--baudrate', type=int, default=None,\n help='baudrate of coms')\n\n args = parser.parse_args()\n\n if not args.accel and not args.mag:\n print(\"Error: Must specify at least one plot option\")\n raise SystemExit(-1)\n\n lsm = LSM303DLHC_Parser(\"/dev/tty.SLAB_USBtoUART\", args.baudrate, verbose=args.verbose)\n lsm.post_plot(save_mag=args.mag, save_accel=args.accel, num_samples=args.samples)\n"
] |
[
[
"matplotlib.pyplot.subplots"
]
] |
jmarrietar/tensorflow-recorder
|
[
"f03063c763936a4911eb52e62a0c796f9173204d"
] |
[
"tfrecorder/accessor.py"
] |
[
"# Lint as: python3\n\n# Copyright 2020 Google LLC.\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\"\"\"Creates a pandas DataFrame accessor for TFRecorder.\n\naccessor.py contains TFRecorderAccessor which provides a pandas DataFrame\naccessor. This accessor allows us to inject the to_tfr() function into\npandas DataFrames.\n\"\"\"\n\nfrom typing import Any, Dict, Optional, Union\nimport pandas as pd\nfrom IPython.core import display\n\nfrom tfrecorder import client\nfrom tfrecorder import constants\n\n\n@pd.api.extensions.register_dataframe_accessor('tensorflow')\nclass TFRecorderAccessor:\n \"\"\"DataFrame Accessor class for TFRecorder.\"\"\"\n\n def __init__(self, pandas_obj):\n self._df = pandas_obj\n\n # pylint: disable=too-many-arguments\n def to_tfr(\n self,\n output_dir: str,\n runner: str = 'DirectRunner',\n project: Optional[str] = None,\n region: Optional[str] = None,\n dataflow_options: Union[Dict[str, Any], None] = None,\n job_label: str = 'to-tfr',\n compression: Optional[str] = 'gzip',\n num_shards: int = 0) -> Dict[str, Any]:\n \"\"\"TFRecorder Pandas Accessor.\n\n TFRecorder provides an easy interface to create image-based tensorflow\n records from a dataframe containing GCS locations of the images and labels.\n\n Usage:\n import tfrecorder\n\n df.tfrecorder.to_tfr(\n output_dir='gcs://foo/bar/train',\n runner='DirectRunner',\n compression='gzip',\n num_shards=10)\n\n Args:\n output_dir: Local directory or GCS Location to save TFRecords to.\n runner: Beam runner. Can be DirectRunner or DataFlowRunner.\n project: GCP project name (Required if DataFlowRunner).\n region: GCP region name (Required if DataFlowRunner).\n dataflow_options: Optional dictionary containing DataFlow options.\n job_label: User supplied description for the beam job name.\n compression: Can be 'gzip' or None for no compression.\n num_shards: Number of shards to divide the TFRecords into. Default is\n 0 = no sharding.\n Returns:\n job_results: A dictionary of job results.\n \"\"\"\n display.display(\n display.HTML(\n '<b>Logging output to /tmp/{} </b>'.format(constants.LOGFILE)))\n\n r = client.create_tfrecords(\n self._df,\n output_dir=output_dir,\n runner=runner,\n project=project,\n region=region,\n dataflow_options=dataflow_options,\n job_label=job_label,\n compression=compression,\n num_shards=num_shards)\n return r\n"
] |
[
[
"pandas.api.extensions.register_dataframe_accessor"
]
] |
zqcchris/feudal_networks
|
[
"02935592d7bceb77b49bd6deef836c67a23e408b"
] |
[
"feudal_networks/envs/vision_maze.py"
] |
[
"\nimport gym\nfrom gym import spaces\nimport numpy as np\n\nclass VisionMazeEnv(gym.Env):\n def __init__(self, room_length=3, num_rooms_per_side=2):\n assert room_length % 2 == 1, \"room_length must be odd\"\n assert room_length >= 3, \"room_length must be greater than 3\"\n assert num_rooms_per_side >= 1, \"must have at least 1 room\"\n\n self.room_length = room_length\n self.num_rooms_per_side = num_rooms_per_side\n # 0 = up, 1 = right, 2 = down, 3 = left\n self.action_space = spaces.Discrete(4)\n self.max_pos = room_length * num_rooms_per_side - 1\n obs_space = (self.max_pos + 1, self.max_pos + 1, 1)\n self.observation_space = spaces.Box(low=0, high=1, shape=obs_space)\n self.goal_reward = 1\n self.goal_state = [self.max_pos, self.max_pos]\n self._obs = np.zeros(obs_space)\n self._reset()\n\n def _get_obs(self):\n self._obs.fill(0)\n self._obs[self.state[0], self.state[1], :] = 1\n return self._obs\n\n def _reset(self):\n # start in random state in the maze\n x = np.random.randint(self.max_pos)\n y = np.random.randint(self.max_pos)\n self.state = np.array([x, y])\n return self._get_obs()\n\n def _step(self, a):\n assert self.action_space.contains(a)\n x, y = self.state\n\n # up\n if a == 0:\n y = self._step_up(x, y)\n # right\n elif a == 1:\n x = self._step_right(x, y)\n # down\n elif a == 2:\n y = self._step_down(x, y)\n # left\n else:\n x = self._step_left(x, y)\n\n r, done = 0, False\n if x == self.goal_state[0] and y == self.goal_state[1]:\n r, done = self.goal_reward, True\n \n self.state = np.array([x, y])\n return self._get_obs(), r, done, {}\n\n def _step_up(self, x, y):\n ny = y + 1\n\n # convert to single room format\n local_ny = ny % self.room_length\n\n # this condition True indicates passing through wall\n if local_ny == 0:\n\n # this is only allowed if passing through doorway\n if not (x % self.room_length == self.room_length // 2):\n ny = y\n\n ny = min(ny, self.max_pos)\n return ny\n\n def _step_right(self, x, y):\n nx = x + 1\n\n # convert to single room format\n local_nx = nx % self.room_length\n\n # this condition True indicates passing through wall\n if local_nx == 0:\n\n # this is only allowed if passing through doorway\n if not (y % self.room_length == self.room_length // 2):\n nx = x\n\n nx = min(nx, self.max_pos)\n return nx\n\n def _step_down(self, x, y): \n ny = y - 1\n\n # convert to single room format\n local_ny = ny % self.room_length\n\n # this condition True indicates passing through wall\n if local_ny == self.room_length - 1:\n\n # this is only allowed if passing through doorway\n if not (x % self.room_length == self.room_length // 2):\n ny = y\n\n ny = max(0, ny)\n return ny\n\n def _step_left(self, x, y):\n nx = x - 1\n\n # convert to single room format\n local_nx = nx % self.room_length\n\n # this condition True indicates passing through wall\n if local_nx == self.room_length - 1:\n\n # this is only allowed if passing through doorway\n if not (y % self.room_length == self.room_length // 2):\n nx = x\n\n nx = max(0, nx)\n return nx\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
WilmerLab/mofun
|
[
"ec95f2c4455a37ff73d0f595b56f4a246924c2dd"
] |
[
"perf/uio-66-67-perf/perf-plot.py"
] |
[
"\nimport click\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\nimport pandas as pd\n\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n\nfsl = fs = 9\n\n@click.command()\n@click.argument('csv-path', type=click.File())\n@click.option('--outputpath', '-o', type=click.Path(), default=\"perf-plot.png\")\ndef perfplot(csv_path, outputpath=\"perf-plot.png\"):\n fig = plt.figure(figsize=(3.3, 3.3))\n\n data = pd.read_csv(csv_path)\n find = data[data['operation'] == 'find']\n replace = data[data['operation'] == 'replace']\n print(data)\n\n ax = fig.subplots(ncols=1)\n ax.set_xticks([0, 50000, 100000, 150000, 200000, 250000])\n ax.set_xticklabels([\"0\", \"50K\", \"100K\", \"150K\", \"200K\", \"250K\"])\n\n ax.set_ylim((-10, 400))\n ax.set_xlim((-15000, 250000))\n\n ax.grid(which='major', axis='x', linestyle='-', color='0.85', zorder=10)\n ax.grid(which='major', axis='y', linestyle='-', color='0.85', zorder=10)\n\n ax.set_ylabel(\"Time (s)\")\n ax.set_xlabel(\"# Atoms\")\n\n ax.scatter(pd.to_numeric(find['num_atoms']), find['process_time_seconds'], label=\"Find\", zorder=50)\n ax.scatter(pd.to_numeric(replace['num_atoms']), replace['process_time_seconds'], label=\"Find + Replace\", zorder=50)\n\n for row in replace.itertuples():\n print(row)\n ax.annotate(row.repl, (row.num_atoms, row.process_time_seconds), xytext=(0,3), textcoords='offset points', horizontalalignment=\"center\", verticalalignment='bottom', fontsize=7.5, c=\"black\")\n\n ax.legend()\n\n fig.savefig(outputpath, dpi=300, bbox_inches='tight')#, transparent=True)\n plt.close(fig)\n\n\nif __name__ == '__main__':\n perfplot()\n"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.close",
"pandas.to_numeric",
"matplotlib.rc",
"matplotlib.pyplot.figure"
]
] |
aczyzewski/data_visualization_with_multidimensional_scaling
|
[
"3a607833da1c207b40899d6c0fe6f9b9d3180ca2"
] |
[
"lab1_lin_combination/aczyzewski_lab_1_homework.py"
] |
[
"#!/usr/bin/env python\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # Without this projection='3d' is not recognized\n\n\ndef draw_contour_2d(points):\n \"\"\"Draws contour of the 2D figure based on the order of the points.\n\n :param points: list of numpy arrays describing nodes of the figure.\n \"\"\"\n xs, ys = zip(points[-1], *points)\n plt.plot(xs, ys, color=\"blue\")\n\n\ndef draw_contour_3d(points, sides):\n \"\"\"Draws contour of the 3D figure based on the description of its sides.\n\n :param points: list of numpy arrays describing nodes of the figure.\n :param sides: list containing description of the figure's sides. Each side is described by a list of indexes of elements in points.\n \"\"\"\n for side in sides:\n xs, ys, zs = [], [], []\n for s in side:\n xs.append(points[s][0])\n ys.append(points[s][1])\n zs.append(points[s][2])\n # Adding connection to the first node\n a = points[side[0]]\n xs.append(a[0])\n ys.append(a[1])\n zs.append(a[2])\n plt.plot(xs, ys, zs, color=\"blue\")\n\ndef convex_comb_general(points, limit=1.0, step_arange=0.1, tabs=\"\"):\n \"\"\"Generates all linear convex combinations of points with the specified precision.\n\n :param points: list of numpy arrays representing nodes of the figure.\n :param limit: value to be distributed among remaining unassigned linear coefficients.\n :param step_arange: step in arange.\n :param tabs: indent for debug printing.\n :return: list of points, each represented as np.array.\n \"\"\"\n\n # TODO: Zadanie 4.1: Implementacja za pomocą pętli obliczenia wypukłych kombinacji liniowych dla wierzchołków trójkąta.\n coefficients = np.arange(0, 1 + step_arange, step_arange)\n output = []\n for combination in itertools.product(coefficients, repeat=len(points) - 1):\n if np.sum(combination) <= limit:\n combination = list(combination) + [limit - np.sum(combination)]\n output.append(np.sum(np.array(combination).reshape(-1, 1) * points, axis=0))\n \n return output\n\ndef convex_comb_triangle_loop(points):\n \"\"\"Generates all linear convex combinations of points for a triangle using loops.\n\n :param points: list of numpy arrays representing nodes of the figure.\n :return: list of points, each represented as np.array.\n \"\"\"\n\n assert len(points) == 3\n\n # TODO: Zadanie 4.1: Implementacja za pomocą pętli obliczenia wypukłych kombinacji liniowych dla wierzchołków trójkąta.\n coefficients = np.linspace(0, 1, 10)\n output = []\n for combination in itertools.product(coefficients, repeat=len(points) - 1):\n if np.sum(combination) <= 1:\n combination = list(combination) + [1 - np.sum(combination)]\n output.append(np.sum(np.array(combination).reshape(-1, 1) * points, axis=0))\n \n return output \n\ndef draw_convex_combination_2d(points, cc_points):\n # TODO: Zadanie 4.1: Rysowanie wykresu dla wygenerowanej listy punktów (cc_points).\n \n # Draw points (as a line)\n cc_points = np.array(cc_points)\n x, y = cc_points[:, 0], cc_points[:, 1]\n plt.plot(x, y, 'ro')\n plt.margins(0.05)\n\n # Drawing contour of the figure (with plt.plot).\n draw_contour_2d(points)\n\n\ndef draw_convex_combination_3d(points, cc_points, sides=None, color_z=True):\n fig = plt.figure()\n # To create a 3D plot a sublot with projection='3d' must be created.\n # For this to work required is the import of Axes3D: \"from mpl_toolkits.mplot3d import Axes3D\"\n ax = fig.add_subplot(111, projection='3d')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n # TODO: Zadanie 4.3: Zaimplementuj rysowanie wykresu 3D dla cc_points. Możesz dodatkowo zaimplementować kolorowanie względem wartości na osi z.\n\n cc_points = np.array(cc_points)\n x, y, z = cc_points[:, 0], cc_points[:, 1], cc_points[:, 2]\n plt.plot(x, y, z, 'ro')\n\n # Drawing contour of the figure (with plt.plot).\n if sides is not None:\n draw_contour_3d(points, sides)\n\n\ndef draw_vector_addition(vectors, coeffs):\n start = np.array([0.0, 0.0])\n for c, v in zip(coeffs, vectors):\n assert isinstance(v, np.ndarray)\n assert isinstance(c, float)\n # TODO: Zadanie 4.4: Wzorując się na poniższym użyciu funkcji plt.arrow, napisz kod rysujący wektory składowe.\n # TODO: Każdy kolejny wektor powininen być rysowany od punktu, w którym zakończył się poprzedni wektor.\n # TODO: Pamiętaj o przeskalowaniu wektorów przez odpowiedni współczynnik.\n end = c * v\n plt.arrow(*start, *end, head_width=0.1, head_length=0.1, color=\"green\", zorder=4, length_includes_head=True)\n start = end\n\n # Drawing the final vector being a linear combination of the given vectors.\n # The third and the fourth arguments of the plt.arrow function indicate movement (dx, dy), not the ending point.\n resultant_vector = sum([c * v for c, v in zip(coeffs, vectors)])\n plt.arrow(0.0, 0.0, resultant_vector[0], resultant_vector[1], head_width=0.1, head_length=0.1, color=\"magenta\", zorder=4, length_includes_head=True)\n plt.margins(0.05)\n\n\n\ndef draw_triangle_simple_1():\n points = [np.array([-1, 4]),\n np.array([2, 0]),\n np.array([0, 0])]\n cc_points = convex_comb_triangle_loop(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_triangle_simple_2():\n points = [np.array([-2, 3]),\n np.array([4, 4]),\n np.array([3, 2])]\n cc_points = convex_comb_triangle_loop(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_triangle_1():\n points = [np.array([-1, 4]),\n np.array([2, 0]),\n np.array([0, 0])]\n cc_points = convex_comb_general(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_triangle_2():\n points = [np.array([-2, 3]),\n np.array([4, 4]),\n np.array([3, 2])]\n cc_points = convex_comb_general(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_rectangle():\n points = [np.array([0, 0]),\n np.array([0, 1]),\n np.array([1, 1]),\n np.array([1, 0])]\n cc_points = convex_comb_general(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_hexagon():\n points = [np.array([1, -2]),\n np.array([-1, -2]),\n np.array([-2, 0]),\n np.array([-1, 2]),\n np.array([1, 2]),\n np.array([2, 0])]\n cc_points = convex_comb_general(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_not_convex():\n points = [np.array([0, 0]),\n np.array([0, 2]),\n np.array([1, 1]),\n np.array([2, 3]),\n np.array([2, 0])]\n cc_points = convex_comb_general(points)\n draw_convex_combination_2d(points, cc_points)\n plt.show()\n\ndef draw_tetrahedron():\n sides = [[0,1,2], [1,2,3], [0,2,3], [0,1,3]]\n points = [np.array([1.0, 1.0, 1.0]),\n np.array([-1.0, -1.0, 1.0]),\n np.array([-1.0, 1.0, -1.0]),\n np.array([1.0, -1.0, -1.0])]\n cc_points = convex_comb_general(points, step_arange=0.1)\n draw_convex_combination_3d(points, cc_points, sides=sides, color_z=True)\n plt.show()\n\ndef draw_cube():\n sides = [[0,1,2,3], [4,5,6,7], [0,4,5,1], [2,6,7,3]]\n points = [np.array([0.0, 0.0, 0.0]),\n np.array([1.0, 0.0, 0.0]),\n np.array([1.0, 1.0, 0.0]),\n np.array([0.0, 1.0, 0.0]),\n np.array([0.0, 0.0, 1.0]),\n np.array([1.0, 0.0, 1.0]),\n np.array([1.0, 1.0, 1.0]),\n np.array([0.0, 1.0, 1.0])]\n cc_points = convex_comb_general(points, step_arange=0.2)\n draw_convex_combination_3d(points, cc_points, sides=sides, color_z=True)\n plt.show()\n\ndef draw_vector_addition_ex1():\n v = [np.array([-1, 4]),\n np.array([2, 0]),\n np.array([0, 0])]\n coeffs = [0.4, 0.3, 0.3]\n draw_convex_combination_2d(v, convex_comb_general(v))\n draw_vector_addition(v, coeffs)\n plt.show()\n coeffs = [0.2, 0.8, 0.0]\n draw_convex_combination_2d(v, convex_comb_general(v))\n draw_vector_addition(v, coeffs)\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n # for task 4.1\n draw_triangle_simple_1()\n draw_triangle_simple_2()\n\n # for task 4.2\n draw_triangle_1()\n draw_triangle_2()\n draw_rectangle()\n draw_hexagon()\n draw_not_convex()\n\n # for task 4.3\n draw_tetrahedron()\n draw_cube()\n\n # for task 4.4\n draw_vector_addition_ex1()"
] |
[
[
"numpy.linspace",
"numpy.arange",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.arrow",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
shenzebang/FedRep
|
[
"7cd63f1065e2f42079e71294fa4df7b4d20c968a"
] |
[
"models/test.py"
] |
[
"# Modified from: https://github.com/pliang279/LG-FedAvg/blob/master/models/test.py\n# credit goes to: Paul Pu Liang\n\n# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @python: 3.6\n\nimport copy\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, Dataset\nimport time\nfrom models.language_utils import get_word_emb_arr, repackage_hidden, process_x, process_y\n\n\nclass DatasetSplit(Dataset):\n def __init__(self, dataset, idxs):\n self.dataset = dataset\n self.idxs = list(idxs)\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n d = int(self.idxs[item])\n image, label = self.dataset[d]\n return image, label\n\n\nclass DatasetSplit_leaf(Dataset):\n def __init__(self, dataset, idxs):\n self.dataset = dataset\n self.idxs = list(idxs)\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n image, label = self.dataset[item]\n return image, label\n\n\ndef test_img_local(net_g, dataset, args, idx=None, indd=None, user_idx=-1, idxs=None):\n net_g.eval()\n test_loss = 0\n correct = 0\n\n # put LEAF data into proper format\n if 'femnist' in args.dataset:\n leaf = True\n datatest_new = []\n usr = idx\n for j in range(len(dataset[usr]['x'])):\n datatest_new.append(\n (torch.reshape(torch.tensor(dataset[idx]['x'][j]), (1, 28, 28)), torch.tensor(dataset[idx]['y'][j])))\n elif 'sent140' in args.dataset:\n leaf = True\n datatest_new = []\n for j in range(len(dataset[idx]['x'])):\n datatest_new.append((dataset[idx]['x'][j], dataset[idx]['y'][j]))\n else:\n leaf = False\n\n if leaf:\n data_loader = DataLoader(DatasetSplit_leaf(datatest_new, np.ones(len(datatest_new))), batch_size=args.local_bs,\n shuffle=False)\n else:\n data_loader = DataLoader(DatasetSplit(dataset, idxs), batch_size=args.local_bs, shuffle=False)\n if 'sent140' in args.dataset:\n hidden_train = net_g.init_hidden(args.local_bs)\n count = 0\n for idx, (data, target) in enumerate(data_loader):\n if 'sent140' in args.dataset:\n input_data, target_data = process_x(data, indd), process_y(target, indd)\n if args.local_bs != 1 and input_data.shape[0] != args.local_bs:\n break\n\n data, targets = torch.from_numpy(input_data).to(args.device), torch.from_numpy(target_data).to(args.device)\n net_g.zero_grad()\n\n hidden_train = repackage_hidden(hidden_train)\n output, hidden_train = net_g(data, hidden_train)\n\n loss = F.cross_entropy(output.t(), torch.max(targets, 1)[1])\n _, pred_label = torch.max(output.t(), 1)\n correct += (pred_label == torch.max(targets, 1)[1]).sum().item()\n count += args.local_bs\n test_loss += loss.item()\n\n else:\n if args.gpu != -1:\n data, target = data.to(args.device), target.to(args.device)\n log_probs = net_g(data)\n # sum up batch loss\n test_loss += F.cross_entropy(log_probs, target, reduction='sum').item()\n y_pred = log_probs.data.max(1, keepdim=True)[1]\n correct += y_pred.eq(target.data.view_as(y_pred)).long().cpu().sum()\n\n if 'sent140' not in args.dataset:\n count = len(data_loader.dataset)\n test_loss /= count\n accuracy = 100.00 * float(correct) / count\n return accuracy, test_loss\n\n\ndef test_img_local_all(net, args, dataset_test, dict_users_test, w_locals=None, w_glob_keys=None, indd=None,\n dataset_train=None, dict_users_train=None, return_all=False):\n tot = 0\n num_idxxs = args.num_users\n acc_test_local = np.zeros(num_idxxs)\n loss_test_local = np.zeros(num_idxxs)\n for idx in range(num_idxxs):\n net_local = copy.deepcopy(net)\n if w_locals is not None:\n w_local = net_local.state_dict()\n for k in w_locals[idx].keys():\n w_local[k] = w_locals[idx][k]\n net_local.load_state_dict(w_local)\n net_local.eval()\n if 'femnist' in args.dataset or 'sent140' in args.dataset:\n a, b = test_img_local(net_local, dataset_test, args, idx=dict_users_test[idx], indd=indd, user_idx=idx)\n tot += len(dataset_test[dict_users_test[idx]]['x'])\n else:\n a, b = test_img_local(net_local, dataset_test, args, user_idx=idx, idxs=dict_users_test[idx])\n tot += len(dict_users_test[idx])\n if 'femnist' in args.dataset or 'sent140' in args.dataset:\n acc_test_local[idx] = a * len(dataset_test[dict_users_test[idx]]['x'])\n loss_test_local[idx] = b * len(dataset_test[dict_users_test[idx]]['x'])\n else:\n acc_test_local[idx] = a * len(dict_users_test[idx])\n loss_test_local[idx] = b * len(dict_users_test[idx])\n del net_local\n\n if return_all:\n return acc_test_local, loss_test_local\n return sum(acc_test_local) / tot, sum(loss_test_local) / tot\n"
] |
[
[
"torch.max",
"torch.nn.functional.cross_entropy",
"torch.from_numpy",
"torch.tensor",
"numpy.zeros"
]
] |
amitkml/TSAI-DeepVision-EVA4.0-Phase-2
|
[
"f9e232b3eb6ce20f522136523e79208ed85a1f28"
] |
[
"03-FaceRecognition-I/thetensorclan-aws/face/face_blend_common.py"
] |
[
"import math\n\nimport cv2\nimport dlib\nimport numpy as np\n\n\n# Returns 8 points on the boundary of a rectangle\ndef getEightBoundaryPoints(h, w):\n boundaryPts = []\n boundaryPts.append((0, 0))\n boundaryPts.append((w / 2, 0))\n boundaryPts.append((w - 1, 0))\n boundaryPts.append((w - 1, h / 2))\n boundaryPts.append((w - 1, h - 1))\n boundaryPts.append((w / 2, h - 1))\n boundaryPts.append((0, h - 1))\n boundaryPts.append((0, h / 2))\n return np.array(boundaryPts, dtype=np.float)\n\n\n# Constrains points to be inside boundary\ndef constrainPoint(p, w, h):\n p = (min(max(p[0], 0), w - 1), min(max(p[1], 0), h - 1))\n return p\n\n\n# convert Dlib shape detector object to list of tuples\ndef dlibLandmarksToPoints(shape):\n points = []\n for p in shape.parts():\n pt = (p.x, p.y)\n points.append(pt)\n return points\n\n\n# Compute similarity transform given two sets of two points.\n# OpenCV requires 3 pairs of corresponding points.\n# We are faking the third one.\ndef similarityTransform(inPoints, outPoints):\n s60 = math.sin(60 * math.pi / 180)\n c60 = math.cos(60 * math.pi / 180)\n\n inPts = np.copy(inPoints).tolist()\n outPts = np.copy(outPoints).tolist()\n\n # The third point is calculated so that the three points make an equilateral triangle\n xin = c60 * (inPts[0][0] - inPts[1][0]) - s60 * (inPts[0][1] - inPts[1][1]) + inPts[1][0]\n yin = s60 * (inPts[0][0] - inPts[1][0]) + c60 * (inPts[0][1] - inPts[1][1]) + inPts[1][1]\n\n inPts.append([np.int(xin), np.int(yin)])\n\n xout = c60 * (outPts[0][0] - outPts[1][0]) - s60 * (outPts[0][1] - outPts[1][1]) + outPts[1][0]\n yout = s60 * (outPts[0][0] - outPts[1][0]) + c60 * (outPts[0][1] - outPts[1][1]) + outPts[1][1]\n\n outPts.append([np.int(xout), np.int(yout)])\n\n # Now we can use estimateRigidTransform for calculating the similarity transform.\n tform, _ = cv2.estimateAffine2D(np.array([inPts]), np.array([outPts]), False)\n return tform\n\n\n# Normalizes a facial image to a standard size given by outSize.\n# Normalization is done based on Dlib's landmark points passed as pointsIn\n# After normalization, left corner of the left eye is at (0.3 * w, h/3 )\n# and right corner of the right eye is at ( 0.7 * w, h / 3) where w and h\n# are the width and height of outSize.\ndef normalizeImagesAndLandmarks(outSize, imIn, pointsIn):\n h, w = outSize\n\n # Corners of the eye in input image\n eyecornerSrc = [pointsIn[36], pointsIn[45]]\n\n # Corners of the eye in normalized image\n eyecornerDst = [(np.int(0.3 * w), np.int(h / 3)),\n (np.int(0.7 * w), np.int(h / 3))]\n\n # Calculate similarity transform\n tform = similarityTransform(eyecornerSrc, eyecornerDst)\n\n imOut = np.zeros(imIn.shape, dtype=imIn.dtype)\n\n # Apply similarity transform to input image\n imOut = cv2.warpAffine(imIn, tform, (w, h))\n\n # reshape pointsIn from numLandmarks x 2 to numLandmarks x 1 x 2\n points2 = np.reshape(pointsIn, (pointsIn.shape[0], 1, pointsIn.shape[1]))\n\n # Apply similarity transform to landmarks\n pointsOut = cv2.transform(points2, tform)\n\n # reshape pointsOut to numLandmarks x 2\n pointsOut = np.reshape(pointsOut, (pointsIn.shape[0], pointsIn.shape[1]))\n\n return imOut, pointsOut\n\n\n# find the point closest to an array of points\n# pointsArray is a Nx2 and point is 1x2 ndarray\ndef findIndex(pointsArray, point):\n dist = np.linalg.norm(pointsArray - point, axis=1)\n minIndex = np.argmin(dist)\n return minIndex\n\n\n# Check if a point is inside a rectangle\ndef rectContains(rect, point):\n if point[0] < rect[0]:\n return False\n elif point[1] < rect[1]:\n return False\n elif point[0] > rect[2]:\n return False\n elif point[1] > rect[3]:\n return False\n return True\n\n\n# Calculate Delaunay triangles for set of points\n# Returns the vector of indices of 3 points for each triangle\ndef calculateDelaunayTriangles(rect, points):\n # Create an instance of Subdiv2D\n subdiv = cv2.Subdiv2D(rect)\n\n # Insert points into subdiv\n for p in points:\n subdiv.insert((p[0], p[1]))\n\n # Get Delaunay triangulation\n triangleList = subdiv.getTriangleList()\n\n # Find the indices of triangles in the points array\n delaunayTri = []\n\n for t in triangleList:\n # The triangle returned by getTriangleList is\n # a list of 6 coordinates of the 3 points in\n # x1, y1, x2, y2, x3, y3 format.\n # Store triangle as a list of three points\n pt = []\n pt.append((t[0], t[1]))\n pt.append((t[2], t[3]))\n pt.append((t[4], t[5]))\n\n pt1 = (t[0], t[1])\n pt2 = (t[2], t[3])\n pt3 = (t[4], t[5])\n\n if rectContains(rect, pt1) and rectContains(rect, pt2) and rectContains(rect, pt3):\n # Variable to store a triangle as indices from list of points\n ind = []\n # Find the index of each vertex in the points list\n for j in range(0, 3):\n for k in range(0, len(points)):\n if (abs(pt[j][0] - points[k][0]) < 1.0 and abs(pt[j][1] - points[k][1]) < 1.0):\n ind.append(k)\n # Store triangulation as a list of indices\n if len(ind) == 3:\n delaunayTri.append((ind[0], ind[1], ind[2]))\n\n return delaunayTri\n\n\n# Apply affine transform calculated using srcTri and dstTri to src and\n# output an image of size.\ndef applyAffineTransform(src, srcTri, dstTri, size):\n # Given a pair of triangles, find the affine transform.\n warpMat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri))\n\n # Apply the Affine Transform just found to the src image\n dst = cv2.warpAffine(src, warpMat, (size[0], size[1]), None,\n flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)\n\n return dst\n\n\n# Warps and alpha blends triangular regions from img1 and img2 to img\ndef warpTriangle(img1, img2, t1, t2):\n # Find bounding rectangle for each triangle\n r1 = cv2.boundingRect(np.float32([t1]))\n r2 = cv2.boundingRect(np.float32([t2]))\n\n # Offset points by left top corner of the respective rectangles\n t1Rect = []\n t2Rect = []\n t2RectInt = []\n\n for i in range(0, 3):\n t1Rect.append(((t1[i][0] - r1[0]), (t1[i][1] - r1[1])))\n t2Rect.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1])))\n t2RectInt.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1])))\n\n # Get mask by filling triangle\n mask = np.zeros((r2[3], r2[2], 3), dtype=np.float32)\n cv2.fillConvexPoly(mask, np.int32(t2RectInt), (1.0, 1.0, 1.0), 16, 0)\n\n # Apply warpImage to small rectangular patches\n img1Rect = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]]\n\n size = (r2[2], r2[3])\n\n img2Rect = applyAffineTransform(img1Rect, t1Rect, t2Rect, size)\n\n img2Rect = img2Rect * mask\n\n # Copy triangular region of the rectangular patch to the output image\n img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] = img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] * (\n (1.0, 1.0, 1.0) - mask)\n img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] = img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] + img2Rect\n\n\n# detect facial landmarks in image\ndef getLandmarks(faceDetector, landmarkDetector, im, FACE_DOWNSAMPLE_RATIO=1):\n points = []\n imSmall = cv2.resize(im, None,\n fx=1.0 / FACE_DOWNSAMPLE_RATIO,\n fy=1.0 / FACE_DOWNSAMPLE_RATIO,\n interpolation=cv2.INTER_LINEAR)\n\n faceRects = faceDetector(imSmall, 0)\n\n if len(faceRects) > 0:\n maxArea = 0\n maxRect = None\n # TODO: test on images with multiple faces\n for face in faceRects:\n if face.area() > maxArea:\n maxArea = face.area()\n maxRect = [face.left(),\n face.top(),\n face.right(),\n face.bottom()\n ]\n\n rect = dlib.rectangle(*maxRect)\n scaledRect = dlib.rectangle(int(rect.left() * FACE_DOWNSAMPLE_RATIO),\n int(rect.top() * FACE_DOWNSAMPLE_RATIO),\n int(rect.right() * FACE_DOWNSAMPLE_RATIO),\n int(rect.bottom() * FACE_DOWNSAMPLE_RATIO))\n\n landmarks = landmarkDetector(im, scaledRect)\n points = dlibLandmarksToPoints(landmarks)\n return points\n\n\n# Warps an image in a piecewise affine manner.\n# The warp is defined by the movement of landmark points specified by pointsIn\n# to a new location specified by pointsOut. The triangulation beween points is specified\n# by their indices in delaunayTri.\ndef warpImage(imIn, pointsIn, pointsOut, delaunayTri):\n h, w, ch = imIn.shape\n # Output image\n imOut = np.zeros(imIn.shape, dtype=imIn.dtype)\n\n # Warp each input triangle to output triangle.\n # The triangulation is specified by delaunayTri\n for j in range(0, len(delaunayTri)):\n # Input and output points corresponding to jth triangle\n tin = []\n tout = []\n\n for k in range(0, 3):\n # Extract a vertex of input triangle\n pIn = pointsIn[delaunayTri[j][k]]\n # Make sure the vertex is inside the image.\n pIn = constrainPoint(pIn, w, h)\n\n # Extract a vertex of the output triangle\n pOut = pointsOut[delaunayTri[j][k]]\n # Make sure the vertex is inside the image.\n pOut = constrainPoint(pOut, w, h)\n\n # Push the input vertex into input triangle\n tin.append(pIn)\n # Push the output vertex into output triangle\n tout.append(pOut)\n\n # Warp pixels inside input triangle to output triangle.\n warpTriangle(imIn, imOut, tin, tout)\n return imOut\n"
] |
[
[
"numpy.reshape",
"numpy.int32",
"numpy.linalg.norm",
"numpy.int",
"numpy.copy",
"numpy.argmin",
"numpy.float32",
"numpy.array",
"numpy.zeros"
]
] |
voxmenthe/keras-io
|
[
"7165ea10a913de1857cbaa81a90c4443a699c726"
] |
[
"guides/training_with_built_in_methods.py"
] |
[
"\"\"\"\nTitle: Training & evaluation with the built-in methods\nAuthor: [fchollet](https://twitter.com/fchollet)\nDate created: 2019/03/01\nLast modified: 2020/04/13\nDescription: Complete guide to training & evaluation with `fit()` and `evaluate()`.\n\"\"\"\n\n\n\"\"\"\n## Setup\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n\"\"\"\n## Introduction\n\nThis guide covers training, evaluation, and prediction (inference) models\nwhen using built-in APIs for training & validation (such as `model.fit()`,\n`model.evaluate()`, `model.predict()`).\n\nIf you are interested in leveraging `fit()` while specifying your\nown training step function, see the guide\n[\"customizing what happens in `fit()`\"](/guides/customizing_what_happens_in_fit/).\n\nIf you are interested in writing your own training & evaluation loops from\nscratch, see the guide\n[\"writing a training loop from scratch\"](/guides/writing_a_training_loop_from_scratch/).\n\nIn general, whether you are using built-in loops or writing your own, model training &\nevaluation works strictly in the same way across every kind of Keras model --\nSequential models, models built with the Functional API, and models written from\nscratch via model subclassing.\n\nThis guide doesn't cover distributed training. For distributed training, see\nour [guide to multi-gpu & distributed training](https://keras.io/guides/distributed_training/).\n\"\"\"\n\n\"\"\"\n## API overview: a first end-to-end example\n\nWhen passing data to the built-in training loops of a model, you should either use\n**NumPy arrays** (if your data is small and fits in memory) or **`tf.data Dataset`\nobjects**. In the next few paragraphs, we'll use the MNIST dataset as NumPy arrays, in\norder to demonstrate how to use optimizers, losses, and metrics.\n\nLet's consider the following model (here, we build in with the Functional API, but it\ncould be a Sequential model or a subclassed model as well):\n\"\"\"\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)\n\n\"\"\"\nHere's what the typical end-to-end workflow looks like, consisting of:\n\n- Training\n- Validation on a holdout set generated from the original training data\n- Evaluation on the test data\n\nWe'll use MNIST data for this example.\n\"\"\"\n\n(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n\n# Preprocess the data (these are NumPy arrays)\nx_train = x_train.reshape(60000, 784).astype(\"float32\") / 255\nx_test = x_test.reshape(10000, 784).astype(\"float32\") / 255\n\ny_train = y_train.astype(\"float32\")\ny_test = y_test.astype(\"float32\")\n\n# Reserve 10,000 samples for validation\nx_val = x_train[-10000:]\ny_val = y_train[-10000:]\nx_train = x_train[:-10000]\ny_train = y_train[:-10000]\n\n\"\"\"\nWe specify the training configuration (optimizer, loss, metrics):\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(), # Optimizer\n # Loss function to minimize\n loss=keras.losses.SparseCategoricalCrossentropy(),\n # List of metrics to monitor\n metrics=[keras.metrics.SparseCategoricalAccuracy()],\n)\n\n\"\"\"\nWe call `fit()`, which will train the model by slicing the data into \"batches\" of size\n\"batch_size\", and repeatedly iterating over the entire dataset for a given number of\n\"epochs\".\n\"\"\"\n\nprint(\"Fit model on training data\")\nhistory = model.fit(\n x_train,\n y_train,\n batch_size=64,\n epochs=2,\n # We pass some validation for\n # monitoring validation loss and metrics\n # at the end of each epoch\n validation_data=(x_val, y_val),\n)\n\n\"\"\"\nThe returned \"history\" object holds a record of the loss values and metric values\nduring training:\n\"\"\"\n\nhistory.history\n\n\"\"\"\nWe evaluate the model on the test data via `evaluate()`:\n\"\"\"\n\n# Evaluate the model on the test data using `evaluate`\nprint(\"Evaluate on test data\")\nresults = model.evaluate(x_test, y_test, batch_size=128)\nprint(\"test loss, test acc:\", results)\n\n# Generate predictions (probabilities -- the output of the last layer)\n# on new data using `predict`\nprint(\"Generate predictions for 3 samples\")\npredictions = model.predict(x_test[:3])\nprint(\"predictions shape:\", predictions.shape)\n\n\"\"\"\nNow, let's review each piece of this workflow in detail.\n\"\"\"\n\n\"\"\"\n## The `compile()` method: specifying a loss, metrics, and an optimizer\n\nTo train a model with `fit()`, you need to specify a loss function, an optimizer, and\noptionally, some metrics to monitor.\n\nYou pass these to the model as arguments to the `compile()` method:\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()],\n)\n\n\"\"\"\nThe `metrics` argument should be a list -- your model can have any number of metrics.\n\nIf your model has multiple outputs, you can specify different losses and metrics for\neach output, and you can modulate the contribution of each output to the total loss of\nthe model. You will find more details about this in the section **\"Passing data to\nmulti-input, multi-output models\"**.\n\nNote that if you're satisfied with the default settings, in many cases the optimizer,\nloss, and metrics can be specified via string identifiers as a shortcut:\n\"\"\"\n\nmodel.compile(\n optimizer=\"rmsprop\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"sparse_categorical_accuracy\"],\n)\n\n\"\"\"\nFor later reuse, let's put our model definition and compile step in functions; we will\ncall them several times across different examples in this guide.\n\"\"\"\n\n\ndef get_uncompiled_model():\n inputs = keras.Input(shape=(784,), name=\"digits\")\n x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n outputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\ndef get_compiled_model():\n model = get_uncompiled_model()\n model.compile(\n optimizer=\"rmsprop\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"sparse_categorical_accuracy\"],\n )\n return model\n\n\n\"\"\"\n### Many built-in optimizers, losses, and metrics are available\n\nIn general, you won't have to create from scratch your own losses, metrics, or\noptimizers, because what you need is likely already part of the Keras API:\n\nOptimizers:\n\n- `SGD()` (with or without momentum)\n- `RMSprop()`\n- `Adam()`\n- etc.\n\nLosses:\n\n- `MeanSquaredError()`\n- `KLDivergence()`\n- `CosineSimilarity()`\n- etc.\n\nMetrics:\n\n- `AUC()`\n- `Precision()`\n- `Recall()`\n- etc.\n\"\"\"\n\n\"\"\"\n### Custom losses\n\nThere are two ways to provide custom losses with Keras. The first example creates a\nfunction that accepts inputs `y_true` and `y_pred`. The following example shows a loss\nfunction that computes the mean squared error between the real data and the\npredictions:\n\"\"\"\n\n\ndef custom_mean_squared_error(y_true, y_pred):\n return tf.math.reduce_mean(tf.square(y_true - y_pred))\n\n\nmodel = get_uncompiled_model()\nmodel.compile(optimizer=keras.optimizers.Adam(), loss=custom_mean_squared_error)\n\n# We need to one-hot encode the labels to use MSE\ny_train_one_hot = tf.one_hot(y_train, depth=10)\nmodel.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)\n\n\"\"\"\nIf you need a loss function that takes in parameters beside `y_true` and `y_pred`, you\ncan subclass the `tf.keras.losses.Loss` class and implement the following two methods:\n\n- `__init__(self)`: accept parameters to pass during the call of your loss function\n- `call(self, y_true, y_pred)`: use the targets (y_true) and the model predictions\n(y_pred) to compute the model's loss\n\nLet's say you want to use mean squared error, but with an added term that\nwill de-incentivize prediction values far from 0.5 (we assume that the categorical\ntargets are one-hot encoded and take values between 0 and 1). This\ncreates an incentive for the model not to be too confident, which may help\nreduce overfitting (we won't know if it works until we try!).\n\nHere's how you would do it:\n\"\"\"\n\n\nclass CustomMSE(keras.losses.Loss):\n def __init__(self, regularization_factor=0.1, name=\"custom_mse\"):\n super().__init__(name=name)\n self.regularization_factor = regularization_factor\n\n def call(self, y_true, y_pred):\n mse = tf.math.reduce_mean(tf.square(y_true - y_pred))\n reg = tf.math.reduce_mean(tf.square(0.5 - y_pred))\n return mse + reg * self.regularization_factor\n\n\nmodel = get_uncompiled_model()\nmodel.compile(optimizer=keras.optimizers.Adam(), loss=CustomMSE())\n\ny_train_one_hot = tf.one_hot(y_train, depth=10)\nmodel.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)\n\n\"\"\"\n### Custom metrics\n\nIf you need a metric that isn't part of the API, you can easily create custom metrics\nby subclassing the `tf.keras.metrics.Metric` class. You will need to implement 4\nmethods:\n\n- `__init__(self)`, in which you will create state variables for your metric.\n- `update_state(self, y_true, y_pred, sample_weight=None)`, which uses the targets\ny_true and the model predictions y_pred to update the state variables.\n- `result(self)`, which uses the state variables to compute the final results.\n- `reset_states(self)`, which reinitializes the state of the metric.\n\nState update and results computation are kept separate (in `update_state()` and\n`result()`, respectively) because in some cases, results computation might be very\nexpensive, and would only be done periodically.\n\nHere's a simple example showing how to implement a `CategoricalTruePositives` metric,\nthat counts how many samples were correctly classified as belonging to a given class:\n\"\"\"\n\n\nclass CategoricalTruePositives(keras.metrics.Metric):\n def __init__(self, name=\"categorical_true_positives\", **kwargs):\n super(CategoricalTruePositives, self).__init__(name=name, **kwargs)\n self.true_positives = self.add_weight(name=\"ctp\", initializer=\"zeros\")\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n y_pred = tf.reshape(tf.argmax(y_pred, axis=1), shape=(-1, 1))\n values = tf.cast(y_true, \"int32\") == tf.cast(y_pred, \"int32\")\n values = tf.cast(values, \"float32\")\n if sample_weight is not None:\n sample_weight = tf.cast(sample_weight, \"float32\")\n values = tf.multiply(values, sample_weight)\n self.true_positives.assign_add(tf.reduce_sum(values))\n\n def result(self):\n return self.true_positives\n\n def reset_states(self):\n # The state of the metric will be reset at the start of each epoch.\n self.true_positives.assign(0.0)\n\n\nmodel = get_uncompiled_model()\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[CategoricalTruePositives()],\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=3)\n\n\"\"\"\n### Handling losses and metrics that don't fit the standard signature\n\nThe overwhelming majority of losses and metrics can be computed from `y_true` and\n`y_pred`, where `y_pred` is an output of your model. But not all of them. For\ninstance, a regularization loss may only require the activation of a layer (there are\nno targets in this case), and this activation may not be a model output.\n\nIn such cases, you can call `self.add_loss(loss_value)` from inside the call method of\na custom layer. Losses added in this way get added to the \"main\" loss during training\n(the one passed to `compile()`). Here's a simple example that adds activity\nregularization (note that activity regularization is built-in in all Keras layers --\nthis layer is just for the sake of providing a concrete example):\n\"\"\"\n\n\nclass ActivityRegularizationLayer(layers.Layer):\n def call(self, inputs):\n self.add_loss(tf.reduce_sum(inputs) * 0.1)\n return inputs # Pass-through layer.\n\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n\n# Insert activity regularization as a layer\nx = ActivityRegularizationLayer()(x)\n\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\n\n# The displayed loss will be much higher than before\n# due to the regularization component.\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)\n\n\"\"\"\nYou can do the same for logging metric values, using `add_metric()`:\n\"\"\"\n\n\nclass MetricLoggingLayer(layers.Layer):\n def call(self, inputs):\n # The `aggregation` argument defines\n # how to aggregate the per-batch values\n # over each epoch:\n # in this case we simply average them.\n self.add_metric(\n keras.backend.std(inputs), name=\"std_of_activation\", aggregation=\"mean\"\n )\n return inputs # Pass-through layer.\n\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n\n# Insert std logging as a layer.\nx = MetricLoggingLayer()(x)\n\nx = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\noutputs = layers.Dense(10, name=\"predictions\")(x)\n\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)\n\n\"\"\"\nIn the [Functional API](/guides/functional_api/),\nyou can also call `model.add_loss(loss_tensor)`,\nor `model.add_metric(metric_tensor, name, aggregation)`.\n\nHere's a simple example:\n\"\"\"\n\ninputs = keras.Input(shape=(784,), name=\"digits\")\nx1 = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\nx2 = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x1)\noutputs = layers.Dense(10, name=\"predictions\")(x2)\nmodel = keras.Model(inputs=inputs, outputs=outputs)\n\nmodel.add_loss(tf.reduce_sum(x1) * 0.1)\n\nmodel.add_metric(keras.backend.std(x1), name=\"std_of_activation\", aggregation=\"mean\")\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n)\nmodel.fit(x_train, y_train, batch_size=64, epochs=1)\n\n\"\"\"\nNote that when you pass losses via `add_loss()`, it becomes possible to call\n`compile()` without a loss function, since the model already has a loss to minimize.\n\nConsider the following `LogisticEndpoint` layer: it takes as inputs\ntargets & logits, and it tracks a crossentropy loss via `add_loss()`. It also\ntracks classification accuracy via `add_metric()`.\n\"\"\"\n\n\nclass LogisticEndpoint(keras.layers.Layer):\n def __init__(self, name=None):\n super(LogisticEndpoint, self).__init__(name=name)\n self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)\n self.accuracy_fn = keras.metrics.BinaryAccuracy()\n\n def call(self, targets, logits, sample_weights=None):\n # Compute the training-time loss value and add it\n # to the layer using `self.add_loss()`.\n loss = self.loss_fn(targets, logits, sample_weights)\n self.add_loss(loss)\n\n # Log accuracy as a metric and add it\n # to the layer using `self.add_metric()`.\n acc = self.accuracy_fn(targets, logits, sample_weights)\n self.add_metric(acc, name=\"accuracy\")\n\n # Return the inference-time prediction tensor (for `.predict()`).\n return tf.nn.softmax(logits)\n\n\n\"\"\"\nYou can use it in a model with two inputs (input data & targets), compiled without a\n`loss` argument, like this:\n\"\"\"\n\nimport numpy as np\n\ninputs = keras.Input(shape=(3,), name=\"inputs\")\ntargets = keras.Input(shape=(10,), name=\"targets\")\nlogits = keras.layers.Dense(10)(inputs)\npredictions = LogisticEndpoint(name=\"predictions\")(logits, targets)\n\nmodel = keras.Model(inputs=[inputs, targets], outputs=predictions)\nmodel.compile(optimizer=\"adam\") # No loss argument!\n\ndata = {\n \"inputs\": np.random.random((3, 3)),\n \"targets\": np.random.random((3, 10)),\n}\nmodel.fit(data)\n\n\"\"\"\nFor more information about training multi-input models, see the section **Passing data\nto multi-input, multi-output models**.\n\"\"\"\n\n\"\"\"\n### Automatically setting apart a validation holdout set\n\nIn the first end-to-end example you saw, we used the `validation_data` argument to pass\na tuple of NumPy arrays `(x_val, y_val)` to the model for evaluating a validation loss\nand validation metrics at the end of each epoch.\n\nHere's another option: the argument `validation_split` allows you to automatically\nreserve part of your training data for validation. The argument value represents the\nfraction of the data to be reserved for validation, so it should be set to a number\nhigher than 0 and lower than 1. For instance, `validation_split=0.2` means \"use 20% of\nthe data for validation\", and `validation_split=0.6` means \"use 60% of the data for\nvalidation\".\n\nThe way the validation is computed is by taking the last x% samples of the arrays\nreceived by the fit call, before any shuffling.\n\nNote that you can only use `validation_split` when training with NumPy data.\n\"\"\"\n\nmodel = get_compiled_model()\nmodel.fit(x_train, y_train, batch_size=64, validation_split=0.2, epochs=1)\n\n\"\"\"\n## Training & evaluation from tf.data Datasets\n\nIn the past few paragraphs, you've seen how to handle losses, metrics, and optimizers,\nand you've seen how to use the `validation_data` and `validation_split` arguments in\nfit, when your data is passed as NumPy arrays.\n\nLet's now take a look at the case where your data comes in the form of a\n`tf.data.Dataset` object.\n\nThe `tf.data` API is a set of utilities in TensorFlow 2.0 for loading and preprocessing\ndata in a way that's fast and scalable.\n\nFor a complete guide about creating `Datasets`, see the\n[tf.data documentation](https://www.tensorflow.org/guide/data).\n\nYou can pass a `Dataset` instance directly to the methods `fit()`, `evaluate()`, and\n`predict()`:\n\"\"\"\n\nmodel = get_compiled_model()\n\n# First, let's create a training Dataset instance.\n# For the sake of our example, we'll use the same MNIST data as before.\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n# Shuffle and slice the dataset.\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Now we get a test dataset.\ntest_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\ntest_dataset = test_dataset.batch(64)\n\n# Since the dataset already takes care of batching,\n# we don't pass a `batch_size` argument.\nmodel.fit(train_dataset, epochs=3)\n\n# You can also evaluate or predict on a dataset.\nprint(\"Evaluate\")\nresult = model.evaluate(test_dataset)\ndict(zip(model.metrics_names, result))\n\n\"\"\"\nNote that the Dataset is reset at the end of each epoch, so it can be reused of the\nnext epoch.\n\nIf you want to run training only on a specific number of batches from this Dataset, you\ncan pass the `steps_per_epoch` argument, which specifies how many training steps the\nmodel should run using this Dataset before moving on to the next epoch.\n\nIf you do this, the dataset is not reset at the end of each epoch, instead we just keep\ndrawing the next batches. The dataset will eventually run out of data (unless it is an\ninfinitely-looping dataset).\n\"\"\"\n\nmodel = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Only use the 100 batches per epoch (that's 64 * 100 samples)\nmodel.fit(train_dataset, epochs=3, steps_per_epoch=100)\n\n\"\"\"\n### Using a validation dataset\n\nYou can pass a `Dataset` instance as the `validation_data` argument in `fit()`:\n\"\"\"\n\nmodel = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Prepare the validation dataset\nval_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nval_dataset = val_dataset.batch(64)\n\nmodel.fit(train_dataset, epochs=1, validation_data=val_dataset)\n\n\"\"\"\nAt the end of each epoch, the model will iterate over the validation dataset and\ncompute the validation loss and validation metrics.\n\nIf you want to run validation only on a specific number of batches from this dataset,\nyou can pass the `validation_steps` argument, which specifies how many validation\nsteps the model should run with the validation dataset before interrupting validation\nand moving on to the next epoch:\n\"\"\"\n\nmodel = get_compiled_model()\n\n# Prepare the training dataset\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\n# Prepare the validation dataset\nval_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nval_dataset = val_dataset.batch(64)\n\nmodel.fit(\n train_dataset,\n epochs=1,\n # Only run validation using the first 10 batches of the dataset\n # using the `validation_steps` argument\n validation_data=val_dataset,\n validation_steps=10,\n)\n\n\"\"\"\nNote that the validation dataset will be reset after each use (so that you will always\nbe evaluating on the same samples from epoch to epoch).\n\nThe argument `validation_split` (generating a holdout set from the training data) is\nnot supported when training from `Dataset` objects, since this feature requires the\nability to index the samples of the datasets, which is not possible in general with\nthe `Dataset` API.\n\"\"\"\n\n\"\"\"\n## Other input formats supported\n\nBesides NumPy arrays, eager tensors, and TensorFlow `Datasets`, it's possible to train\na Keras model using Pandas dataframes, or from Python generators that yield batches of\ndata & labels.\n\nIn particular, the `keras.utils.Sequence` class offers a simple interface to build\nPython data generators that are multiprocessing-aware and can be shuffled.\n\nIn general, we recommend that you use:\n\n- NumPy input data if your data is small and fits in memory\n- `Dataset` objects if you have large datasets and you need to do distributed training\n- `Sequence` objects if you have large datasets and you need to do a lot of custom\nPython-side processing that cannot be done in TensorFlow (e.g. if you rely on external libraries\nfor data loading or preprocessing).\n\n\n## Using a `keras.utils.Sequence` object as input\n\n`keras.utils.Sequence` is a utility that you can subclass to obtain a Python generator with\ntwo important properties:\n\n- It works well with multiprocessing.\n- It can be shuffled (e.g. when passing `shuffle=True` in `fit()`).\n\nA `Sequence` must implement two methods:\n\n- `__getitem__`\n- `__len__`\n\nThe method `__getitem__` should return a complete batch.\nIf you want to modify your dataset between epochs, you may implement `on_epoch_end`.\n\nHere's a quick example:\n\n```python\nfrom skimage.io import imread\nfrom skimage.transform import resize\nimport numpy as np\n\n# Here, `filenames` is list of path to the images\n# and `labels` are the associated labels.\n\nclass CIFAR10Sequence(Sequence):\n def __init__(self, filenames, labels, batch_size):\n self.filenames, self.labels = filenames, labels\n self.batch_size = batch_size\n\n def __len__(self):\n return int(np.ceil(len(self.filenames) / float(self.batch_size)))\n\n def __getitem__(self, idx):\n batch_x = self.filenames[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_y = self.labels[idx * self.batch_size:(idx + 1) * self.batch_size]\n return np.array([\n resize(imread(filename), (200, 200))\n for filename in batch_x]), np.array(batch_y)\n\nsequence = CIFAR10Sequence(filenames, labels, batch_size)\nmodel.fit(sequence, epochs=10)\n```\n\n\"\"\"\n\n\"\"\"\n## Using sample weighting and class weighting\n\nWith the default settings the weight of a sample is decided by its frequency\nin the dataset. There are two methods to weight the data, independent of\nsample frequency:\n\n* Class weights\n* Sample weights\n\"\"\"\n\n\"\"\"\n### Class weights\n\nThis is set by passing a dictionary to the `class_weight` argument to\n`Model.fit()`. This dictionary maps class indices to the weight that should\nbe used for samples belonging to this class.\n\nThis can be used to balance classes without resampling, or to train a\nmodel that gives more importance to a particular class.\n\nFor instance, if class \"0\" is half as represented as class \"1\" in your data,\nyou could use `Model.fit(..., class_weight={0: 1., 1: 0.5})`.\n\"\"\"\n\n\"\"\"\nHere's a NumPy example where we use class weights or sample weights to\ngive more importance to the correct classification of class #5 (which\nis the digit \"5\" in the MNIST dataset).\n\"\"\"\n\nimport numpy as np\n\nclass_weight = {\n 0: 1.0,\n 1: 1.0,\n 2: 1.0,\n 3: 1.0,\n 4: 1.0,\n # Set weight \"2\" for class \"5\",\n # making this class 2x more important\n 5: 2.0,\n 6: 1.0,\n 7: 1.0,\n 8: 1.0,\n 9: 1.0,\n}\n\nprint(\"Fit with class weight\")\nmodel = get_compiled_model()\nmodel.fit(x_train, y_train, class_weight=class_weight, batch_size=64, epochs=1)\n\n\"\"\"\n### Sample weights\n\nFor fine grained control, or if you are not building a classifier,\nyou can use \"sample weights\".\n\n- When training from NumPy data: Pass the `sample_weight`\n argument to `Model.fit()`.\n- When training from `tf.data` or any other sort of iterator:\n Yield `(input_batch, label_batch, sample_weight_batch)` tuples.\n\nA \"sample weights\" array is an array of numbers that specify how much weight\neach sample in a batch should have in computing the total loss. It is commonly\nused in imbalanced classification problems (the idea being to give more weight\nto rarely-seen classes).\n\nWhen the weights used are ones and zeros, the array can be used as a *mask* for\nthe loss function (entirely discarding the contribution of certain samples to\nthe total loss).\n\"\"\"\n\nsample_weight = np.ones(shape=(len(y_train),))\nsample_weight[y_train == 5] = 2.0\n\nprint(\"Fit with sample weight\")\nmodel = get_compiled_model()\nmodel.fit(x_train, y_train, sample_weight=sample_weight, batch_size=64, epochs=1)\n\n\"\"\"\nHere's a matching `Dataset` example:\n\"\"\"\n\nsample_weight = np.ones(shape=(len(y_train),))\nsample_weight[y_train == 5] = 2.0\n\n# Create a Dataset that includes sample weights\n# (3rd element in the return tuple).\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train, sample_weight))\n\n# Shuffle and slice the dataset.\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\nmodel = get_compiled_model()\nmodel.fit(train_dataset, epochs=1)\n\n\"\"\"\n## Passing data to multi-input, multi-output models\n\nIn the previous examples, we were considering a model with a single input (a tensor of\nshape `(764,)`) and a single output (a prediction tensor of shape `(10,)`). But what\nabout models that have multiple inputs or outputs?\n\nConsider the following model, which has an image input of shape `(32, 32, 3)` (that's\n`(height, width, channels)`) and a timeseries input of shape `(None, 10)` (that's\n`(timesteps, features)`). Our model will have two outputs computed from the\ncombination of these inputs: a \"score\" (of shape `(1,)`) and a probability\ndistribution over five classes (of shape `(5,)`).\n\"\"\"\n\nimage_input = keras.Input(shape=(32, 32, 3), name=\"img_input\")\ntimeseries_input = keras.Input(shape=(None, 10), name=\"ts_input\")\n\nx1 = layers.Conv2D(3, 3)(image_input)\nx1 = layers.GlobalMaxPooling2D()(x1)\n\nx2 = layers.Conv1D(3, 3)(timeseries_input)\nx2 = layers.GlobalMaxPooling1D()(x2)\n\nx = layers.concatenate([x1, x2])\n\nscore_output = layers.Dense(1, name=\"score_output\")(x)\nclass_output = layers.Dense(5, name=\"class_output\")(x)\n\nmodel = keras.Model(\n inputs=[image_input, timeseries_input], outputs=[score_output, class_output]\n)\n\n\"\"\"\nLet's plot this model, so you can clearly see what we're doing here (note that the\nshapes shown in the plot are batch shapes, rather than per-sample shapes).\n\"\"\"\n\nkeras.utils.plot_model(model, \"multi_input_and_output_model.png\", show_shapes=True)\n\n\"\"\"\nAt compilation time, we can specify different losses to different outputs, by passing\nthe loss functions as a list:\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n)\n\n\"\"\"\nIf we only passed a single loss function to the model, the same loss function would be\napplied to every output (which is not appropriate here).\n\nLikewise for metrics:\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n metrics=[\n [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n [keras.metrics.CategoricalAccuracy()],\n ],\n)\n\n\"\"\"\nSince we gave names to our output layers, we could also specify per-output losses and\nmetrics via a dict:\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\n \"score_output\": keras.losses.MeanSquaredError(),\n \"class_output\": keras.losses.CategoricalCrossentropy(),\n },\n metrics={\n \"score_output\": [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n \"class_output\": [keras.metrics.CategoricalAccuracy()],\n },\n)\n\n\"\"\"\nWe recommend the use of explicit names and dicts if you have more than 2 outputs.\n\nIt's possible to give different weights to different output-specific losses (for\ninstance, one might wish to privilege the \"score\" loss in our example, by giving to 2x\nthe importance of the class loss), using the `loss_weights` argument:\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\n \"score_output\": keras.losses.MeanSquaredError(),\n \"class_output\": keras.losses.CategoricalCrossentropy(),\n },\n metrics={\n \"score_output\": [\n keras.metrics.MeanAbsolutePercentageError(),\n keras.metrics.MeanAbsoluteError(),\n ],\n \"class_output\": [keras.metrics.CategoricalAccuracy()],\n },\n loss_weights={\"score_output\": 2.0, \"class_output\": 1.0},\n)\n\n\"\"\"\nYou could also chose not to compute a loss for certain outputs, if these outputs meant\nfor prediction but not for training:\n\"\"\"\n\n# List loss version\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[None, keras.losses.CategoricalCrossentropy()],\n)\n\n# Or dict loss version\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss={\"class_output\": keras.losses.CategoricalCrossentropy()},\n)\n\n\"\"\"\nPassing data to a multi-input or multi-output model in fit works in a similar way as\nspecifying a loss function in compile: you can pass **lists of NumPy arrays** (with\n1:1 mapping to the outputs that received a loss function) or **dicts mapping output\nnames to NumPy arrays**.\n\"\"\"\n\nmodel.compile(\n optimizer=keras.optimizers.RMSprop(1e-3),\n loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n)\n\n# Generate dummy NumPy data\nimg_data = np.random.random_sample(size=(100, 32, 32, 3))\nts_data = np.random.random_sample(size=(100, 20, 10))\nscore_targets = np.random.random_sample(size=(100, 1))\nclass_targets = np.random.random_sample(size=(100, 5))\n\n# Fit on lists\nmodel.fit([img_data, ts_data], [score_targets, class_targets], batch_size=32, epochs=1)\n\n# Alternatively, fit on dicts\nmodel.fit(\n {\"img_input\": img_data, \"ts_input\": ts_data},\n {\"score_output\": score_targets, \"class_output\": class_targets},\n batch_size=32,\n epochs=1,\n)\n\n\"\"\"\nHere's the `Dataset` use case: similarly as what we did for NumPy arrays, the `Dataset`\nshould return a tuple of dicts.\n\"\"\"\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices(\n (\n {\"img_input\": img_data, \"ts_input\": ts_data},\n {\"score_output\": score_targets, \"class_output\": class_targets},\n )\n)\ntrain_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n\nmodel.fit(train_dataset, epochs=1)\n\n\"\"\"\n## Using callbacks\n\nCallbacks in Keras are objects that are called at different points during training (at\nthe start of an epoch, at the end of a batch, at the end of an epoch, etc.) and which\ncan be used to implement behaviors such as:\n\n- Doing validation at different points during training (beyond the built-in per-epoch\nvalidation)\n- Checkpointing the model at regular intervals or when it exceeds a certain accuracy\nthreshold\n- Changing the learning rate of the model when training seems to be plateauing\n- Doing fine-tuning of the top layers when training seems to be plateauing\n- Sending email or instant message notifications when training ends or where a certain\nperformance threshold is exceeded\n- Etc.\n\nCallbacks can be passed as a list to your call to `fit()`:\n\"\"\"\n\nmodel = get_compiled_model()\n\ncallbacks = [\n keras.callbacks.EarlyStopping(\n # Stop training when `val_loss` is no longer improving\n monitor=\"val_loss\",\n # \"no longer improving\" being defined as \"no better than 1e-2 less\"\n min_delta=1e-2,\n # \"no longer improving\" being further defined as \"for at least 2 epochs\"\n patience=2,\n verbose=1,\n )\n]\nmodel.fit(\n x_train,\n y_train,\n epochs=20,\n batch_size=64,\n callbacks=callbacks,\n validation_split=0.2,\n)\n\n\"\"\"\n### Many built-in callbacks are available\n\n- `ModelCheckpoint`: Periodically save the model.\n- `EarlyStopping`: Stop training when training is no longer improving the validation\nmetrics.\n- `TensorBoard`: periodically write model logs that can be visualized in\n[TensorBoard](https://www.tensorflow.org/tensorboard) (more details in the section\n\"Visualization\").\n- `CSVLogger`: streams loss and metrics data to a CSV file.\n- etc.\n\nSee the [callbacks documentation](/api/callbacks/) for the complete list.\n\n### Writing your own callback\n\nYou can create a custom callback by extending the base class\n`keras.callbacks.Callback`. A callback has access to its associated model through the\nclass property `self.model`.\n\nMake sure to read the\n[complete guide to writing custom callbacks](/guides/writing_your_own_callbacks/).\n\nHere's a simple example saving a list of per-batch loss values during training:\n\"\"\"\n\n\nclass LossHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs):\n self.per_batch_losses = []\n\n def on_batch_end(self, batch, logs):\n self.per_batch_losses.append(logs.get(\"loss\"))\n\n\n\"\"\"\n## Checkpointing models\n\nWhen you're training model on relatively large datasets, it's crucial to save\ncheckpoints of your model at frequent intervals.\n\nThe easiest way to achieve this is with the `ModelCheckpoint` callback:\n\"\"\"\n\nmodel = get_compiled_model()\n\ncallbacks = [\n keras.callbacks.ModelCheckpoint(\n # Path where to save the model\n # The two parameters below mean that we will overwrite\n # the current checkpoint if and only if\n # the `val_loss` score has improved.\n # The saved model name will include the current epoch.\n filepath=\"mymodel_{epoch}\",\n save_best_only=True, # Only save a model if `val_loss` has improved.\n monitor=\"val_loss\",\n verbose=1,\n )\n]\nmodel.fit(\n x_train, y_train, epochs=2, batch_size=64, callbacks=callbacks, validation_split=0.2\n)\n\n\"\"\"\nThe `ModelCheckpoint` callback can be used to implement fault-tolerance:\nthe ability to restart training from the last saved state of the model in case training\ngets randomly interrupted. Here's a basic example:\n\"\"\"\n\nimport os\n\n# Prepare a directory to store all the checkpoints.\ncheckpoint_dir = \"./ckpt\"\nif not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n\ndef make_or_restore_model():\n # Either restore the latest model, or create a fresh one\n # if there is no checkpoint available.\n checkpoints = [checkpoint_dir + \"/\" + name for name in os.listdir(checkpoint_dir)]\n if checkpoints:\n latest_checkpoint = max(checkpoints, key=os.path.getctime)\n print(\"Restoring from\", latest_checkpoint)\n return keras.models.load_model(latest_checkpoint)\n print(\"Creating a new model\")\n return get_compiled_model()\n\n\nmodel = make_or_restore_model()\ncallbacks = [\n # This callback saves a SavedModel every 100 batches.\n # We include the training loss in the saved model name.\n keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_dir + \"/ckpt-loss={loss:.2f}\", save_freq=100\n )\n]\nmodel.fit(x_train, y_train, epochs=1, callbacks=callbacks)\n\n\"\"\"\nYou call also write your own callback for saving and restoring models.\n\nFor a complete guide on serialization and saving, see the\n[guide to saving and serializing Models](/guides/serialization_and_saving/).\n\"\"\"\n\n\"\"\"\n## Using learning rate schedules\n\nA common pattern when training deep learning models is to gradually reduce the learning\nas training progresses. This is generally known as \"learning rate decay\".\n\nThe learning decay schedule could be static (fixed in advance, as a function of the\ncurrent epoch or the current batch index), or dynamic (responding to the current\nbehavior of the model, in particular the validation loss).\n\n### Passing a schedule to an optimizer\n\nYou can easily use a static learning rate decay schedule by passing a schedule object\nas the `learning_rate` argument in your optimizer:\n\"\"\"\n\ninitial_learning_rate = 0.1\nlr_schedule = keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True\n)\n\noptimizer = keras.optimizers.RMSprop(learning_rate=lr_schedule)\n\n\"\"\"\nSeveral built-in schedules are available: `ExponentialDecay`, `PiecewiseConstantDecay`,\n`PolynomialDecay`, and `InverseTimeDecay`.\n\n### Using callbacks to implement a dynamic learning rate schedule\n\nA dynamic learning rate schedule (for instance, decreasing the learning rate when the\nvalidation loss is no longer improving) cannot be achieved with these schedule objects\nsince the optimizer does not have access to validation metrics.\n\nHowever, callbacks do have access to all metrics, including validation metrics! You can\nthus achieve this pattern by using a callback that modifies the current learning rate\non the optimizer. In fact, this is even built-in as the `ReduceLROnPlateau` callback.\n\"\"\"\n\n\"\"\"\n## Visualizing loss and metrics during training\n\nThe best way to keep an eye on your model during training is to use\n[TensorBoard](https://www.tensorflow.org/tensorboard), a browser-based application\nthat you can run locally that provides you with:\n\n- Live plots of the loss and metrics for training and evaluation\n- (optionally) Visualizations of the histograms of your layer activations\n- (optionally) 3D visualizations of the embedding spaces learned by your `Embedding`\nlayers\n\nIf you have installed TensorFlow with pip, you should be able to launch TensorBoard\nfrom the command line:\n\n```\ntensorboard --logdir=/full_path_to_your_logs\n```\n\"\"\"\n\n\"\"\"\n### Using the TensorBoard callback\n\nThe easiest way to use TensorBoard with a Keras model and the fit method is the\n`TensorBoard` callback.\n\nIn the simplest case, just specify where you want the callback to write logs, and\nyou're good to go:\n\"\"\"\n\nkeras.callbacks.TensorBoard(\n log_dir=\"/full_path_to_your_logs\",\n histogram_freq=0, # How often to log histogram visualizations\n embeddings_freq=0, # How often to log embedding visualizations\n update_freq=\"epoch\",\n) # How often to write logs (default: once per epoch)\n\n\"\"\"\nFor more information, see the\n[documentation for the `TensorBoard` callback](/api/callbacks/tensorboard/).\n\"\"\"\n"
] |
[
[
"tensorflow.keras.metrics.BinaryAccuracy",
"tensorflow.keras.models.load_model",
"tensorflow.keras.losses.CategoricalCrossentropy",
"tensorflow.reduce_sum",
"tensorflow.cast",
"numpy.random.random_sample",
"tensorflow.keras.metrics.CategoricalAccuracy",
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.keras.metrics.MeanAbsolutePercentageError",
"tensorflow.keras.Input",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.losses.BinaryCrossentropy",
"tensorflow.square",
"tensorflow.argmax",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.layers.GlobalMaxPooling1D",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.utils.plot_model",
"tensorflow.keras.Model",
"tensorflow.one_hot",
"tensorflow.nn.softmax",
"numpy.random.random",
"tensorflow.multiply",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.keras.layers.Conv1D",
"tensorflow.keras.optimizers.schedules.ExponentialDecay",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.datasets.mnist.load_data",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.backend.std",
"tensorflow.keras.metrics.MeanAbsoluteError",
"tensorflow.keras.layers.GlobalMaxPooling2D",
"tensorflow.keras.metrics.SparseCategoricalAccuracy"
]
] |
Abhishek-TyRnT/scikit-learn
|
[
"bcd902e591e07ee3a67cecc77fcda5a4d1935631",
"b758c2e84d5082eab5fdfee68490d43223a0ec35"
] |
[
"sklearn/kernel_approximation.py",
"sklearn/neural_network/_multilayer_perceptron.py"
] |
[
"\"\"\"\nThe :mod:`sklearn.kernel_approximation` module implements several\napproximate kernel feature maps based on Fourier transforms and Count Sketches.\n\"\"\"\n\n# Author: Andreas Mueller <amueller@ais.uni-bonn.de>\n# Daniel Lopez-Sanchez (TensorSketch) <lope@usal.es>\n\n# License: BSD 3 clause\n\nimport warnings\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.linalg import svd\n\ntry:\n from scipy.fft import fft, ifft\nexcept ImportError: # scipy < 1.4\n from scipy.fftpack import fft, ifft\n\nfrom .base import BaseEstimator\nfrom .base import TransformerMixin\nfrom .utils import check_random_state\nfrom .utils.extmath import safe_sparse_dot\nfrom .utils.validation import check_is_fitted\nfrom .metrics.pairwise import pairwise_kernels, KERNEL_PARAMS\nfrom .utils.validation import check_non_negative\n\n\nclass PolynomialCountSketch(BaseEstimator, TransformerMixin):\n \"\"\"Polynomial kernel approximation via Tensor Sketch.\n\n Implements Tensor Sketch, which approximates the feature map\n of the polynomial kernel::\n\n K(X, Y) = (gamma * <X, Y> + coef0)^degree\n\n by efficiently computing a Count Sketch of the outer product of a\n vector with itself using Fast Fourier Transforms (FFT). Read more in the\n :ref:`User Guide <polynomial_kernel_approx>`.\n\n .. versionadded:: 0.24\n\n Parameters\n ----------\n gamma : float, default=1.0\n Parameter of the polynomial kernel whose feature map\n will be approximated.\n\n degree : int, default=2\n Degree of the polynomial kernel whose feature map\n will be approximated.\n\n coef0 : int, default=0\n Constant term of the polynomial kernel whose feature map\n will be approximated.\n\n n_components : int, default=100\n Dimensionality of the output feature space. Usually, `n_components`\n should be greater than the number of features in input samples in\n order to achieve good performance. The optimal score / run time\n balance is typically achieved around `n_components` = 10 * `n_features`,\n but this depends on the specific dataset being used.\n\n random_state : int, RandomState instance, default=None\n Determines random number generation for indexHash and bitHash\n initialization. Pass an int for reproducible results across multiple\n function calls. See :term:`Glossary <random_state>`.\n\n Attributes\n ----------\n indexHash_ : ndarray of shape (degree, n_features), dtype=int64\n Array of indexes in range [0, n_components) used to represent\n the 2-wise independent hash functions for Count Sketch computation.\n\n bitHash_ : ndarray of shape (degree, n_features), dtype=float32\n Array with random entries in {+1, -1}, used to represent\n the 2-wise independent hash functions for Count Sketch computation.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.\n Nystroem : Approximate a kernel map using a subset of the training data.\n RBFSampler : Approximate a RBF kernel feature map using random Fourier\n features.\n SkewedChi2Sampler : Approximate feature map for \"skewed chi-squared\" kernel.\n sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.\n\n Examples\n --------\n >>> from sklearn.kernel_approximation import PolynomialCountSketch\n >>> from sklearn.linear_model import SGDClassifier\n >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]\n >>> y = [0, 0, 1, 1]\n >>> ps = PolynomialCountSketch(degree=3, random_state=1)\n >>> X_features = ps.fit_transform(X)\n >>> clf = SGDClassifier(max_iter=10, tol=1e-3)\n >>> clf.fit(X_features, y)\n SGDClassifier(max_iter=10)\n >>> clf.score(X_features, y)\n 1.0\n \"\"\"\n\n def __init__(\n self, *, gamma=1.0, degree=2, coef0=0, n_components=100, random_state=None\n ):\n self.gamma = gamma\n self.degree = degree\n self.coef0 = coef0\n self.n_components = n_components\n self.random_state = random_state\n\n def fit(self, X, y=None):\n \"\"\"Fit the model with X.\n\n Initializes the internal variables. The method needs no information\n about the distribution of data, so we only care about n_features in X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n Returns\n -------\n self : object\n Returns the instance itself.\n \"\"\"\n if not self.degree >= 1:\n raise ValueError(f\"degree={self.degree} should be >=1.\")\n\n X = self._validate_data(X, accept_sparse=\"csc\")\n random_state = check_random_state(self.random_state)\n\n n_features = X.shape[1]\n if self.coef0 != 0:\n n_features += 1\n\n self.indexHash_ = random_state.randint(\n 0, high=self.n_components, size=(self.degree, n_features)\n )\n\n self.bitHash_ = random_state.choice(a=[-1, 1], size=(self.degree, n_features))\n return self\n\n def transform(self, X):\n \"\"\"Generate the feature map approximation for X.\n\n Parameters\n ----------\n X : {array-like}, shape (n_samples, n_features)\n New data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n Returns\n -------\n X_new : array-like, shape (n_samples, n_components)\n Returns the instance itself.\n \"\"\"\n\n check_is_fitted(self)\n X = self._validate_data(X, accept_sparse=\"csc\", reset=False)\n\n X_gamma = np.sqrt(self.gamma) * X\n\n if sp.issparse(X_gamma) and self.coef0 != 0:\n X_gamma = sp.hstack(\n [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))],\n format=\"csc\",\n )\n\n elif not sp.issparse(X_gamma) and self.coef0 != 0:\n X_gamma = np.hstack(\n [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))]\n )\n\n if X_gamma.shape[1] != self.indexHash_.shape[1]:\n raise ValueError(\n \"Number of features of test samples does not\"\n \" match that of training samples.\"\n )\n\n count_sketches = np.zeros((X_gamma.shape[0], self.degree, self.n_components))\n\n if sp.issparse(X_gamma):\n for j in range(X_gamma.shape[1]):\n for d in range(self.degree):\n iHashIndex = self.indexHash_[d, j]\n iHashBit = self.bitHash_[d, j]\n count_sketches[:, d, iHashIndex] += (\n (iHashBit * X_gamma[:, j]).toarray().ravel()\n )\n\n else:\n for j in range(X_gamma.shape[1]):\n for d in range(self.degree):\n iHashIndex = self.indexHash_[d, j]\n iHashBit = self.bitHash_[d, j]\n count_sketches[:, d, iHashIndex] += iHashBit * X_gamma[:, j]\n\n # For each same, compute a count sketch of phi(x) using the polynomial\n # multiplication (via FFT) of p count sketches of x.\n count_sketches_fft = fft(count_sketches, axis=2, overwrite_x=True)\n count_sketches_fft_prod = np.prod(count_sketches_fft, axis=1)\n data_sketch = np.real(ifft(count_sketches_fft_prod, overwrite_x=True))\n\n return data_sketch\n\n\nclass RBFSampler(TransformerMixin, BaseEstimator):\n \"\"\"Approximate a RBF kernel feature map using random Fourier features.\n\n It implements a variant of Random Kitchen Sinks.[1]\n\n Read more in the :ref:`User Guide <rbf_kernel_approx>`.\n\n Parameters\n ----------\n gamma : float, default=1.0\n Parameter of RBF kernel: exp(-gamma * x^2).\n\n n_components : int, default=100\n Number of Monte Carlo samples per original feature.\n Equals the dimensionality of the computed feature space.\n\n random_state : int, RandomState instance or None, default=None\n Pseudo-random number generator to control the generation of the random\n weights and random offset when fitting the training data.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Attributes\n ----------\n random_offset_ : ndarray of shape (n_components,), dtype=float64\n Random offset used to compute the projection in the `n_components`\n dimensions of the feature space.\n\n random_weights_ : ndarray of shape (n_features, n_components),\\\n dtype=float64\n Random projection directions drawn from the Fourier transform\n of the RBF kernel.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.\n Nystroem : Approximate a kernel map using a subset of the training data.\n PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.\n SkewedChi2Sampler : Approximate feature map for\n \"skewed chi-squared\" kernel.\n sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.\n\n Notes\n -----\n See \"Random Features for Large-Scale Kernel Machines\" by A. Rahimi and\n Benjamin Recht.\n\n [1] \"Weighted Sums of Random Kitchen Sinks: Replacing\n minimization with randomization in learning\" by A. Rahimi and\n Benjamin Recht.\n (https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf)\n\n Examples\n --------\n >>> from sklearn.kernel_approximation import RBFSampler\n >>> from sklearn.linear_model import SGDClassifier\n >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]\n >>> y = [0, 0, 1, 1]\n >>> rbf_feature = RBFSampler(gamma=1, random_state=1)\n >>> X_features = rbf_feature.fit_transform(X)\n >>> clf = SGDClassifier(max_iter=5, tol=1e-3)\n >>> clf.fit(X_features, y)\n SGDClassifier(max_iter=5)\n >>> clf.score(X_features, y)\n 1.0\n \"\"\"\n\n def __init__(self, *, gamma=1.0, n_components=100, random_state=None):\n self.gamma = gamma\n self.n_components = n_components\n self.random_state = random_state\n\n def fit(self, X, y=None):\n \"\"\"Fit the model with X.\n\n Samples random projection according to n_features.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Training data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n Returns\n -------\n self : object\n Returns the instance itself.\n \"\"\"\n\n X = self._validate_data(X, accept_sparse=\"csr\")\n random_state = check_random_state(self.random_state)\n n_features = X.shape[1]\n\n self.random_weights_ = np.sqrt(2 * self.gamma) * random_state.normal(\n size=(n_features, self.n_components)\n )\n\n self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components)\n return self\n\n def transform(self, X):\n \"\"\"Apply the approximate feature map to X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n New data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n Returns\n -------\n X_new : array-like, shape (n_samples, n_components)\n Returns the instance itself.\n \"\"\"\n check_is_fitted(self)\n\n X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n projection = safe_sparse_dot(X, self.random_weights_)\n projection += self.random_offset_\n np.cos(projection, projection)\n projection *= np.sqrt(2.0) / np.sqrt(self.n_components)\n return projection\n\n\nclass SkewedChi2Sampler(TransformerMixin, BaseEstimator):\n \"\"\"Approximate feature map for \"skewed chi-squared\" kernel.\n\n Read more in the :ref:`User Guide <skewed_chi_kernel_approx>`.\n\n Parameters\n ----------\n skewedness : float, default=1.0\n \"skewedness\" parameter of the kernel. Needs to be cross-validated.\n\n n_components : int, default=100\n Number of Monte Carlo samples per original feature.\n Equals the dimensionality of the computed feature space.\n\n random_state : int, RandomState instance or None, default=None\n Pseudo-random number generator to control the generation of the random\n weights and random offset when fitting the training data.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Attributes\n ----------\n random_weights_ : ndarray of shape (n_features, n_components)\n Weight array, sampled from a secant hyperbolic distribution, which will\n be used to linearly transform the log of the data.\n\n random_offset_ : ndarray of shape (n_features, n_components)\n Bias term, which will be added to the data. It is uniformly distributed\n between 0 and 2*pi.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.\n Nystroem : Approximate a kernel map using a subset of the training data.\n RBFSampler : Approximate a RBF kernel feature map using random Fourier\n features.\n SkewedChi2Sampler : Approximate feature map for \"skewed chi-squared\" kernel.\n sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.\n sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.\n\n References\n ----------\n See \"Random Fourier Approximations for Skewed Multiplicative Histogram\n Kernels\" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu.\n\n Examples\n --------\n >>> from sklearn.kernel_approximation import SkewedChi2Sampler\n >>> from sklearn.linear_model import SGDClassifier\n >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]\n >>> y = [0, 0, 1, 1]\n >>> chi2_feature = SkewedChi2Sampler(skewedness=.01,\n ... n_components=10,\n ... random_state=0)\n >>> X_features = chi2_feature.fit_transform(X, y)\n >>> clf = SGDClassifier(max_iter=10, tol=1e-3)\n >>> clf.fit(X_features, y)\n SGDClassifier(max_iter=10)\n >>> clf.score(X_features, y)\n 1.0\n \"\"\"\n\n def __init__(self, *, skewedness=1.0, n_components=100, random_state=None):\n self.skewedness = skewedness\n self.n_components = n_components\n self.random_state = random_state\n\n def fit(self, X, y=None):\n \"\"\"Fit the model with X.\n\n Samples random projection according to n_features.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n Returns\n -------\n self : object\n Returns the instance itself.\n \"\"\"\n\n X = self._validate_data(X)\n random_state = check_random_state(self.random_state)\n n_features = X.shape[1]\n uniform = random_state.uniform(size=(n_features, self.n_components))\n # transform by inverse CDF of sech\n self.random_weights_ = 1.0 / np.pi * np.log(np.tan(np.pi / 2.0 * uniform))\n self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components)\n return self\n\n def transform(self, X):\n \"\"\"Apply the approximate feature map to X.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n New data, where `n_samples` is the number of samples\n and `n_features` is the number of features. All values of X must be\n strictly greater than \"-skewedness\".\n\n Returns\n -------\n X_new : array-like, shape (n_samples, n_components)\n Returns the instance itself.\n \"\"\"\n check_is_fitted(self)\n X = self._validate_data(\n X, copy=True, dtype=[np.float64, np.float32], reset=False\n )\n if (X <= -self.skewedness).any():\n raise ValueError(\"X may not contain entries smaller than -skewedness.\")\n\n X += self.skewedness\n np.log(X, X)\n projection = safe_sparse_dot(X, self.random_weights_)\n projection += self.random_offset_\n np.cos(projection, projection)\n projection *= np.sqrt(2.0) / np.sqrt(self.n_components)\n return projection\n\n\nclass AdditiveChi2Sampler(TransformerMixin, BaseEstimator):\n \"\"\"Approximate feature map for additive chi2 kernel.\n\n Uses sampling the fourier transform of the kernel characteristic\n at regular intervals.\n\n Since the kernel that is to be approximated is additive, the components of\n the input vectors can be treated separately. Each entry in the original\n space is transformed into 2*sample_steps+1 features, where sample_steps is\n a parameter of the method. Typical values of sample_steps include 1, 2 and\n 3.\n\n Optimal choices for the sampling interval for certain data ranges can be\n computed (see the reference). The default values should be reasonable.\n\n Read more in the :ref:`User Guide <additive_chi_kernel_approx>`.\n\n Parameters\n ----------\n sample_steps : int, default=2\n Gives the number of (complex) sampling points.\n\n sample_interval : float, default=None\n Sampling interval. Must be specified when sample_steps not in {1,2,3}.\n\n Attributes\n ----------\n sample_interval_ : float\n Stored sampling interval. Specified as a parameter if `sample_steps`\n not in {1,2,3}.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of\n the chi squared kernel.\n\n sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.\n\n sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi\n squared kernel.\n\n Notes\n -----\n This estimator approximates a slightly different version of the additive\n chi squared kernel then ``metric.additive_chi2`` computes.\n\n References\n ----------\n See `\"Efficient additive kernels via explicit feature maps\"\n <http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf>`_\n A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence,\n 2011\n\n Examples\n --------\n >>> from sklearn.datasets import load_digits\n >>> from sklearn.linear_model import SGDClassifier\n >>> from sklearn.kernel_approximation import AdditiveChi2Sampler\n >>> X, y = load_digits(return_X_y=True)\n >>> chi2sampler = AdditiveChi2Sampler(sample_steps=2)\n >>> X_transformed = chi2sampler.fit_transform(X, y)\n >>> clf = SGDClassifier(max_iter=5, random_state=0, tol=1e-3)\n >>> clf.fit(X_transformed, y)\n SGDClassifier(max_iter=5, random_state=0)\n >>> clf.score(X_transformed, y)\n 0.9499...\n \"\"\"\n\n def __init__(self, *, sample_steps=2, sample_interval=None):\n self.sample_steps = sample_steps\n self.sample_interval = sample_interval\n\n def fit(self, X, y=None):\n \"\"\"Set the parameters.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training data, where `n_samples` is the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n Returns\n -------\n self : object\n Returns the transformer.\n \"\"\"\n X = self._validate_data(X, accept_sparse=\"csr\")\n check_non_negative(X, \"X in AdditiveChi2Sampler.fit\")\n\n if self.sample_interval is None:\n # See reference, figure 2 c)\n if self.sample_steps == 1:\n self.sample_interval_ = 0.8\n elif self.sample_steps == 2:\n self.sample_interval_ = 0.5\n elif self.sample_steps == 3:\n self.sample_interval_ = 0.4\n else:\n raise ValueError(\n \"If sample_steps is not in [1, 2, 3],\"\n \" you need to provide sample_interval\"\n )\n else:\n self.sample_interval_ = self.sample_interval\n return self\n\n def transform(self, X):\n \"\"\"Apply approximate feature map to X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Training data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n Returns\n -------\n X_new : {ndarray, sparse matrix}, \\\n shape = (n_samples, n_features * (2*sample_steps + 1))\n Whether the return value is an array or sparse matrix depends on\n the type of the input X.\n \"\"\"\n msg = (\n \"%(name)s is not fitted. Call fit to set the parameters before\"\n \" calling transform\"\n )\n check_is_fitted(self, msg=msg)\n\n X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n check_non_negative(X, \"X in AdditiveChi2Sampler.transform\")\n sparse = sp.issparse(X)\n\n # zeroth component\n # 1/cosh = sech\n # cosh(0) = 1.0\n\n transf = self._transform_sparse if sparse else self._transform_dense\n return transf(X)\n\n def _transform_dense(self, X):\n non_zero = X != 0.0\n X_nz = X[non_zero]\n\n X_step = np.zeros_like(X)\n X_step[non_zero] = np.sqrt(X_nz * self.sample_interval_)\n\n X_new = [X_step]\n\n log_step_nz = self.sample_interval_ * np.log(X_nz)\n step_nz = 2 * X_nz * self.sample_interval_\n\n for j in range(1, self.sample_steps):\n factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * self.sample_interval_))\n\n X_step = np.zeros_like(X)\n X_step[non_zero] = factor_nz * np.cos(j * log_step_nz)\n X_new.append(X_step)\n\n X_step = np.zeros_like(X)\n X_step[non_zero] = factor_nz * np.sin(j * log_step_nz)\n X_new.append(X_step)\n\n return np.hstack(X_new)\n\n def _transform_sparse(self, X):\n indices = X.indices.copy()\n indptr = X.indptr.copy()\n\n data_step = np.sqrt(X.data * self.sample_interval_)\n X_step = sp.csr_matrix(\n (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False\n )\n X_new = [X_step]\n\n log_step_nz = self.sample_interval_ * np.log(X.data)\n step_nz = 2 * X.data * self.sample_interval_\n\n for j in range(1, self.sample_steps):\n factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * self.sample_interval_))\n\n data_step = factor_nz * np.cos(j * log_step_nz)\n X_step = sp.csr_matrix(\n (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False\n )\n X_new.append(X_step)\n\n data_step = factor_nz * np.sin(j * log_step_nz)\n X_step = sp.csr_matrix(\n (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False\n )\n X_new.append(X_step)\n\n return sp.hstack(X_new)\n\n def _more_tags(self):\n return {\"stateless\": True, \"requires_positive_X\": True}\n\n\nclass Nystroem(TransformerMixin, BaseEstimator):\n \"\"\"Approximate a kernel map using a subset of the training data.\n\n Constructs an approximate feature map for an arbitrary kernel\n using a subset of the data as basis.\n\n Read more in the :ref:`User Guide <nystroem_kernel_approx>`.\n\n .. versionadded:: 0.13\n\n Parameters\n ----------\n kernel : str or callable, default='rbf'\n Kernel map to be approximated. A callable should accept two arguments\n and the keyword arguments passed to this object as `kernel_params`, and\n should return a floating point number.\n\n gamma : float, default=None\n Gamma parameter for the RBF, laplacian, polynomial, exponential chi2\n and sigmoid kernels. Interpretation of the default value is left to\n the kernel; see the documentation for sklearn.metrics.pairwise.\n Ignored by other kernels.\n\n coef0 : float, default=None\n Zero coefficient for polynomial and sigmoid kernels.\n Ignored by other kernels.\n\n degree : float, default=None\n Degree of the polynomial kernel. Ignored by other kernels.\n\n kernel_params : dict, default=None\n Additional parameters (keyword arguments) for kernel function passed\n as callable object.\n\n n_components : int, default=100\n Number of features to construct.\n How many data points will be used to construct the mapping.\n\n random_state : int, RandomState instance or None, default=None\n Pseudo-random number generator to control the uniform sampling without\n replacement of `n_components` of the training data to construct the\n basis kernel.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n n_jobs : int, default=None\n The number of jobs to use for the computation. This works by breaking\n down the kernel matrix into `n_jobs` even slices and computing them in\n parallel.\n\n ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n ``-1`` means using all processors. See :term:`Glossary <n_jobs>`\n for more details.\n\n .. versionadded:: 0.24\n\n Attributes\n ----------\n components_ : ndarray of shape (n_components, n_features)\n Subset of training points used to construct the feature map.\n\n component_indices_ : ndarray of shape (n_components)\n Indices of ``components_`` in the training set.\n\n normalization_ : ndarray of shape (n_components, n_components)\n Normalization matrix needed for embedding.\n Square root of the kernel matrix on ``components_``.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.\n PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.\n RBFSampler : Approximate a RBF kernel feature map using random Fourier\n features.\n SkewedChi2Sampler : Approximate feature map for \"skewed chi-squared\" kernel.\n sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.\n\n References\n ----------\n * Williams, C.K.I. and Seeger, M.\n \"Using the Nystroem method to speed up kernel machines\",\n Advances in neural information processing systems 2001\n\n * T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou\n \"Nystroem Method vs Random Fourier Features: A Theoretical and Empirical\n Comparison\",\n Advances in Neural Information Processing Systems 2012\n\n Examples\n --------\n >>> from sklearn import datasets, svm\n >>> from sklearn.kernel_approximation import Nystroem\n >>> X, y = datasets.load_digits(n_class=9, return_X_y=True)\n >>> data = X / 16.\n >>> clf = svm.LinearSVC()\n >>> feature_map_nystroem = Nystroem(gamma=.2,\n ... random_state=1,\n ... n_components=300)\n >>> data_transformed = feature_map_nystroem.fit_transform(data)\n >>> clf.fit(data_transformed, y)\n LinearSVC()\n >>> clf.score(data_transformed, y)\n 0.9987...\n \"\"\"\n\n def __init__(\n self,\n kernel=\"rbf\",\n *,\n gamma=None,\n coef0=None,\n degree=None,\n kernel_params=None,\n n_components=100,\n random_state=None,\n n_jobs=None,\n ):\n\n self.kernel = kernel\n self.gamma = gamma\n self.coef0 = coef0\n self.degree = degree\n self.kernel_params = kernel_params\n self.n_components = n_components\n self.random_state = random_state\n self.n_jobs = n_jobs\n\n def fit(self, X, y=None):\n \"\"\"Fit estimator to data.\n\n Samples a subset of training points, computes kernel\n on these and computes normalization matrix.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training data, where `n_samples` in the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n Returns\n -------\n self : object\n Returns the instance itself.\n \"\"\"\n X = self._validate_data(X, accept_sparse=\"csr\")\n rnd = check_random_state(self.random_state)\n n_samples = X.shape[0]\n\n # get basis vectors\n if self.n_components > n_samples:\n # XXX should we just bail?\n n_components = n_samples\n warnings.warn(\n \"n_components > n_samples. This is not possible.\\n\"\n \"n_components was set to n_samples, which results\"\n \" in inefficient evaluation of the full kernel.\"\n )\n\n else:\n n_components = self.n_components\n n_components = min(n_samples, n_components)\n inds = rnd.permutation(n_samples)\n basis_inds = inds[:n_components]\n basis = X[basis_inds]\n\n basis_kernel = pairwise_kernels(\n basis,\n metric=self.kernel,\n filter_params=True,\n n_jobs=self.n_jobs,\n **self._get_kernel_params(),\n )\n\n # sqrt of kernel matrix on basis vectors\n U, S, V = svd(basis_kernel)\n S = np.maximum(S, 1e-12)\n self.normalization_ = np.dot(U / np.sqrt(S), V)\n self.components_ = basis\n self.component_indices_ = inds\n return self\n\n def transform(self, X):\n \"\"\"Apply feature map to X.\n\n Computes an approximate feature map using the kernel\n between some training points and X.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Data to transform.\n\n Returns\n -------\n X_transformed : ndarray of shape (n_samples, n_components)\n Transformed data.\n \"\"\"\n check_is_fitted(self)\n X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n\n kernel_params = self._get_kernel_params()\n embedded = pairwise_kernels(\n X,\n self.components_,\n metric=self.kernel,\n filter_params=True,\n n_jobs=self.n_jobs,\n **kernel_params,\n )\n return np.dot(embedded, self.normalization_.T)\n\n def _get_kernel_params(self):\n params = self.kernel_params\n if params is None:\n params = {}\n if not callable(self.kernel) and self.kernel != \"precomputed\":\n for param in KERNEL_PARAMS[self.kernel]:\n if getattr(self, param) is not None:\n params[param] = getattr(self, param)\n else:\n if (\n self.gamma is not None\n or self.coef0 is not None\n or self.degree is not None\n ):\n raise ValueError(\n \"Don't pass gamma, coef0 or degree to \"\n \"Nystroem if using a callable \"\n \"or precomputed kernel\"\n )\n\n return params\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_transformer_preserve_dtypes\": (\n \"dtypes are preserved but not at a close enough precision\"\n )\n },\n \"preserves_dtype\": [np.float64, np.float32],\n }\n",
"\"\"\"Multi-layer Perceptron\n\"\"\"\n\n# Authors: Issam H. Laradji <issam.laradji@gmail.com>\n# Andreas Mueller\n# Jiyuan Qian\n# License: BSD 3 clause\nimport os\nimport numpy as np\n\nfrom abc import ABCMeta, abstractmethod\nimport warnings\n\nimport scipy.optimize\n\nfrom ..base import (\n BaseEstimator,\n ClassifierMixin,\n RegressorMixin,\n)\nfrom ..base import is_classifier\nfrom ._base import ACTIVATIONS, DERIVATIVES, LOSS_FUNCTIONS\nfrom ._stochastic_optimizers import SGDOptimizer, AdamOptimizer\nfrom ..model_selection import train_test_split\nfrom ..preprocessing import LabelBinarizer\nfrom ..utils import gen_batches, check_random_state\nfrom ..utils import shuffle\nfrom ..utils import _safe_indexing\nfrom ..utils import column_or_1d\nfrom ..exceptions import ConvergenceWarning\nfrom ..utils.extmath import safe_sparse_dot\nfrom ..utils.validation import check_is_fitted\nfrom ..utils.multiclass import _check_partial_fit_first_call, unique_labels\nfrom ..utils.multiclass import type_of_target\nfrom ..utils.optimize import _check_optimize_result\nfrom ..utils.metaestimators import available_if\n\n\n_STOCHASTIC_SOLVERS = [\"sgd\", \"adam\"]\n\n\ndef _pack(coefs_, intercepts_):\n \"\"\"Pack the parameters into a single vector.\"\"\"\n return np.hstack([l.ravel() for l in coefs_ + intercepts_])\n\n\nclass BaseMultilayerPerceptron(BaseEstimator, metaclass=ABCMeta):\n \"\"\"Base class for MLP classification and regression.\n\n Warning: This class should not be used directly.\n Use derived classes instead.\n\n .. versionadded:: 0.18\n \"\"\"\n\n @abstractmethod\n def __init__(\n self,\n hidden_layer_sizes,\n activation,\n solver,\n alpha,\n batch_size,\n learning_rate,\n learning_rate_init,\n power_t,\n max_iter,\n loss,\n shuffle,\n random_state,\n tol,\n verbose,\n warm_start,\n momentum,\n nesterovs_momentum,\n early_stopping,\n validation_fraction,\n beta_1,\n beta_2,\n epsilon,\n n_iter_no_change,\n max_fun,\n ):\n self.activation = activation\n self.solver = solver\n self.alpha = alpha\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.learning_rate_init = learning_rate_init\n self.power_t = power_t\n self.max_iter = max_iter\n self.loss = loss\n self.hidden_layer_sizes = hidden_layer_sizes\n self.shuffle = shuffle\n self.random_state = random_state\n self.tol = tol\n self.verbose = verbose\n self.warm_start = warm_start\n self.momentum = momentum\n self.nesterovs_momentum = nesterovs_momentum\n self.early_stopping = early_stopping\n self.validation_fraction = validation_fraction\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n self.n_iter_no_change = n_iter_no_change\n self.max_fun = max_fun\n\n def _unpack(self, packed_parameters):\n \"\"\"Extract the coefficients and intercepts from packed_parameters.\"\"\"\n for i in range(self.n_layers_ - 1):\n start, end, shape = self._coef_indptr[i]\n self.coefs_[i] = np.reshape(packed_parameters[start:end], shape)\n\n start, end = self._intercept_indptr[i]\n self.intercepts_[i] = packed_parameters[start:end]\n\n def _forward_pass(self, activations):\n \"\"\"Perform a forward pass on the network by computing the values\n of the neurons in the hidden layers and the output layer.\n\n Parameters\n ----------\n activations : list, length = n_layers - 1\n The ith element of the list holds the values of the ith layer.\n \"\"\"\n hidden_activation = ACTIVATIONS[self.activation]\n # Iterate over the hidden layers\n for i in range(self.n_layers_ - 1):\n activations[i + 1] = safe_sparse_dot(activations[i], self.coefs_[i])\n activations[i + 1] += self.intercepts_[i]\n\n # For the hidden layers\n if (i + 1) != (self.n_layers_ - 1):\n hidden_activation(activations[i + 1])\n\n # For the last layer\n output_activation = ACTIVATIONS[self.out_activation_]\n output_activation(activations[i + 1])\n\n return activations\n\n def _forward_pass_fast(self, X):\n \"\"\"Predict using the trained model\n\n This is the same as _forward_pass but does not record the activations\n of all layers and only returns the last layer's activation.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n Returns\n -------\n y_pred : ndarray of shape (n_samples,) or (n_samples, n_outputs)\n The decision function of the samples for each class in the model.\n \"\"\"\n X = self._validate_data(X, accept_sparse=[\"csr\", \"csc\"], reset=False)\n\n # Initialize first layer\n activation = X\n\n # Forward propagate\n hidden_activation = ACTIVATIONS[self.activation]\n for i in range(self.n_layers_ - 1):\n activation = safe_sparse_dot(activation, self.coefs_[i])\n activation += self.intercepts_[i]\n if i != self.n_layers_ - 2:\n hidden_activation(activation)\n output_activation = ACTIVATIONS[self.out_activation_]\n output_activation(activation)\n\n return activation\n\n def _compute_loss_grad(\n self, layer, n_samples, activations, deltas, coef_grads, intercept_grads\n ):\n \"\"\"Compute the gradient of loss with respect to coefs and intercept for\n specified layer.\n\n This function does backpropagation for the specified one layer.\n \"\"\"\n coef_grads[layer] = safe_sparse_dot(activations[layer].T, deltas[layer])\n coef_grads[layer] += self.alpha * self.coefs_[layer]\n coef_grads[layer] /= n_samples\n\n intercept_grads[layer] = np.mean(deltas[layer], 0)\n\n def _loss_grad_lbfgs(\n self, packed_coef_inter, X, y, activations, deltas, coef_grads, intercept_grads\n ):\n \"\"\"Compute the MLP loss function and its corresponding derivatives\n with respect to the different parameters given in the initialization.\n\n Returned gradients are packed in a single vector so it can be used\n in lbfgs\n\n Parameters\n ----------\n packed_coef_inter : ndarray\n A vector comprising the flattened coefficients and intercepts.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n y : ndarray of shape (n_samples,)\n The target values.\n\n activations : list, length = n_layers - 1\n The ith element of the list holds the values of the ith layer.\n\n deltas : list, length = n_layers - 1\n The ith element of the list holds the difference between the\n activations of the i + 1 layer and the backpropagated error.\n More specifically, deltas are gradients of loss with respect to z\n in each layer, where z = wx + b is the value of a particular layer\n before passing through the activation function\n\n coef_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the\n coefficient parameters of the ith layer in an iteration.\n\n intercept_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the\n intercept parameters of the ith layer in an iteration.\n\n Returns\n -------\n loss : float\n grad : array-like, shape (number of nodes of all layers,)\n \"\"\"\n self._unpack(packed_coef_inter)\n loss, coef_grads, intercept_grads = self._backprop(\n X, y, activations, deltas, coef_grads, intercept_grads\n )\n grad = _pack(coef_grads, intercept_grads)\n return loss, grad\n\n def _backprop(self, X, y, activations, deltas, coef_grads, intercept_grads):\n \"\"\"Compute the MLP loss function and its corresponding derivatives\n with respect to each parameter: weights and bias vectors.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n y : ndarray of shape (n_samples,)\n The target values.\n\n activations : list, length = n_layers - 1\n The ith element of the list holds the values of the ith layer.\n\n deltas : list, length = n_layers - 1\n The ith element of the list holds the difference between the\n activations of the i + 1 layer and the backpropagated error.\n More specifically, deltas are gradients of loss with respect to z\n in each layer, where z = wx + b is the value of a particular layer\n before passing through the activation function\n\n coef_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the\n coefficient parameters of the ith layer in an iteration.\n\n intercept_grads : list, length = n_layers - 1\n The ith element contains the amount of change used to update the\n intercept parameters of the ith layer in an iteration.\n\n Returns\n -------\n loss : float\n coef_grads : list, length = n_layers - 1\n intercept_grads : list, length = n_layers - 1\n \"\"\"\n n_samples = X.shape[0]\n\n # Forward propagate\n activations = self._forward_pass(activations)\n\n # Get loss\n loss_func_name = self.loss\n if loss_func_name == \"log_loss\" and self.out_activation_ == \"logistic\":\n loss_func_name = \"binary_log_loss\"\n loss = LOSS_FUNCTIONS[loss_func_name](y, activations[-1])\n # Add L2 regularization term to loss\n values = 0\n for s in self.coefs_:\n s = s.ravel()\n values += np.dot(s, s)\n loss += (0.5 * self.alpha) * values / n_samples\n\n # Backward propagate\n last = self.n_layers_ - 2\n\n # The calculation of delta[last] here works with following\n # combinations of output activation and loss function:\n # sigmoid and binary cross entropy, softmax and categorical cross\n # entropy, and identity with squared loss\n deltas[last] = activations[-1] - y\n\n # Compute gradient for the last layer\n self._compute_loss_grad(\n last, n_samples, activations, deltas, coef_grads, intercept_grads\n )\n\n inplace_derivative = DERIVATIVES[self.activation]\n # Iterate over the hidden layers\n for i in range(self.n_layers_ - 2, 0, -1):\n deltas[i - 1] = safe_sparse_dot(deltas[i], self.coefs_[i].T)\n inplace_derivative(activations[i], deltas[i - 1])\n\n self._compute_loss_grad(\n i - 1, n_samples, activations, deltas, coef_grads, intercept_grads\n )\n\n return loss, coef_grads, intercept_grads\n\n def _initialize(self, y, layer_units, dtype):\n # set all attributes, allocate weights etc for first call\n # Initialize parameters\n self.n_iter_ = 0\n self.t_ = 0\n self.n_outputs_ = y.shape[1]\n\n # Compute the number of layers\n self.n_layers_ = len(layer_units)\n\n # Output for regression\n if not is_classifier(self):\n self.out_activation_ = \"identity\"\n # Output for multi class\n elif self._label_binarizer.y_type_ == \"multiclass\":\n self.out_activation_ = \"softmax\"\n # Output for binary class and multi-label\n else:\n self.out_activation_ = \"logistic\"\n\n # Initialize coefficient and intercept layers\n self.coefs_ = []\n self.intercepts_ = []\n\n for i in range(self.n_layers_ - 1):\n coef_init, intercept_init = self._init_coef(\n layer_units[i], layer_units[i + 1], dtype\n )\n self.coefs_.append(coef_init)\n self.intercepts_.append(intercept_init)\n\n if self.solver in _STOCHASTIC_SOLVERS:\n self.loss_curve_ = []\n self._no_improvement_count = 0\n if self.early_stopping:\n self.validation_scores_ = []\n self.best_validation_score_ = -np.inf\n else:\n self.best_loss_ = np.inf\n\n def _init_coef(self, fan_in, fan_out, dtype):\n # Use the initialization method recommended by\n # Glorot et al.\n factor = 6.0\n if self.activation == \"logistic\":\n factor = 2.0\n init_bound = np.sqrt(factor / (fan_in + fan_out))\n\n # Generate weights and bias:\n coef_init = self._random_state.uniform(\n -init_bound, init_bound, (fan_in, fan_out)\n )\n intercept_init = self._random_state.uniform(-init_bound, init_bound, fan_out)\n coef_init = coef_init.astype(dtype, copy=False)\n intercept_init = intercept_init.astype(dtype, copy=False)\n return coef_init, intercept_init\n\n def _fit(self, X, y, incremental=False):\n # Make sure self.hidden_layer_sizes is a list\n hidden_layer_sizes = self.hidden_layer_sizes\n if not hasattr(hidden_layer_sizes, \"__iter__\"):\n hidden_layer_sizes = [hidden_layer_sizes]\n hidden_layer_sizes = list(hidden_layer_sizes)\n\n # Validate input parameters.\n self._validate_hyperparameters()\n if np.any(np.array(hidden_layer_sizes) <= 0):\n raise ValueError(\n \"hidden_layer_sizes must be > 0, got %s.\" % hidden_layer_sizes\n )\n first_pass = not hasattr(self, \"coefs_\") or (\n not self.warm_start and not incremental\n )\n\n X, y = self._validate_input(X, y, incremental, reset=first_pass)\n\n n_samples, n_features = X.shape\n\n # Ensure y is 2D\n if y.ndim == 1:\n y = y.reshape((-1, 1))\n\n self.n_outputs_ = y.shape[1]\n\n layer_units = [n_features] + hidden_layer_sizes + [self.n_outputs_]\n\n # check random state\n self._random_state = check_random_state(self.random_state)\n\n if first_pass:\n # First time training the model\n self._initialize(y, layer_units, X.dtype)\n\n # Initialize lists\n activations = [X] + [None] * (len(layer_units) - 1)\n deltas = [None] * (len(activations) - 1)\n\n coef_grads = [\n np.empty((n_fan_in_, n_fan_out_), dtype=X.dtype)\n for n_fan_in_, n_fan_out_ in zip(layer_units[:-1], layer_units[1:])\n ]\n\n intercept_grads = [\n np.empty(n_fan_out_, dtype=X.dtype) for n_fan_out_ in layer_units[1:]\n ]\n\n # Run the Stochastic optimization solver\n if self.solver in _STOCHASTIC_SOLVERS:\n self._fit_stochastic(\n X,\n y,\n activations,\n deltas,\n coef_grads,\n intercept_grads,\n layer_units,\n incremental,\n )\n\n # Run the LBFGS solver\n elif self.solver == \"lbfgs\":\n self._fit_lbfgs(\n X, y, activations, deltas, coef_grads, intercept_grads, layer_units\n )\n return self\n\n def _validate_hyperparameters(self):\n if not isinstance(self.shuffle, bool):\n raise ValueError(\n \"shuffle must be either True or False, got %s.\" % self.shuffle\n )\n if self.max_iter <= 0:\n raise ValueError(\"max_iter must be > 0, got %s.\" % self.max_iter)\n if self.max_fun <= 0:\n raise ValueError(\"max_fun must be > 0, got %s.\" % self.max_fun)\n if self.alpha < 0.0:\n raise ValueError(\"alpha must be >= 0, got %s.\" % self.alpha)\n if (\n self.learning_rate in [\"constant\", \"invscaling\", \"adaptive\"]\n and self.learning_rate_init <= 0.0\n ):\n raise ValueError(\n \"learning_rate_init must be > 0, got %s.\" % self.learning_rate\n )\n if self.momentum > 1 or self.momentum < 0:\n raise ValueError(\"momentum must be >= 0 and <= 1, got %s\" % self.momentum)\n if not isinstance(self.nesterovs_momentum, bool):\n raise ValueError(\n \"nesterovs_momentum must be either True or False, got %s.\"\n % self.nesterovs_momentum\n )\n if not isinstance(self.early_stopping, bool):\n raise ValueError(\n \"early_stopping must be either True or False, got %s.\"\n % self.early_stopping\n )\n if self.validation_fraction < 0 or self.validation_fraction >= 1:\n raise ValueError(\n \"validation_fraction must be >= 0 and < 1, got %s\"\n % self.validation_fraction\n )\n if self.beta_1 < 0 or self.beta_1 >= 1:\n raise ValueError(\"beta_1 must be >= 0 and < 1, got %s\" % self.beta_1)\n if self.beta_2 < 0 or self.beta_2 >= 1:\n raise ValueError(\"beta_2 must be >= 0 and < 1, got %s\" % self.beta_2)\n if self.epsilon <= 0.0:\n raise ValueError(\"epsilon must be > 0, got %s.\" % self.epsilon)\n if self.n_iter_no_change <= 0:\n raise ValueError(\n \"n_iter_no_change must be > 0, got %s.\" % self.n_iter_no_change\n )\n\n # raise ValueError if not registered\n if self.activation not in ACTIVATIONS:\n raise ValueError(\n \"The activation '%s' is not supported. Supported activations are %s.\"\n % (self.activation, list(sorted(ACTIVATIONS)))\n )\n if self.learning_rate not in [\"constant\", \"invscaling\", \"adaptive\"]:\n raise ValueError(\"learning rate %s is not supported. \" % self.learning_rate)\n supported_solvers = _STOCHASTIC_SOLVERS + [\"lbfgs\"]\n if self.solver not in supported_solvers:\n raise ValueError(\n \"The solver %s is not supported. Expected one of: %s\"\n % (self.solver, \", \".join(supported_solvers))\n )\n\n def _fit_lbfgs(\n self, X, y, activations, deltas, coef_grads, intercept_grads, layer_units\n ):\n # Store meta information for the parameters\n self._coef_indptr = []\n self._intercept_indptr = []\n start = 0\n\n # Save sizes and indices of coefficients for faster unpacking\n for i in range(self.n_layers_ - 1):\n n_fan_in, n_fan_out = layer_units[i], layer_units[i + 1]\n\n end = start + (n_fan_in * n_fan_out)\n self._coef_indptr.append((start, end, (n_fan_in, n_fan_out)))\n start = end\n\n # Save sizes and indices of intercepts for faster unpacking\n for i in range(self.n_layers_ - 1):\n end = start + layer_units[i + 1]\n self._intercept_indptr.append((start, end))\n start = end\n\n # Run LBFGS\n packed_coef_inter = _pack(self.coefs_, self.intercepts_)\n\n if self.verbose is True or self.verbose >= 1:\n iprint = 1\n else:\n iprint = -1\n\n opt_res = scipy.optimize.minimize(\n self._loss_grad_lbfgs,\n packed_coef_inter,\n method=\"L-BFGS-B\",\n jac=True,\n options={\n \"maxfun\": self.max_fun,\n \"maxiter\": self.max_iter,\n \"iprint\": iprint,\n \"gtol\": self.tol,\n },\n args=(X, y, activations, deltas, coef_grads, intercept_grads),\n )\n self.n_iter_ = _check_optimize_result(\"lbfgs\", opt_res, self.max_iter)\n self.loss_ = opt_res.fun\n self._unpack(opt_res.x)\n\n def _fit_stochastic(\n self,\n X,\n y,\n activations,\n deltas,\n coef_grads,\n intercept_grads,\n layer_units,\n incremental,\n ):\n\n params = self.coefs_ + self.intercepts_\n if not incremental or not hasattr(self, \"_optimizer\"):\n if self.solver == \"sgd\":\n self._optimizer = SGDOptimizer(\n params,\n self.learning_rate_init,\n self.learning_rate,\n self.momentum,\n self.nesterovs_momentum,\n self.power_t,\n )\n elif self.solver == \"adam\":\n self._optimizer = AdamOptimizer(\n params,\n self.learning_rate_init,\n self.beta_1,\n self.beta_2,\n self.epsilon,\n )\n\n # early_stopping in partial_fit doesn't make sense\n early_stopping = self.early_stopping and not incremental\n if early_stopping:\n # don't stratify in multilabel classification\n should_stratify = is_classifier(self) and self.n_outputs_ == 1\n stratify = y if should_stratify else None\n X, X_val, y, y_val = train_test_split(\n X,\n y,\n random_state=self._random_state,\n test_size=self.validation_fraction,\n stratify=stratify,\n )\n if is_classifier(self):\n y_val = self._label_binarizer.inverse_transform(y_val)\n else:\n X_val = None\n y_val = None\n\n n_samples = X.shape[0]\n sample_idx = np.arange(n_samples, dtype=int)\n\n if self.batch_size == \"auto\":\n batch_size = min(200, n_samples)\n else:\n if self.batch_size < 1 or self.batch_size > n_samples:\n warnings.warn(\n \"Got `batch_size` less than 1 or larger than \"\n \"sample size. It is going to be clipped\"\n )\n batch_size = np.clip(self.batch_size, 1, n_samples)\n\n try:\n for it in range(self.max_iter):\n if self.shuffle:\n # Only shuffle the sample indices instead of X and y to\n # reduce the memory footprint. These indices will be used\n # to slice the X and y.\n sample_idx = shuffle(sample_idx, random_state=self._random_state)\n\n accumulated_loss = 0.0\n for batch_slice in gen_batches(n_samples, batch_size):\n if self.shuffle:\n X_batch = _safe_indexing(X, sample_idx[batch_slice])\n y_batch = y[sample_idx[batch_slice]]\n else:\n X_batch = X[batch_slice]\n y_batch = y[batch_slice]\n\n activations[0] = X_batch\n batch_loss, coef_grads, intercept_grads = self._backprop(\n X_batch,\n y_batch,\n activations,\n deltas,\n coef_grads,\n intercept_grads,\n )\n accumulated_loss += batch_loss * (\n batch_slice.stop - batch_slice.start\n )\n\n # update weights\n grads = coef_grads + intercept_grads\n self._optimizer.update_params(params, grads)\n\n self.n_iter_ += 1\n self.loss_ = accumulated_loss / X.shape[0]\n\n self.t_ += n_samples\n self.loss_curve_.append(self.loss_)\n if self.verbose:\n print(\"Iteration %d, loss = %.8f\" % (self.n_iter_, self.loss_))\n\n # update no_improvement_count based on training loss or\n # validation score according to early_stopping\n self._update_no_improvement_count(early_stopping, X_val, y_val)\n\n # for learning rate that needs to be updated at iteration end\n self._optimizer.iteration_ends(self.t_)\n\n if self._no_improvement_count > self.n_iter_no_change:\n # not better than last `n_iter_no_change` iterations by tol\n # stop or decrease learning rate\n if early_stopping:\n msg = (\n \"Validation score did not improve more than \"\n \"tol=%f for %d consecutive epochs.\"\n % (self.tol, self.n_iter_no_change)\n )\n else:\n msg = (\n \"Training loss did not improve more than tol=%f\"\n \" for %d consecutive epochs.\"\n % (self.tol, self.n_iter_no_change)\n )\n\n is_stopping = self._optimizer.trigger_stopping(msg, self.verbose)\n if is_stopping:\n break\n else:\n self._no_improvement_count = 0\n\n if incremental:\n break\n\n if self.n_iter_ == self.max_iter:\n warnings.warn(\n \"Stochastic Optimizer: Maximum iterations (%d) \"\n \"reached and the optimization hasn't converged yet.\"\n % self.max_iter,\n ConvergenceWarning,\n )\n except KeyboardInterrupt:\n warnings.warn(\"Training interrupted by user.\")\n\n if early_stopping:\n # restore best weights\n self.coefs_ = self._best_coefs\n self.intercepts_ = self._best_intercepts\n\n def _update_no_improvement_count(self, early_stopping, X_val, y_val):\n if early_stopping:\n # compute validation score, use that for stopping\n self.validation_scores_.append(self.score(X_val, y_val))\n\n if self.verbose:\n print(\"Validation score: %f\" % self.validation_scores_[-1])\n # update best parameters\n # use validation_scores_, not loss_curve_\n # let's hope no-one overloads .score with mse\n last_valid_score = self.validation_scores_[-1]\n\n if last_valid_score < (self.best_validation_score_ + self.tol):\n self._no_improvement_count += 1\n else:\n self._no_improvement_count = 0\n\n if last_valid_score > self.best_validation_score_:\n self.best_validation_score_ = last_valid_score\n self._best_coefs = [c.copy() for c in self.coefs_]\n self._best_intercepts = [i.copy() for i in self.intercepts_]\n else:\n if self.loss_curve_[-1] > self.best_loss_ - self.tol:\n self._no_improvement_count += 1\n else:\n self._no_improvement_count = 0\n if self.loss_curve_[-1] < self.best_loss_:\n self.best_loss_ = self.loss_curve_[-1]\n\n def fit(self, X, y):\n \"\"\"Fit the model to data matrix X and target(s) y.\n\n Parameters\n ----------\n X : ndarray or sparse matrix of shape (n_samples, n_features)\n The input data.\n\n y : ndarray of shape (n_samples,) or (n_samples, n_outputs)\n The target values (class labels in classification, real numbers in\n regression).\n\n Returns\n -------\n self : object\n Returns a trained MLP model.\n \"\"\"\n return self._fit(X, y, incremental=False)\n\n def _check_solver(self):\n if self.solver not in _STOCHASTIC_SOLVERS:\n raise AttributeError(\n \"partial_fit is only available for stochastic\"\n \" optimizers. %s is not stochastic.\"\n % self.solver\n )\n return True\n\n @available_if(_check_solver)\n def partial_fit(self, X, y):\n \"\"\"Update the model with a single iteration over the given data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n y : ndarray of shape (n_samples,)\n The target values.\n\n Returns\n -------\n self : object\n Trained MLP model.\n \"\"\"\n return self._fit(X, y, incremental=True)\n\n\nclass MLPClassifier(ClassifierMixin, BaseMultilayerPerceptron):\n \"\"\"Multi-layer Perceptron classifier.\n\n This model optimizes the log-loss function using LBFGS or stochastic\n gradient descent.\n\n .. versionadded:: 0.18\n\n Parameters\n ----------\n hidden_layer_sizes : tuple, length = n_layers - 2, default=(100,)\n The ith element represents the number of neurons in the ith\n hidden layer.\n\n activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu'\n Activation function for the hidden layer.\n\n - 'identity', no-op activation, useful to implement linear bottleneck,\n returns f(x) = x\n\n - 'logistic', the logistic sigmoid function,\n returns f(x) = 1 / (1 + exp(-x)).\n\n - 'tanh', the hyperbolic tan function,\n returns f(x) = tanh(x).\n\n - 'relu', the rectified linear unit function,\n returns f(x) = max(0, x)\n\n solver : {'lbfgs', 'sgd', 'adam'}, default='adam'\n The solver for weight optimization.\n\n - 'lbfgs' is an optimizer in the family of quasi-Newton methods.\n\n - 'sgd' refers to stochastic gradient descent.\n\n - 'adam' refers to a stochastic gradient-based optimizer proposed\n by Kingma, Diederik, and Jimmy Ba\n\n Note: The default solver 'adam' works pretty well on relatively\n large datasets (with thousands of training samples or more) in terms of\n both training time and validation score.\n For small datasets, however, 'lbfgs' can converge faster and perform\n better.\n\n alpha : float, default=0.0001\n L2 penalty (regularization term) parameter.\n\n batch_size : int, default='auto'\n Size of minibatches for stochastic optimizers.\n If the solver is 'lbfgs', the classifier will not use minibatch.\n When set to \"auto\", `batch_size=min(200, n_samples)`.\n\n learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant'\n Learning rate schedule for weight updates.\n\n - 'constant' is a constant learning rate given by\n 'learning_rate_init'.\n\n - 'invscaling' gradually decreases the learning rate at each\n time step 't' using an inverse scaling exponent of 'power_t'.\n effective_learning_rate = learning_rate_init / pow(t, power_t)\n\n - 'adaptive' keeps the learning rate constant to\n 'learning_rate_init' as long as training loss keeps decreasing.\n Each time two consecutive epochs fail to decrease training loss by at\n least tol, or fail to increase validation score by at least tol if\n 'early_stopping' is on, the current learning rate is divided by 5.\n\n Only used when ``solver='sgd'``.\n\n learning_rate_init : double, default=0.001\n The initial learning rate used. It controls the step-size\n in updating the weights. Only used when solver='sgd' or 'adam'.\n\n power_t : double, default=0.5\n The exponent for inverse scaling learning rate.\n It is used in updating effective learning rate when the learning_rate\n is set to 'invscaling'. Only used when solver='sgd'.\n\n max_iter : int, default=200\n Maximum number of iterations. The solver iterates until convergence\n (determined by 'tol') or this number of iterations. For stochastic\n solvers ('sgd', 'adam'), note that this determines the number of epochs\n (how many times each data point will be used), not the number of\n gradient steps.\n\n shuffle : bool, default=True\n Whether to shuffle samples in each iteration. Only used when\n solver='sgd' or 'adam'.\n\n random_state : int, RandomState instance, default=None\n Determines random number generation for weights and bias\n initialization, train-test split if early stopping is used, and batch\n sampling when solver='sgd' or 'adam'.\n Pass an int for reproducible results across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n tol : float, default=1e-4\n Tolerance for the optimization. When the loss or score is not improving\n by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,\n unless ``learning_rate`` is set to 'adaptive', convergence is\n considered to be reached and training stops.\n\n verbose : bool, default=False\n Whether to print progress messages to stdout.\n\n warm_start : bool, default=False\n When set to True, reuse the solution of the previous\n call to fit as initialization, otherwise, just erase the\n previous solution. See :term:`the Glossary <warm_start>`.\n\n momentum : float, default=0.9\n Momentum for gradient descent update. Should be between 0 and 1. Only\n used when solver='sgd'.\n\n nesterovs_momentum : bool, default=True\n Whether to use Nesterov's momentum. Only used when solver='sgd' and\n momentum > 0.\n\n early_stopping : bool, default=False\n Whether to use early stopping to terminate training when validation\n score is not improving. If set to true, it will automatically set\n aside 10% of training data as validation and terminate training when\n validation score is not improving by at least tol for\n ``n_iter_no_change`` consecutive epochs. The split is stratified,\n except in a multilabel setting.\n If early stopping is False, then the training stops when the training\n loss does not improve by more than tol for n_iter_no_change consecutive\n passes over the training set.\n Only effective when solver='sgd' or 'adam'.\n\n validation_fraction : float, default=0.1\n The proportion of training data to set aside as validation set for\n early stopping. Must be between 0 and 1.\n Only used if early_stopping is True.\n\n beta_1 : float, default=0.9\n Exponential decay rate for estimates of first moment vector in adam,\n should be in [0, 1). Only used when solver='adam'.\n\n beta_2 : float, default=0.999\n Exponential decay rate for estimates of second moment vector in adam,\n should be in [0, 1). Only used when solver='adam'.\n\n epsilon : float, default=1e-8\n Value for numerical stability in adam. Only used when solver='adam'.\n\n n_iter_no_change : int, default=10\n Maximum number of epochs to not meet ``tol`` improvement.\n Only effective when solver='sgd' or 'adam'.\n\n .. versionadded:: 0.20\n\n max_fun : int, default=15000\n Only used when solver='lbfgs'. Maximum number of loss function calls.\n The solver iterates until convergence (determined by 'tol'), number\n of iterations reaches max_iter, or this number of loss function calls.\n Note that number of loss function calls will be greater than or equal\n to the number of iterations for the `MLPClassifier`.\n\n .. versionadded:: 0.22\n\n Attributes\n ----------\n classes_ : ndarray or list of ndarray of shape (n_classes,)\n Class labels for each output.\n\n loss_ : float\n The current loss computed with the loss function.\n\n best_loss_ : float\n The minimum loss reached by the solver throughout fitting.\n\n loss_curve_ : list of shape (`n_iter_`,)\n The ith element in the list represents the loss at the ith iteration.\n\n t_ : int\n The number of training samples seen by the solver during fitting.\n\n coefs_ : list of shape (n_layers - 1,)\n The ith element in the list represents the weight matrix corresponding\n to layer i.\n\n intercepts_ : list of shape (n_layers - 1,)\n The ith element in the list represents the bias vector corresponding to\n layer i + 1.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n n_iter_ : int\n The number of iterations the solver has run.\n\n n_layers_ : int\n Number of layers.\n\n n_outputs_ : int\n Number of outputs.\n\n out_activation_ : str\n Name of the output activation function.\n\n See Also\n --------\n MLPRegressor : Multi-layer Perceptron regressor.\n BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM).\n\n Notes\n -----\n MLPClassifier trains iteratively since at each time step\n the partial derivatives of the loss function with respect to the model\n parameters are computed to update the parameters.\n\n It can also have a regularization term added to the loss function\n that shrinks model parameters to prevent overfitting.\n\n This implementation works with data represented as dense numpy arrays or\n sparse scipy arrays of floating point values.\n\n References\n ----------\n Hinton, Geoffrey E.\n \"Connectionist learning procedures.\" Artificial intelligence 40.1\n (1989): 185-234.\n\n Glorot, Xavier, and Yoshua Bengio. \"Understanding the difficulty of\n training deep feedforward neural networks.\" International Conference\n on Artificial Intelligence and Statistics. 2010.\n\n He, Kaiming, et al. \"Delving deep into rectifiers: Surpassing human-level\n performance on imagenet classification.\" arXiv preprint\n arXiv:1502.01852 (2015).\n\n Kingma, Diederik, and Jimmy Ba. \"Adam: A method for stochastic\n optimization.\" arXiv preprint arXiv:1412.6980 (2014).\n\n Examples\n --------\n >>> from sklearn.neural_network import MLPClassifier\n >>> from sklearn.datasets import make_classification\n >>> from sklearn.model_selection import train_test_split\n >>> X, y = make_classification(n_samples=100, random_state=1)\n >>> X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y,\n ... random_state=1)\n >>> clf = MLPClassifier(random_state=1, max_iter=300).fit(X_train, y_train)\n >>> clf.predict_proba(X_test[:1])\n array([[0.038..., 0.961...]])\n >>> clf.predict(X_test[:5, :])\n array([1, 0, 1, 0, 1])\n >>> clf.score(X_test, y_test)\n 0.8...\n \"\"\"\n\n def __init__(\n self,\n hidden_layer_sizes=(100,),\n activation=\"relu\",\n *,\n solver=\"adam\",\n alpha=0.0001,\n batch_size=\"auto\",\n learning_rate=\"constant\",\n learning_rate_init=0.001,\n power_t=0.5,\n max_iter=200,\n shuffle=True,\n random_state=None,\n tol=1e-4,\n verbose=False,\n warm_start=False,\n momentum=0.9,\n nesterovs_momentum=True,\n early_stopping=False,\n validation_fraction=0.1,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-8,\n n_iter_no_change=10,\n max_fun=15000,\n ):\n super().__init__(\n hidden_layer_sizes=hidden_layer_sizes,\n activation=activation,\n solver=solver,\n alpha=alpha,\n batch_size=batch_size,\n learning_rate=learning_rate,\n learning_rate_init=learning_rate_init,\n power_t=power_t,\n max_iter=max_iter,\n loss=\"log_loss\",\n shuffle=shuffle,\n random_state=random_state,\n tol=tol,\n verbose=verbose,\n warm_start=warm_start,\n momentum=momentum,\n nesterovs_momentum=nesterovs_momentum,\n early_stopping=early_stopping,\n validation_fraction=validation_fraction,\n beta_1=beta_1,\n beta_2=beta_2,\n epsilon=epsilon,\n n_iter_no_change=n_iter_no_change,\n max_fun=max_fun,\n )\n\n def _validate_input(self, X, y, incremental, reset):\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=[\"csr\", \"csc\"],\n multi_output=True,\n dtype=(np.float64, np.float32),\n reset=reset,\n )\n if y.ndim == 2 and y.shape[1] == 1:\n y = column_or_1d(y, warn=True)\n\n # Matrix of actions to be taken under the possible combinations:\n # The case that incremental == True and classes_ not defined is\n # already checked by _check_partial_fit_first_call that is called\n # in _partial_fit below.\n # The cases are already grouped into the respective if blocks below.\n #\n # incremental warm_start classes_ def action\n # 0 0 0 define classes_\n # 0 1 0 define classes_\n # 0 0 1 redefine classes_\n #\n # 0 1 1 check compat warm_start\n # 1 1 1 check compat warm_start\n #\n # 1 0 1 check compat last fit\n #\n # Note the reliance on short-circuiting here, so that the second\n # or part implies that classes_ is defined.\n if (not hasattr(self, \"classes_\")) or (not self.warm_start and not incremental):\n self._label_binarizer = LabelBinarizer()\n self._label_binarizer.fit(y)\n self.classes_ = self._label_binarizer.classes_\n else:\n classes = unique_labels(y)\n if self.warm_start:\n if set(classes) != set(self.classes_):\n raise ValueError(\n \"warm_start can only be used where `y` has the same \"\n \"classes as in the previous call to fit. Previously \"\n f\"got {self.classes_}, `y` has {classes}\"\n )\n elif len(np.setdiff1d(classes, self.classes_, assume_unique=True)):\n raise ValueError(\n \"`y` has classes not in `self.classes_`. \"\n f\"`self.classes_` has {self.classes_}. 'y' has {classes}.\"\n )\n\n # This downcast to bool is to prevent upcasting when working with\n # float32 data\n y = self._label_binarizer.transform(y).astype(bool)\n return X, y\n\n def predict(self, X):\n \"\"\"Predict using the multi-layer perceptron classifier.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n Returns\n -------\n y : ndarray, shape (n_samples,) or (n_samples, n_classes)\n The predicted classes.\n \"\"\"\n check_is_fitted(self)\n y_pred = self._forward_pass_fast(X)\n\n if self.n_outputs_ == 1:\n y_pred = y_pred.ravel()\n\n return self._label_binarizer.inverse_transform(y_pred)\n\n @available_if(lambda est: est._check_solver())\n def partial_fit(self, X, y, classes=None):\n \"\"\"Update the model with a single iteration over the given data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n y : array-like of shape (n_samples,)\n The target values.\n\n classes : array of shape (n_classes,), default=None\n Classes across all calls to partial_fit.\n Can be obtained via `np.unique(y_all)`, where y_all is the\n target vector of the entire dataset.\n This argument is required for the first call to partial_fit\n and can be omitted in the subsequent calls.\n Note that y doesn't need to contain all labels in `classes`.\n\n Returns\n -------\n self : object\n Trained MLP model.\n \"\"\"\n if _check_partial_fit_first_call(self, classes):\n self._label_binarizer = LabelBinarizer()\n if type_of_target(y).startswith(\"multilabel\"):\n self._label_binarizer.fit(y)\n else:\n self._label_binarizer.fit(classes)\n\n super().partial_fit(X, y)\n\n return self\n\n def predict_log_proba(self, X):\n \"\"\"Return the log of probability estimates.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n The input data.\n\n Returns\n -------\n log_y_prob : ndarray of shape (n_samples, n_classes)\n The predicted log-probability of the sample for each class\n in the model, where classes are ordered as they are in\n `self.classes_`. Equivalent to `log(predict_proba(X))`.\n \"\"\"\n y_prob = self.predict_proba(X)\n return np.log(y_prob, out=y_prob)\n\n def predict_proba(self, X):\n \"\"\"Probability estimates.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n Returns\n -------\n y_prob : ndarray of shape (n_samples, n_classes)\n The predicted probability of the sample for each class in the\n model, where classes are ordered as they are in `self.classes_`.\n \"\"\"\n check_is_fitted(self)\n y_pred = self._forward_pass_fast(X)\n\n if self.n_outputs_ == 1:\n y_pred = y_pred.ravel()\n\n if y_pred.ndim == 1:\n return np.vstack([1 - y_pred, y_pred]).T\n else:\n return y_pred\n\n def _more_tags(self):\n return {\"multilabel\": True}\n\n\nclass MLPRegressor(RegressorMixin, BaseMultilayerPerceptron):\n \"\"\"Multi-layer Perceptron regressor.\n\n This model optimizes the squared error using LBFGS or stochastic gradient\n descent.\n\n .. versionadded:: 0.18\n\n Parameters\n ----------\n hidden_layer_sizes : tuple, length = n_layers - 2, default=(100,)\n The ith element represents the number of neurons in the ith\n hidden layer.\n\n activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu'\n Activation function for the hidden layer.\n\n - 'identity', no-op activation, useful to implement linear bottleneck,\n returns f(x) = x\n\n - 'logistic', the logistic sigmoid function,\n returns f(x) = 1 / (1 + exp(-x)).\n\n - 'tanh', the hyperbolic tan function,\n returns f(x) = tanh(x).\n\n - 'relu', the rectified linear unit function,\n returns f(x) = max(0, x)\n\n solver : {'lbfgs', 'sgd', 'adam'}, default='adam'\n The solver for weight optimization.\n\n - 'lbfgs' is an optimizer in the family of quasi-Newton methods.\n\n - 'sgd' refers to stochastic gradient descent.\n\n - 'adam' refers to a stochastic gradient-based optimizer proposed by\n Kingma, Diederik, and Jimmy Ba\n\n Note: The default solver 'adam' works pretty well on relatively\n large datasets (with thousands of training samples or more) in terms of\n both training time and validation score.\n For small datasets, however, 'lbfgs' can converge faster and perform\n better.\n\n alpha : float, default=0.0001\n L2 penalty (regularization term) parameter.\n\n batch_size : int, default='auto'\n Size of minibatches for stochastic optimizers.\n If the solver is 'lbfgs', the classifier will not use minibatch.\n When set to \"auto\", `batch_size=min(200, n_samples)`.\n\n learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant'\n Learning rate schedule for weight updates.\n\n - 'constant' is a constant learning rate given by\n 'learning_rate_init'.\n\n - 'invscaling' gradually decreases the learning rate ``learning_rate_``\n at each time step 't' using an inverse scaling exponent of 'power_t'.\n effective_learning_rate = learning_rate_init / pow(t, power_t)\n\n - 'adaptive' keeps the learning rate constant to\n 'learning_rate_init' as long as training loss keeps decreasing.\n Each time two consecutive epochs fail to decrease training loss by at\n least tol, or fail to increase validation score by at least tol if\n 'early_stopping' is on, the current learning rate is divided by 5.\n\n Only used when solver='sgd'.\n\n learning_rate_init : double, default=0.001\n The initial learning rate used. It controls the step-size\n in updating the weights. Only used when solver='sgd' or 'adam'.\n\n power_t : double, default=0.5\n The exponent for inverse scaling learning rate.\n It is used in updating effective learning rate when the learning_rate\n is set to 'invscaling'. Only used when solver='sgd'.\n\n max_iter : int, default=200\n Maximum number of iterations. The solver iterates until convergence\n (determined by 'tol') or this number of iterations. For stochastic\n solvers ('sgd', 'adam'), note that this determines the number of epochs\n (how many times each data point will be used), not the number of\n gradient steps.\n\n shuffle : bool, default=True\n Whether to shuffle samples in each iteration. Only used when\n solver='sgd' or 'adam'.\n\n random_state : int, RandomState instance, default=None\n Determines random number generation for weights and bias\n initialization, train-test split if early stopping is used, and batch\n sampling when solver='sgd' or 'adam'.\n Pass an int for reproducible results across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n tol : float, default=1e-4\n Tolerance for the optimization. When the loss or score is not improving\n by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,\n unless ``learning_rate`` is set to 'adaptive', convergence is\n considered to be reached and training stops.\n\n verbose : bool, default=False\n Whether to print progress messages to stdout.\n\n warm_start : bool, default=False\n When set to True, reuse the solution of the previous\n call to fit as initialization, otherwise, just erase the\n previous solution. See :term:`the Glossary <warm_start>`.\n\n momentum : float, default=0.9\n Momentum for gradient descent update. Should be between 0 and 1. Only\n used when solver='sgd'.\n\n nesterovs_momentum : bool, default=True\n Whether to use Nesterov's momentum. Only used when solver='sgd' and\n momentum > 0.\n\n early_stopping : bool, default=False\n Whether to use early stopping to terminate training when validation\n score is not improving. If set to true, it will automatically set\n aside 10% of training data as validation and terminate training when\n validation score is not improving by at least ``tol`` for\n ``n_iter_no_change`` consecutive epochs.\n Only effective when solver='sgd' or 'adam'.\n\n validation_fraction : float, default=0.1\n The proportion of training data to set aside as validation set for\n early stopping. Must be between 0 and 1.\n Only used if early_stopping is True.\n\n beta_1 : float, default=0.9\n Exponential decay rate for estimates of first moment vector in adam,\n should be in [0, 1). Only used when solver='adam'.\n\n beta_2 : float, default=0.999\n Exponential decay rate for estimates of second moment vector in adam,\n should be in [0, 1). Only used when solver='adam'.\n\n epsilon : float, default=1e-8\n Value for numerical stability in adam. Only used when solver='adam'.\n\n n_iter_no_change : int, default=10\n Maximum number of epochs to not meet ``tol`` improvement.\n Only effective when solver='sgd' or 'adam'.\n\n .. versionadded:: 0.20\n\n max_fun : int, default=15000\n Only used when solver='lbfgs'. Maximum number of function calls.\n The solver iterates until convergence (determined by 'tol'), number\n of iterations reaches max_iter, or this number of function calls.\n Note that number of function calls will be greater than or equal to\n the number of iterations for the MLPRegressor.\n\n .. versionadded:: 0.22\n\n Attributes\n ----------\n loss_ : float\n The current loss computed with the loss function.\n\n best_loss_ : float\n The minimum loss reached by the solver throughout fitting.\n\n loss_curve_ : list of shape (`n_iter_`,)\n Loss value evaluated at the end of each training step.\n The ith element in the list represents the loss at the ith iteration.\n\n t_ : int\n The number of training samples seen by the solver during fitting.\n Mathematically equals `n_iters * X.shape[0]`, it means\n `time_step` and it is used by optimizer's learning rate scheduler.\n\n coefs_ : list of shape (n_layers - 1,)\n The ith element in the list represents the weight matrix corresponding\n to layer i.\n\n intercepts_ : list of shape (n_layers - 1,)\n The ith element in the list represents the bias vector corresponding to\n layer i + 1.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n n_iter_ : int\n The number of iterations the solver has run.\n\n n_layers_ : int\n Number of layers.\n\n n_outputs_ : int\n Number of outputs.\n\n out_activation_ : str\n Name of the output activation function.\n\n See Also\n --------\n BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM).\n MLPClassifier : Multi-layer Perceptron classifier.\n sklearn.linear_model.SGDRegressor : Linear model fitted by minimizing\n a regularized empirical loss with SGD.\n\n Notes\n -----\n MLPRegressor trains iteratively since at each time step\n the partial derivatives of the loss function with respect to the model\n parameters are computed to update the parameters.\n\n It can also have a regularization term added to the loss function\n that shrinks model parameters to prevent overfitting.\n\n This implementation works with data represented as dense and sparse numpy\n arrays of floating point values.\n\n References\n ----------\n Hinton, Geoffrey E.\n \"Connectionist learning procedures.\" Artificial intelligence 40.1\n (1989): 185-234.\n\n Glorot, Xavier, and Yoshua Bengio. \"Understanding the difficulty of\n training deep feedforward neural networks.\" International Conference\n on Artificial Intelligence and Statistics. 2010.\n\n He, Kaiming, et al. \"Delving deep into rectifiers: Surpassing human-level\n performance on imagenet classification.\" arXiv preprint\n arXiv:1502.01852 (2015).\n\n Kingma, Diederik, and Jimmy Ba. \"Adam: A method for stochastic\n optimization.\" arXiv preprint arXiv:1412.6980 (2014).\n\n Examples\n --------\n >>> from sklearn.neural_network import MLPRegressor\n >>> from sklearn.datasets import make_regression\n >>> from sklearn.model_selection import train_test_split\n >>> X, y = make_regression(n_samples=200, random_state=1)\n >>> X_train, X_test, y_train, y_test = train_test_split(X, y,\n ... random_state=1)\n >>> regr = MLPRegressor(random_state=1, max_iter=500).fit(X_train, y_train)\n >>> regr.predict(X_test[:2])\n array([-0.9..., -7.1...])\n >>> regr.score(X_test, y_test)\n 0.4...\n \"\"\"\n\n def __init__(\n self,\n hidden_layer_sizes=(100,),\n activation=\"relu\",\n *,\n solver=\"adam\",\n alpha=0.0001,\n batch_size=\"auto\",\n learning_rate=\"constant\",\n learning_rate_init=0.001,\n power_t=0.5,\n max_iter=200,\n shuffle=True,\n random_state=None,\n tol=1e-4,\n verbose=False,\n warm_start=False,\n momentum=0.9,\n nesterovs_momentum=True,\n early_stopping=False,\n validation_fraction=0.1,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-8,\n n_iter_no_change=10,\n max_fun=15000,\n ):\n super().__init__(\n hidden_layer_sizes=hidden_layer_sizes,\n activation=activation,\n solver=solver,\n alpha=alpha,\n batch_size=batch_size,\n learning_rate=learning_rate,\n learning_rate_init=learning_rate_init,\n power_t=power_t,\n max_iter=max_iter,\n loss=\"squared_error\",\n shuffle=shuffle,\n random_state=random_state,\n tol=tol,\n verbose=verbose,\n warm_start=warm_start,\n momentum=momentum,\n nesterovs_momentum=nesterovs_momentum,\n early_stopping=early_stopping,\n validation_fraction=validation_fraction,\n beta_1=beta_1,\n beta_2=beta_2,\n epsilon=epsilon,\n n_iter_no_change=n_iter_no_change,\n max_fun=max_fun,\n )\n\n def predict(self, X):\n \"\"\"Predict using the multi-layer perceptron model.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n\n Returns\n -------\n y : ndarray of shape (n_samples, n_outputs)\n The predicted values.\n \"\"\"\n check_is_fitted(self)\n y_pred = self._forward_pass_fast(X)\n if y_pred.shape[1] == 1:\n return y_pred.ravel()\n return y_pred\n\n def _validate_input(self, X, y, incremental, reset):\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=[\"csr\", \"csc\"],\n multi_output=True,\n y_numeric=True,\n dtype=(np.float64, np.float32),\n reset=reset,\n )\n if y.ndim == 2 and y.shape[1] == 1:\n y = column_or_1d(y, warn=True)\n return X, y\n"
] |
[
[
"numpy.dot",
"scipy.linalg.svd",
"numpy.sqrt",
"scipy.fftpack.fft",
"numpy.zeros_like",
"numpy.hstack",
"scipy.sparse.issparse",
"numpy.sin",
"numpy.zeros",
"numpy.log",
"scipy.fftpack.ifft",
"numpy.cosh",
"scipy.sparse.csr_matrix",
"numpy.tan",
"scipy.sparse.hstack",
"numpy.maximum",
"numpy.cos",
"numpy.ones",
"numpy.prod"
],
[
"numpy.dot",
"numpy.log",
"numpy.sqrt",
"numpy.clip",
"numpy.reshape",
"numpy.arange",
"numpy.vstack",
"numpy.setdiff1d",
"numpy.mean",
"numpy.array",
"numpy.empty"
]
] |
mpariente/OrdNMF
|
[
"fc038656f2881ef129cf3eba0c8f91380f480cb4"
] |
[
"model/dcPF/dcpf.py"
] |
[
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: ogouvert\n\nVariational Inference algorithm for Discrete Compound Poisson Factorization (DCPF)\n\n- DCPF MODEL:\nW ~ Gamma(aphaW,betaW) ## UxK (size of W)\nH ~ Gamma(aphaH,betaH) ## IxK\nC ~ Poisson(t*W*H) ## UxIxK \nN = sum(C) ## UxI\nY ~ ED(\\theta, n*\\kappa) ## UxI\n\n- VARIATIONAL INFERENCE:\np(W,H,C,N) \\approx q(C|N)q(N)q(W)q(H)\nwhere:\n q(W) = Gamma()\n q(H) = Gamma()\n q(C|N) = Mult()\n q(N) = ? depends on the choice of the EDM, \n see: dcpf_Log, dcpf_ZTP, dcpf_Geo, dcpf_sNB\n\"\"\"\n\nimport numpy as np\nimport scipy.special as special\nimport scipy.sparse as sparse\nimport os\nimport time\nimport cPickle as pickle\nimport sys\n\nclass dcpf():\n def __init__(self, K, \n t=1.,\n alphaW=1., alphaH=1., betaW=1., betaH=1.):\n \"\"\"\n K (int) - number of latent factors\n t (float, >0) - hyperparameter \n alphaW (float, >0) - shape parameter of the prior of W\n alphaH (float, >0) - shape parameter of the prior of H\n betaW (float, >0) - rate parameter of the prior of W\n betaH (float, >0) - rate parameter of the prior of H\n \"\"\"\n self.K = K\n self.t = t\n self.alphaW = alphaW\n self.alphaH = alphaH\n self.betaW = betaW\n self.betaH = betaH\n self.score={}\n # Save arguments\n saved_args_init = locals()\n saved_args_init.pop('self')\n self.saved_args_init = saved_args_init\n \n def fit(self,Y,\n seed=None, \n opt_hyper=[], \n precision=10**(-5), max_iter=10**5, min_iter=0,\n verbose=False,\n save=True, save_dir='', prefix=None, suffix=None):\n \"\"\"\n ------- INPUT VARIABLES -------\n Y (sparse matrix of size UxI) - Observed data\n \n ------- OPTIONAL VARIABLES -------\n seed (int)\n opt_hyper (list of float)\n 't' - update of the hyper-parameter t\n 'beta' - update of the scale parameters of the gamma prior of W and H\n betaW of size U, betaH of size I\n 'p' - update of the parameters of the element distribution (EDM)\n precision (float) - stopping criterion on the ELBO\n max_iter (int) - maximum iteration number\n min_iter (int) - minimum iteration number \n save (bool) - Saving the final class object\n save_dir (str) - Path of the saved file\n prefix, suffix (str) - prefix and suffix to use in the name of the saved file\n \n ------- SAVED VARIABLES -------\n Ew, Elogw : Expectations: Ew = E[W] and Elogw = E[log(W)]\n Eh, Elogh : idem for variable H\n En : Expectation of the number of listening sessions En = E[N]\n Elbo : Evolution of the ELBO\n \"\"\"\n self.seed = seed\n np.random.seed(seed)\n self.opt_hyper = opt_hyper\n self.verbose = verbose\n self.precision = precision\n self.save = save\n self.save_dir = save_dir\n self.filename = self.create_filename(prefix, suffix)\n # Save arguments\n saved_args_fit = locals()\n saved_args_fit.pop('self')\n saved_args_fit.pop('Y')\n self.saved_args_fit = saved_args_fit\n # Timer\n start_time = time.time()\n \n self.stirling_matrix(Y)\n \n # INITIALIZATION \n U,I = Y.shape\n s_y = Y.sum()\n Ew = np.random.gamma(1.,1.,(U,self.K))\n Eh = np.random.gamma(1.,1.,(I,self.K))\n s_wh = np.dot(np.sum(Ew,0,keepdims=True),np.sum(Eh,0,keepdims=True).T)[0,0]\n Elogw = np.log(Ew)\n Elogh = np.log(Eh)\n # Local\n en, Ec_sum_i, Ec_sum_u, elboN = self.q_N_Mult(Y,np.exp(Elogw),np.exp(Elogh))\n s_en = en.sum()\n # Elbo\n self.Elbo = [-float(\"inf\")]\n \n # ITERATIONS\n for n in range(max_iter):\n # Timer\n if verbose:\n print('ITERATION #%d' % n)\n start_t = _writeline_and_time('\\tUpdates...')\n # HYPER PARAMETERS\n if np.isin('t',opt_hyper):\n self.t = s_en / float(s_wh)\n if np.isin('beta',opt_hyper):\n self.betaW = self.alphaW/Ew.mean(axis=1,keepdims=True)\n self.betaH = self.alphaH/Eh.mean(axis=1,keepdims=True)\n if np.isin('p',opt_hyper):\n self.opt_param_xl(s_en, s_y)\n # GLOBAL VARIATIONAL PARAMETERS \n Ew, Elogw, elboW = q_Gamma(self.alphaW , Ec_sum_i, \n self.betaW, self.t*np.sum(Eh,axis=0))\n Eh, Elogh, elboH = q_Gamma(self.alphaH, Ec_sum_u,\n self.betaH, self.t*np.sum(Ew,axis=0))\n s_wh = np.dot(np.sum(Ew,0,keepdims=True),np.sum(Eh,0,keepdims=True).T)[0,0]\n # LOCAL \n en, Ec_sum_i, Ec_sum_u, elboN = self.q_N_Mult(Y,np.exp(Elogw),np.exp(Elogh))\n s_en = en.sum()\n # ELBO\n elbo = elboN - self.t*s_wh + elboW + elboH\n self.rate = (elbo-self.Elbo[-1])/np.abs(self.Elbo[-1])\n if verbose:\n print('\\r\\tUpdates: time=%.2f'% (time.time() - start_t))\n print('\\tRate:' + str(self.rate))\n if elbo<self.Elbo[-1]:\n self.Elbo.append(elbo) \n raise ValueError('ELBO DECREASING!')\n if np.isnan(elbo):\n raise ValueError('ELBO = NAN')\n elif self.rate<precision and n>=min_iter:\n self.Elbo.append(elbo) \n break\n self.Elbo.append(elbo) \n \n # OUTPUT\n u,i = Y.nonzero()\n self.En = sparse.csr_matrix((en,(u,i)),shape=Y.shape)\n self.Ew = Ew.copy()\n self.Eh = Eh.copy()\n self.Elogw = Elogw.copy()\n self.Elogh = Elogh.copy()\n self.duration = time.time()-start_time\n # Save\n if self.save:\n self.save_model()\n \n def stirling_matrix(self,Y):\n pass\n \n def q_N_Mult(self,Y,W,H):\n \"\"\" \n q(C,N) = q(N)q(C|N)\n q(C|N) = Multinomial\n q(N) depends on the choice of the element distribution\n \n OUTPUT:\n en - data of the sparse matrix En\n Ec_sum_i = \\sum_i E[c_{uik}]\n Ec_sum_u = \\sum_u E[c_{uik}]\n \"\"\"\n # Product\n u,i = Y.nonzero()\n s = self.t*np.sum(W[u,:]*H[i,:],1)\n # N ?\n en, elbo = self.c_en(Y,s)\n # Mult\n R = sparse.csr_matrix((en/s,(u,i)),shape=Y.shape) # UxI\n Ec_sum_u = self.t*((R.T).dot(W))*H \n Ec_sum_i = self.t*(R.dot(H))*W \n return en, Ec_sum_i, Ec_sum_u, elbo \n\n def create_filename(self,prefix,suffix):\n if prefix is not None:\n prefix = prefix+'_'\n else:\n prefix = ''\n if suffix is not None:\n suffix = '_'+suffix\n else:\n suffix = ''\n return prefix + self.classname + \\\n '_K%d' % (self.K) + \\\n '_p%.3e' % (self.p) + \\\n '_alpha%.2f_%.2f' %(self.alphaW, self.alphaH) + \\\n '_beta%.2f_%.2f' % (self.betaW, self.betaH) + \\\n '_opthyper_' + '_'.join(sorted(self.opt_hyper)) + \\\n '_precision%.1e' %(self.precision) + \\\n '_seed' + str(self.seed) + suffix\n \n def save_model(self):\n with open(os.path.join(self.save_dir, self.filename), 'wb') as handle:\n pickle.dump(self, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n # ABSTRACT FUNCTIONS\n def c_en(self,Y,s):\n pass\n\n def opt_param_xl(self, s_en, s_y):\n pass\n \n def generate(self):\n pass\n \n def copy_attributes(self,oobj):\n self.__dict__ = oobj.__dict__.copy()\n \ndef stat_gamma(shape,rate):\n \"\"\"\n Statistic of a gamma distribution:\n x \\sim Gamma(shape, rate)\n INPUT: shape and rate parameters\n OUTPUT: E[x], E[log(x)], H the entropy\n \"\"\"\n E = shape/rate\n dig_shape = special.digamma(shape)\n Elog = dig_shape - np.log(rate)\n entropy = shape - np.log(rate) + special.gammaln(shape) + (1-shape)*dig_shape\n return E, Elog, entropy\n \ndef gamma_elbo(shape, rate, Ex, Elogx):\n \"\"\" Part of the ELBO linked to the gamma prior \"\"\"\n return (shape-1)*Elogx -rate*Ex +shape*np.log(rate) -special.gammaln(shape)\n\ndef q_Gamma(shape, _shape, rate, _rate):\n \"\"\" Calculate both statistic and ELBO \"\"\"\n E,Elog,entropy = stat_gamma(shape+_shape, rate+_rate)\n elbo = gamma_elbo(shape, rate, E, Elog)\n elbo = elbo.sum() + entropy.sum()\n return E, Elog, elbo\n \ndef _writeline_and_time(s):\n sys.stdout.write(s)\n sys.stdout.flush()\n return time.time()\n"
] |
[
[
"numpy.log",
"numpy.abs",
"numpy.random.seed",
"numpy.isnan",
"scipy.special.digamma",
"scipy.sparse.csr_matrix",
"scipy.special.gammaln",
"numpy.random.gamma",
"numpy.exp",
"numpy.sum",
"numpy.isin"
]
] |
astrogirl1/montepython_public
|
[
"deaefcf08dd42b4492c00868442afbc25b2fd484"
] |
[
"montepython/analyze.py"
] |
[
"\"\"\"\n.. module:: analyze\n :synopsis: Extract data from chains and produce plots\n\n.. moduleauthor:: Karim Benabed <benabed@iap.fr>\n.. moduleauthor:: Benjamin Audren <benjamin.audren@epfl.ch>\n\nCollection of functions needed to analyze the Markov chains.\n\nThis module defines as well a class :class:`Information`, that stores useful\nquantities, and shortens the argument passing between the functions.\n\n.. note::\n Some of the methods used in this module are directly adapted from the\n `CosmoPmc <http://www.cosmopmc.info>`_ code from Kilbinger et. al.\n\n\"\"\"\nfrom __future__ import print_function\nimport os\nimport math\nimport numpy as np\nfrom itertools import count\n# The root plotting module, to change options like font sizes, etc...\nimport matplotlib\n# The following line suppresses the need for an X server\nmatplotlib.use(\"Agg\")\n# Module for handling display\nimport matplotlib.pyplot as plt\n# Module to handle warnings from matplotlib\nimport warnings\nimport importlib\nimport io_mp\ntry:\n from itertools import ifilterfalse as py_filterfalse\nexcept ImportError:\n from itertools import filterfalse as py_filterfalse\ntry:\n from itertools import ifilter as py_filter\nexcept ImportError:\n from builtins import filter as py_filter\n\nimport scipy.ndimage\nimport scipy.special\nimport numpy.linalg as la\nimport sys\nfrom io_mp import dictitems,dictvalues,dictkeys\n\n# Defined to remove the burnin for all the points that were produced before the\n# first time where -log-likelihood <= min-minus-log-likelihood+LOG_LKL_CUTOFF\n#### Change the following line for MultiNest to 1e300\n#### as we do not want to remove burn-in\nLOG_LKL_CUTOFF = 3\n# LOG_LKL_CUTOFF = 1e300\n\nNUM_COLORS = 6\n\n# Python 2.x - 3.x compatibility: Always use more efficient range function\ntry:\n xrange\nexcept NameError:\n xrange = range\n\n\ndef analyze(command_line):\n \"\"\"\n Main function, does the entire analysis.\n\n It calls in turn all the other routines from this module. To limit the\n arguments of each function to a reasonnable size, a :class:`Information`\n instance is used. This instance is initialized in this function, then\n appended by the other routines.\n\n \"\"\"\n # Check if the scipy module has the interpolate method correctly\n # installed (should be the case on every linux distribution with\n # standard numpy)\n try:\n from scipy.interpolate import interp1d\n Information.has_interpolate_module = True\n except ImportError:\n Information.has_interpolate_module = False\n warnings.warn(\n 'No cubic interpolation done (no interpolate method found ' +\n 'in scipy), only linear')\n\n # Determine how many different folders are asked through the 'info'\n # command, and create as many Information instances\n files = separate_files(command_line.files)\n\n # Create an instance of the Information class for each subgroup found in\n # the previous function. They will each hold all relevant information, and\n # be used as a compact way of exchanging information between functions\n information_instances = []\n for item in files:\n info = Information(command_line)\n information_instances.append(info)\n\n # Prepare the files, according to the case, load the log.param, and\n # prepare the output (plots folder, .covmat, .info and .log files).\n # After this step, info.files will contain all chains.\n status = prepare(item, info)\n # If the preparation step generated new files (for instance,\n # translating from NS or CH to Markov Chains) this routine should stop\n # now.\n if not status:\n return\n\n # Compute the mean, maximum of likelihood, 1-sigma variance for this\n # main folder. This will create the info.chain object, which contains\n # all the points computed stacked in one big array.\n convergence(info)\n\n # check if analyze() is called directly by the user, or by the mcmc loop during an updating phase\n try:\n # command_line.update is defined when called by the mcmc loop\n command_line.update\n except:\n # in case it was not defined (i.e. when analyze() is called directly by user), set it to False\n command_line.update = 0\n # check if analyze() is called directly by the user, or by the mcmc loop at the start of an adaptive run\n try:\n # command_line.adaptive is defined when called by the mcmc loop\n command_line.adaptive\n except:\n # in case it was not defined (i.e. when analyze() is called directly by user), set it to False\n command_line.adaptive = 0\n\n # compute covariance matrix, except when we are in update mode and convergence is too bad or good enough\n # or if we are in adaptive mode and only want a first guess for the covmat\n if command_line.update and (np.amax(info.R) > 3. or np.amax(info.R) < 0.4 or np.isnan(np.sum(info.R))) and not command_line.adaptive:\n print('--> Not computing covariance matrix')\n else:\n try:\n if command_line.want_covmat:\n print('--> Computing covariance matrix')\n info.covar = compute_covariance_matrix(info)\n # Writing it out in name_of_folder.covmat\n io_mp.write_covariance_matrix(\n info.covar, info.backup_names, info.cov_path)\n except:\n print('--> Computing covariance matrix failed')\n pass\n\n # Store an array, sorted_indices, containing the list of indices\n # corresponding to the line with the highest likelihood as the first\n # element, and then as decreasing likelihood\n info.sorted_indices = info.chain[:, 1].argsort(0)\n\n # Writing the best-fit model in name_of_folder.bestfit\n bestfit_line = [elem*info.scales[i, i] for i, elem in\n enumerate(info.chain[info.sorted_indices[0], 2:])]\n io_mp.write_bestfit_file(bestfit_line, info.backup_names,\n info.best_fit_path)\n\n # Overwrite center of Fisher matrix from log.param with the bestfit\n # from the last set of chains provided\n # DEBUG: This doesn't plot the first parameter (omega_b), possibly\n # because it's re-scaled (since it's the only one that is rescaled\n # and the rest are plotted)?\n if command_line.center_fisher:\n for index, elem in enumerate(info.ref_names):\n info.centers[index] = bestfit_line[index]/info.scales[index, index]\n\n if not command_line.minimal:\n # Computing 1,2 and 3-sigma errors, and plot. This will create the\n # triangle and 1d plot by default.\n compute_posterior(information_instances)\n\n print('--> Writing .info and .tex files')\n for info in information_instances:\n info.write_information_files()\n\n # when called by MCMC in update mode, return R values so that they can be written for information in the chains\n if command_line.update:\n return info.R\n\ndef prepare(files, info):\n \"\"\"\n Scan the whole input folder, and include all chains in it.\n\n Since you can decide to analyze some file(s), or a complete folder, this\n function first needs to separate between the two cases.\n\n .. warning::\n If someday you change the way the chains are named, remember to change\n here too, because this routine assumes the chains have a double\n underscore in their names.\n\n .. note::\n Only files ending with .txt will be selected, to keep compatibility\n with CosmoMC format\n\n .. note::\n New in version 2.0.0: if you ask to analyze a MultiNest\n sub-folder (i.e. something that ends in `NS` with capital letters), the\n analyze module will translate the output from MultiNest to\n standard chains for Monte Python, and stops. You can then run the\n `-- info` flag on the whole folder. **This procedure is not necessary\n if the run was complete, but only if the MultiNest run was killed\n before completion**.\n\n Parameters\n ----------\n files : list\n list of potentially only one element, containing the files to analyze.\n This can be only one file, or the encompassing folder, files\n info : Information instance\n Used to store the result\n\n \"\"\"\n # First test if the folder is a MultiNest, PolyChord or CosmoHammer folder.\n # If so, call the module's own routine through the clean conversion\n # function, which will translate the output of this other sampling into\n # MCMC chains that can then be analyzed.\n modules = ['MultiNest', 'PolyChord', 'cosmo_hammer']\n tags = ['NS', 'PC', 'CH']\n for module_name, tag in zip(modules, tags):\n action_done = clean_conversion(module_name, tag, files[0])\n if action_done:\n return False\n\n # If the input command was an entire folder, then grab everything in it.\n # Too small files (below 600 octets) and subfolders are automatically\n # removed.\n folder, files, basename = recover_folder_and_files(files)\n\n info.files = files\n info.folder = folder\n info.basename = basename\n\n # Check if the log.param file exists\n parameter_file_path = os.path.join(folder, 'log.param')\n if os.path.isfile(parameter_file_path):\n if os.path.getsize(parameter_file_path) == 0:\n raise io_mp.AnalyzeError(\n \"The log param file %s \" % os.path.join(folder, 'log.param') +\n \"seems empty\")\n else:\n raise io_mp.AnalyzeError(\n \"The log param file %s \" % os.path.join(folder, 'log.param') +\n \"is missing in the analyzed folder?\")\n\n # If the folder has no subdirectory, then go for a simple infoname,\n # otherwise, call it with the last name\n basename = (os.path.basename(folder) if os.path.basename(folder) != '.'\n else os.path.basename(os.path.abspath(\n os.path.join(folder, '..'))))\n\n info.v_info_path = os.path.join(folder, basename+'.v_info')\n info.h_info_path = os.path.join(folder, basename+'.h_info')\n info.tex_path = os.path.join(folder, basename+'.tex')\n info.cov_path = os.path.join(folder, basename+'.covmat')\n info.log_path = os.path.join(folder, basename+'.log')\n info.best_fit_path = os.path.join(folder, basename+'.bestfit')\n info.param_path = parameter_file_path\n\n return True\n\n\ndef convergence(info):\n \"\"\"\n Compute convergence for the desired chains, using Gelman-Rubin diagnostic\n\n Chains have been stored in the info instance of :class:`Information`. Note\n that the G-R diagnostic can be computed for a single chain, albeit it will\n most probably give absurd results. To do so, it separates the chain into\n three subchains.\n\n \"\"\"\n # Recovering parameter names and scales, creating tex names,\n extract_parameter_names(info)\n\n # Circle through all files to find the global maximum of likelihood\n #print('--> Finding global maximum of likelihood')\n find_maximum_of_likelihood(info)\n\n # Restarting the circling through files, this time removing the burnin,\n # given the maximum of likelihood previously found and the global variable\n # LOG_LKL_CUTOFF. spam now contains all the accepted points that were\n # explored once the chain moved within min_minus_lkl - LOG_LKL_CUTOFF.\n # If the user asks for a keep_fraction <1, this is also the place where\n # a fraction (1-keep_fraction) is removed at the beginning of each chain.\n #print('--> Removing burn-in')\n spam = remove_bad_points(info)\n\n # Re-Map the given parameters\n info.remap_parameters(spam)\n\n # Now that the number of parameters is known\n # (and updated from the remap_parameters)\n # the array containing bounds can be initialised\n info.bounds = np.zeros((len(info.ref_names), len(info.levels), 2))\n\n # Now that the list spam contains all the different chains removed of\n # their respective burn-in, proceed to the convergence computation\n\n # 2D arrays for mean and var, one column will contain the total (over\n # all chains) mean (resp. variance), and each other column the\n # respective chain mean (resp. chain variance). R only contains the\n # values for each parameter. Therefore, mean and var will have len(spam)+1\n # as a first dimension\n mean = np.zeros((len(spam)+1, info.number_parameters))\n var = np.zeros((len(spam)+1, info.number_parameters))\n R = np.zeros(info.number_parameters)\n\n # Store the total number of points, and the total in each chain\n total = np.zeros(len(spam)+1)\n for j in xrange(len(spam)):\n total[j+1] = spam[j][:, 0].sum()\n total[0] = total[1:].sum()\n\n # Compute mean and variance for each chain\n print('--> Computing mean values')\n compute_mean(mean, spam, total)\n\n print('--> Computing variance')\n compute_variance(var, mean, spam, total)\n\n print('--> Computing convergence criterium (Gelman-Rubin)')\n # Gelman Rubin Diagnostic:\n # Computes a quantity linked to the ratio of the mean of the variances of\n # the different chains (within), and the variance of the means (between)\n # Note: This is not strictly speaking the Gelman Rubin test, defined for\n # same-length MC chains. Our quantity is defined without the square root,\n # which should not change much the result: a small sqrt(R) will still be a\n # small R. The same convention is used in CosmoMC, except for the weighted\n # average: we decided to do the average taking into account that longer\n # chains should count more\n within = 0\n between = 0\n for i in xrange(np.shape(mean)[1]):\n for j in xrange(len(spam)):\n within += total[j+1]*var[j+1, i]\n between += total[j+1]*(mean[j+1, i]-mean[0, i])**2\n within /= total[0]\n between /= (total[0]-1)\n\n R[i] = between/within\n if i == 0:\n print(' -> R-1 is %.6f' % R[i], '\\tfor ', info.ref_names[i])\n else:\n print(' %.6f' % R[i], '\\tfor ', info.ref_names[i])\n\n # Log finally the total number of steps, and absolute loglikelihood\n with open(info.log_path, 'a') as log:\n log.write(\"--> Total number of steps: %d\\n\" % (\n info.steps))\n log.write(\"--> Total number of accepted steps: %d\\n\" % (\n info.accepted_steps))\n log.write(\"--> Minimum of -logLike : %.2f\" % (\n info.min_minus_lkl))\n\n # Store the remaining members in the info instance, for further writing to\n # files, storing only the mean and total of all the chains taken together\n info.mean = mean[0]\n info.R = R\n info.total = total[0]\n\n # Create the main chain, which consists in all elements of spam\n # put together. This will serve for the plotting.\n info.chain = np.vstack(spam)\n\ndef compute_posterior(information_instances):\n \"\"\"\n computes the marginalized posterior distributions, and optionnally plots\n them\n\n Parameters\n ----------\n information_instances : list\n list of information objects, initialised on the given folders, or list\n of file, in input. For each of these instance, plot the 1d and 2d\n posterior distribution, depending on the flags stored in the instances,\n comming from command line arguments or read from a file.\n \"\"\"\n # For convenience, store as `conf` the first element of the list\n # information_instances, since it will be called often to check for\n # configuration parameters\n conf = information_instances[0]\n\n # Pre configuration of the output, note that changes to the font size\n # will occur later on as well, to obtain a nice scaling.\n matplotlib.rc('text', usetex=True)\n matplotlib.rc('font', size=11)\n matplotlib.rc('xtick', labelsize='8')\n matplotlib.rc('ytick', labelsize='8')\n\n # Recover max and min values for each instance, defining the a priori place\n # of ticks (in case of a comparison, this should change)\n for info in information_instances:\n info.define_ticks()\n # If plots/ folder in output folder does not exist, create it\n if os.path.isdir(os.path.join(info.folder, 'plots')) is False:\n os.mkdir(os.path.join(info.folder, 'plots'))\n\n # Determine the total number of parameters to plot, based on the list\n # without duplicates of the plotted parameters of all information instances\n plotted_parameters = []\n # For printing not in latex\n ref_names = []\n for info in information_instances:\n for index, name in enumerate(info.plotted_parameters):\n if name not in plotted_parameters:\n plotted_parameters.append(name)\n ref_names.append(info.ref_names[index])\n\n if len(plotted_parameters) == 0:\n raise io_mp.AnalyzeError(\n \"You provided no parameters to analyze, probably by selecting\"\n \" wrong parameters names in the '--extra' file.\")\n # Find the appropriate number of columns and lines for the 1d posterior\n # plot\n if conf.num_columns_1d == None:\n num_columns = int(round(math.sqrt(len(plotted_parameters))))\n else:\n num_columns = conf.num_columns_1d\n num_lines = int(math.ceil(len(plotted_parameters)*1.0/num_columns))\n\n # For special needs, you can impose here a different number of columns and lines in the 1d plot\n # Here is a commented example:\n # if (len(plotted_parameters) == 10):\n # num_columns = 5\n # num_lines = 2\n\n # Create the figures\n # which will be 3*3 inches per subplot, quickly growing!\n if conf.plot:\n fig1d = plt.figure(num=1, figsize=(\n 3*num_columns,\n 3*num_lines), dpi=80)\n if conf.plot_2d:\n if conf.plot_diag:\n fig2d = plt.figure(num=2, figsize=(\n 3*len(plotted_parameters),\n 3*len(plotted_parameters)), dpi=80)\n else:\n fig2d = plt.figure(num=2, figsize=(\n 3*(len(plotted_parameters)-1),\n 3*(len(plotted_parameters)-1)), dpi=80)\n\n # Create the name of the files, concatenating the basenames with\n # underscores.\n file_name = \"_\".join(\n [info.basename for info in information_instances])\n\n\n # JL: READ HERE INVERSE FISHER\n if info.plot_fisher:\n try:\n # read inv_fisher file\n file_name = os.path.join(info.folder, 'inv_fisher.mat')\n n=0\n with open(file_name, 'r') as f:\n inv_fisher = np.zeros((len(info.ref_names), len(info.ref_names)), 'float64')\n for line in f:\n if line.find('#') != -1:\n fisher_num_param = len(line.split())-1\n fisher_indices = np.zeros(fisher_num_param, 'int')\n for i in range(fisher_num_param):\n fisher_name = line.split()[i+1].replace(',', '')\n try:\n fisher_indices[i] = info.ref_names.index(fisher_name)\n print('Read fisher matrix entry for parameter ',fisher_name)\n except:\n print('Input fisher matrix contained unknown parameter ',fisher_name)\n fisher_indices[i] = -1\n else:\n if fisher_indices[n] >= 0:\n for m in range(fisher_num_param):\n if fisher_indices[m] >= 0:\n inv_fisher[fisher_indices[n],fisher_indices[m]]=line.split()[m]\n n += 1\n #print('Read Fisher matrix:')\n #print('param center scale (Fii)^1/2 (Fii)^-1/2')\n #for i in range(len(info.ref_names)):\n # if fisher[i,i] != 0.:\n # print(info.ref_names[i],info.centers[i],info.scales[i,i],math.sqrt(fisher[i,i]),1./math.sqrt(fisher[i,i]))\n # else:\n # print(info.ref_names[i],info.centers[i],' ---')\n except Warning:\n warnings.warn(\"Did not find inv_fisher file %s\" % file_name)\n\n # Loop over all the plotted parameters\n # There will be two indices at all time, the one running over the plotted\n # parameters, `index`, and the one corresponding to the actual column in\n # the actual file, `native_index`. For instance, if you try to plot only\n # two columns of a several columns file, index will vary from 0 to 1, but\n # the corresponding native indices might be anything.\n # Obviously, since plotted parameters contain potentially names not\n # contained in some files (in case of a comparison), native index might be\n # undefined.\n # Defined the legends object, which will store the plot style, to display\n # at the level of the figure\n legends = [None for _ in range(len(information_instances))]\n if not conf.legendnames:\n legend_names = [info.basename.replace('_', ' ')\n for info in information_instances]\n else:\n legend_names = conf.legendnames\n\n\n if conf.plot_2d and not conf.plot_diag:\n for info in information_instances:\n legends[info.id]=plt.Rectangle((0,0),1,1,fc =info.MP_color_cycle[info.id][1],alpha = info.alphas[info.id],linewidth=0)\n\n print('-----------------------------------------------')\n\n for index, name in enumerate(plotted_parameters):\n\n # Adding the subplots to the respective figures, this will correspond\n # to the diagonal on the triangle plot.\n if conf.plot_2d and conf.plot_diag:\n ax2d = fig2d.add_subplot(\n len(plotted_parameters),\n len(plotted_parameters),\n index*(len(plotted_parameters)+1)+1,\n yticks=[])\n if conf.plot:\n ax1d = fig1d.add_subplot(\n num_lines, num_columns, index+1, yticks=[])\n\n # check for each instance if the name is part of the list of plotted\n # parameters, and if yes, store the native_index. If not, store a flag\n # to ignore any further plotting or computing issues concerning this\n # particular instance.\n for info in information_instances:\n try:\n info.native_index = info.ref_names.index(name)\n info.ignore_param = False\n standard_name = info.backup_names[info.native_index]\n except ValueError:\n info.ignore_param = True\n\n # The limits might have been enforced by the user\n if name in dictkeys(conf.force_limits):\n x_span = conf.force_limits[name][1]-conf.force_limits[name][0]\n tick_min = conf.force_limits[name][0] +0.1*x_span\n tick_max = conf.force_limits[name][1] -0.1*x_span\n # [NS] We want to make sure that if there are boundaries, we don't overshoot them by the force_limits\n # (In force_limits you can only provide the limits up to the 0.1*x_span rescaling)\n bounds = info.boundaries[info.native_index]\n # Left boundary\n if bounds[0] is not None:\n if conf.force_limits[name][0] <= bounds[0]:\n tick_min = bounds[0]\n # Right boundary\n if bounds[-1] is not None:\n if conf.force_limits[name][1] > bounds[-1]:\n tick_max = bounds[-1]\n ticks = np.linspace(tick_min,\n tick_max,\n info.ticknumber)\n for info in information_instances:\n if not info.ignore_param:\n info.x_range[info.native_index] = conf.force_limits[name]\n info.ticks[info.native_index] = ticks\n # otherwise, find them automatically\n else:\n adjust_ticks(name, information_instances)\n\n print(' -> Computing histograms for ', name)\n for info in information_instances:\n if not info.ignore_param:\n\n # 1D posterior normalised to P_max=1 (first step)\n #\n # simply the histogram from the chains, with few bins\n #\n info.hist, info.bin_edges = np.histogram(\n # TB: without posterior_smoothing it can be nice to increase the\n # number of bins here.\n info.chain[:, info.native_index+2], bins=info.bins,\n #info.chain[:, info.native_index+2], bins=2*info.bins,\n weights=info.chain[:, 0], normed=False, density=False)\n info.hist = info.hist/info.hist.max()\n # Correct for temperature\n info.hist = info.hist**conf.temperature\n\n info.bincenters = 0.5*(info.bin_edges[1:]+info.bin_edges[:-1])\n\n # 1D posterior normalised to P_max=1 (second step)\n #\n # returns a histogram still normalised to one, but with a ten times finer sampling;\n # >> first, tries a method with spline interpolation between bin centers and extrapolation at the edges\n # >> if it fails, a simpler and more robust method of linear interpolation between bin centers is used\n # >> if the interpolation module is not installed, this step keeps the same posterior\n #\n info.interp_hist, info.interp_grid = cubic_interpolation(\n info, info.hist, info.bincenters)\n\n # minimum credible interval (method by Jan Hamann). Fails for\n # multimodal histograms\n bounds = minimum_credible_intervals(info)\n info.bounds[info.native_index] = bounds\n\n # plotting\n for info in information_instances:\n if not info.ignore_param:\n\n # 1D posterior normalised to P_max=1 (third step, used only for plotting)\n #\n # apply gaussian smoothing (obsolete - we don't do it anymore since the option --posterior-smoothing\n # was defined, so we commented out this part)\n #\n # factor by which the grid has been made thinner (10 means 10 times more bins)\n interpolation_factor = float(len(info.interp_grid))/float(len(info.bincenters))\n # factor for gaussian smoothing\n sigma = interpolation_factor*info.gaussian_smoothing\n # TB: A nice option when turning off posterior_smoothing is to turn on the following\n # two lines of code\n # smooth\n #smoothed_interp_hist = scipy.ndimage.filters.gaussian_filter(info.interp_hist,sigma)\n # re-normalised\n #smoothed_interp_hist = smoothed_interp_hist/smoothed_interp_hist.max()\n\n if conf.plot_2d and conf.plot_diag:\n\n ##################################################\n # plot 1D posterior in diagonal of triangle plot #\n ##################################################\n plot = ax2d.plot(\n info.interp_grid,\n # TB: if no posterior_smoothing uncomment/recomment the next two lines of code\n # version without gaussian smoothing:\n info.interp_hist,\n # version with gaussian smoothing (commented)\n #smoothed_interp_hist,\n linewidth=info.line_width, ls='-',\n color = info.MP_color_cycle[info.id][1],\n # the [1] picks up the color of the 68% contours\n # with [0] you would get that of the 95% contours\n alpha = info.alphas[info.id])\n\n legends[info.id] = plot[0]\n ax2d.set_xticks(info.ticks[info.native_index])\n if conf.legend_style == 'top':\n ax2d.set_title(\n '%s=$%.{0}g^{{+%.{0}g}}_{{%.{0}g}}$'.format(\n info.decimal) % (\n info.tex_names[info.native_index],\n info.mean[info.native_index],\n info.bounds[info.native_index, 0, -1],\n info.bounds[info.native_index, 0, 0]),\n fontsize=info.fontsize)\n ax2d.set_xticklabels(\n ['%.{0}g'.format(info.decimal) % s\n for s in info.ticks[info.native_index]],\n fontsize=info.ticksize)\n elif conf.legend_style == 'sides':\n # Except for the last 1d plot (bottom line), don't\n # print(ticks)\n if index == len(plotted_parameters)-1:\n ax2d.set_xticklabels(\n ['%.{0}g'.format(info.decimal) % s\n for s in info.ticks[info.native_index]],\n fontsize=info.ticksize)\n ax2d.tick_params('x',direction='inout')\n ax2d.set_xlabel(\n info.tex_names[info.native_index],\n fontsize=info.fontsize)\n else:\n ax2d.set_xticklabels([])\n ax2d.axis([info.x_range[info.native_index][0],\n info.x_range[info.native_index][1],\n 0, 1.05])\n\n if conf.plot:\n if conf.short_title_1d:\n ax1d.set_title(\n '%s'.format(info.decimal) % (\n info.tex_names[info.native_index]),\n fontsize=info.fontsize)\n else:\n # Note the use of double curly brackets {{ }} to produce\n # the desired LaTeX output. This is necessary because the\n # format function would otherwise understand single\n # brackets as fields.\n ax1d.set_title(\n '%s=$%.{0}g^{{+%.{0}g}}_{{%.{0}g}}$'.format(\n info.decimal) % (\n info.tex_names[info.native_index],\n info.mean[info.native_index],\n info.bounds[info.native_index, 0, -1],\n info.bounds[info.native_index, 0, 0]),\n fontsize=info.fontsize)\n\n ax1d.set_xticks(info.ticks[info.native_index])\n ax1d.set_xticklabels(\n ['%.{0}g'.format(info.decimal) % s\n for s in info.ticks[info.native_index]],\n fontsize=info.ticksize)\n ax1d.axis([info.x_range[info.native_index][0],\n info.x_range[info.native_index][1],\n 0, 1.05])\n\n # Execute some customisation scripts for the 1d plots\n if (info.custom1d != []):\n for elem in info.custom1d:\n exec(open('plot_files/'+elem).read())\n\n ##################################################\n # plot 1D posterior in 1D plot #\n ##################################################\n ax1d.plot(\n info.interp_grid,\n # TB: if no posterior_smoothing uncomment/recomment the next two lines of code\n # 1d posterior without gaussian filter:\n info.interp_hist,\n # gaussian filtered 1d posterior (commented):\n #smoothed_interp_hist,\n # raw 1d posterior:\n #info.interp_hist,\n lw=info.line_width, ls='-',\n color = info.MP_color_cycle[info.id][1],\n # the [1] picks up the color of the 68% contours\n # with [0] you would get that of the 95% contours\n alpha = info.alphas[info.id])\n # uncomment if you want to see the raw points from the histogram\n # (to check whether the inteprolation and smoothing generated artefacts)\n #ax1d.plot(\n # info.bincenters,\n # info.hist,\n # 'ro')\n\n if conf.mean_likelihood:\n for info in information_instances:\n if not info.ignore_param:\n try:\n\n # 1D mean likelihood normalised to P_max=1 (first step)\n #\n # simply the histogram from the chains, weighted by mutiplicity*likelihood\n #\n lkl_mean, _ = np.histogram(\n info.chain[:, info.native_index+2],\n bins=info.bin_edges,\n normed=False,\n weights=np.exp(\n conf.min_minus_lkl-info.chain[:, 1])*info.chain[:, 0])\n lkl_mean /= lkl_mean.max()\n\n # 1D mean likelihood normalised to P_max=1 (second step)\n #\n # returns a histogram still normalised to one, but with a ten times finer sampling;\n # >> first, tries a method with spline interpolation between bin centers and extrapolation at the edges\n # >> if it fails, a simpler and more robust method of linear interpolation between bin centers is used\n # >> if the interpolation module is not installed, this step keeps the same posterior\n #\n interp_lkl_mean, interp_grid = cubic_interpolation(\n info, lkl_mean, info.bincenters)\n\n # 1D mean likelihood normalised to P_max=1 (third step, used only for plotting)\n #\n # apply gaussian smoothing (obsolete - we don't do it anymore since the option --posterior-smoothing\n # was defined, so we commented out this part)\n #\n # TB: if no posterior_smoothing uncomment the next two lines of code\n # smooth\n #smoothed_interp_lkl_mean = scipy.ndimage.filters.gaussian_filter(interp_lkl_mean,sigma)\n # re-normalised\n #smoothed_interp_lkl_mean = smoothed_interp_lkl_mean/smoothed_interp_lkl_mean.max()\n\n # Execute some customisation scripts for the 1d plots\n if (info.custom1d != []):\n for elem in info.custom1d:\n exec(open('plot_files/'+elem).read())\n\n ########################################################\n # plot 1D mean likelihood in diagonal of triangle plot #\n ########################################################\n if conf.plot_2d and conf.plot_diag:\n # raw mean likelihoods:\n #ax2d.plot(info.bincenter, lkl_mean,\n # ls='--', lw=conf.line_width,\n # color = info.MP_color_cycle[info.id][1],\n # alpha = info.alphas[info.id])\n # smoothed and interpolated mean likelihoods:\n ax2d.plot(interp_grid,\n # TB: if no posterior_smoothing uncomment/recomment the next two lines of code\n # version without gaussian smoothing:\n interp_lkl_mean,\n # version with gaussian smoothing (commented)\n #smoothed_interp_lkl_mean,\n ls='--', lw=conf.line_width,\n color = info.MP_color_cycle[info.id][1],\n alpha = info.alphas[info.id])\n\n ########################################################\n # plot 1D mean likelihood in 1D plot #\n ########################################################\n if conf.plot:\n # raw mean likelihoods:\n #ax1d.plot(info.bincenters, lkl_mean,\n # ls='--', lw=conf.line_width,\n # color = info.MP_color_cycle[info.id][1],\n # alpha = info.alphas[info.id])\n # smoothed and interpolated mean likelihoods:\n ax1d.plot(interp_grid,\n # TB: if no posterior_smoothing uncomment/recomment the next two lines of code\n # version without gaussian smoothing\n interp_lkl_mean,\n # version with gaussian smoothing (commented)\n #smoothed_interp_lkl_mean,\n ls='--', lw=conf.line_width,\n color = info.MP_color_cycle[info.id][1],\n alpha = info.alphas[info.id])\n\n except:\n sys.stdout.write('could not find likelihood contour for ')\n print(info.ref_parameters[info.native_index])\n\n if conf.subplot is True:\n if conf.plot_2d and conf.plot_diag:\n extent2d = ax2d.get_window_extent().transformed(\n fig2d.dpi_scale_trans.inverted())\n fig2d.savefig(os.path.join(\n conf.folder, 'plots', file_name+'.'+conf.extension),\n bbox_inches=extent2d.expanded(1.1, 1.4))\n if conf.plot:\n extent1d = ax1d.get_window_extent().transformed(\n fig1d.dpi_scale_trans.inverted())\n fig1d.savefig(os.path.join(\n conf.folder, 'plots', file_name+'.'+conf.extension),\n bbox_inches=extent1d.expanded(1.1, 1.4))\n # Store the function in a file\n for info in information_instances:\n if not info.ignore_param:\n hist_file_name = os.path.join(\n info.folder, 'plots',\n info.basename+'_%s.hist' % (\n standard_name))\n write_histogram(hist_file_name,\n info.interp_grid, info.interp_hist)\n\n # Now do the rest of the triangle plot\n if conf.plot_2d:\n for second_index in xrange(index):\n second_name = plotted_parameters[second_index]\n for info in information_instances:\n if not info.ignore_param:\n try:\n info.native_second_index = info.ref_names.index(\n plotted_parameters[second_index])\n info.has_second_param = True\n second_standard_name = info.backup_names[\n info.native_second_index]\n except ValueError:\n info.has_second_param = False\n else:\n info.has_second_param = False\n\n if conf.plot_diag:\n ax2dsub = fig2d.add_subplot(\n len(plotted_parameters),\n len(plotted_parameters),\n (index)*len(plotted_parameters)+second_index+1)\n else:\n ax2dsub = fig2d.add_subplot(\n len(plotted_parameters)-1,\n len(plotted_parameters)-1,\n (index-1)*(len(plotted_parameters)-1)+second_index+1)\n\n for info in information_instances:\n if info.has_second_param:\n\n ax2dsub.axis([info.x_range[info.native_second_index][0],\n info.x_range[info.native_second_index][1],\n info.x_range[info.native_index][0],\n info.x_range[info.native_index][1]])\n\n # 2D likelihood (first step)\n #\n # simply the histogram from the chains, with few bins only\n #\n info.n, info.xedges, info.yedges = np.histogram2d(\n info.chain[:, info.native_index+2],\n info.chain[:, info.native_second_index+2],\n weights=info.chain[:, 0],\n bins=(info.bins, info.bins),\n normed=False)\n # Correct for temperature:\n info.n = info.n**conf.temperature\n\n info.extent = [\n info.x_range[info.native_second_index][0],\n info.x_range[info.native_second_index][1],\n info.x_range[info.native_index][0],\n info.x_range[info.native_index][1]]\n info.x_centers = 0.5*(info.xedges[1:]+info.xedges[:-1])\n info.y_centers = 0.5*(info.yedges[1:]+info.yedges[:-1])\n\n # 2D likelihood (second step)\n #\n # like for 1D, interpolate to get a finer grid\n # TODO: we should not only interpolate between bin centers, but also extrapolate between side bin centers and bin edges\n #\n interp_y_centers = scipy.ndimage.zoom(info.y_centers,info.interpolation_smoothing, mode='reflect')\n interp_x_centers = scipy.ndimage.zoom(info.x_centers,info.interpolation_smoothing, mode='reflect')\n interp_likelihood = scipy.ndimage.zoom(info.n,info.interpolation_smoothing, mode='reflect')\n\n # 2D likelihood (third step)\n #\n # gaussian smoothing\n #\n sigma = info.interpolation_smoothing*info.gaussian_smoothing\n interp_smoothed_likelihood = scipy.ndimage.filters.gaussian_filter(interp_likelihood,[sigma,sigma], mode='reflect')\n\n # Execute some customisation scripts for the 2d contour plots\n if (info.custom2d != []):\n for elem in info.custom2d:\n exec(open('plot_files/'+elem).read())\n\n # plotting contours, using the ctr_level method (from Karim\n # Benabed). Note that only the 1 and 2 sigma contours are\n # displayed (due to the line with info.levels[:2])\n try:\n\n ###########################\n # plot 2D filled contours #\n ###########################\n if not info.contours_only:\n contours = ax2dsub.contourf(\n interp_y_centers,\n interp_x_centers,\n interp_smoothed_likelihood,\n extent=info.extent,\n levels=ctr_level(\n interp_smoothed_likelihood,\n info.levels[:2]),\n zorder=4,\n colors = info.MP_color_cycle[info.id],\n alpha=info.alphas[info.id])\n\n # now add a thin darker line\n # around the 95% contour\n ax2dsub.contour(\n interp_y_centers,\n interp_x_centers,\n interp_smoothed_likelihood,\n extent=info.extent,\n levels=ctr_level(\n interp_smoothed_likelihood,\n info.levels[1:2]),\n zorder=4,\n colors = info.MP_color_cycle[info.id][1],\n alpha = info.alphas[info.id],\n linewidths=1)\n\n ###########################\n # plot 2D contours #\n ###########################\n if info.contours_only:\n contours = ax2dsub.contour(\n interp_y_centers,\n interp_x_centers,\n interp_smoothed_likelihood,\n extent=info.extent, levels=ctr_level(\n interp_smoothed_likelihood,\n info.levels[:2]),\n zorder=4,\n colors = info.MP_color_cycle[info.id],\n alpha = info.alphas[info.id],\n linewidths=info.line_width)\n\n except Warning:\n warnings.warn(\n \"The routine could not find the contour of the \" +\n \"'%s-%s' 2d-plot\" % (\n info.plotted_parameters[info.native_index],\n info.plotted_parameters[info.native_second_index]))\n\n # ADDING FISHER CONTOURS\n if info.plot_fisher:\n sub_inv_fisher = np.zeros((2,2), 'float64')\n sub_inv_fisher[0,0] = inv_fisher[info.native_index,info.native_index]/info.scales[info.native_index,info.native_index]/info.scales[info.native_index,info.native_index]\n sub_inv_fisher[1,1] = inv_fisher[info.native_second_index,info.native_second_index]/info.scales[info.native_second_index,info.native_second_index]/info.scales[info.native_second_index,info.native_second_index]\n sub_inv_fisher[0,1] = inv_fisher[info.native_index,info.native_second_index]/info.scales[info.native_index,info.native_index]/info.scales[info.native_second_index,info.native_second_index]\n sub_inv_fisher[1,0] = sub_inv_fisher[0,1]\n if sub_inv_fisher[0,0]*sub_inv_fisher[1,1] != 0.:\n inv_sub_inv_fisher = np.linalg.inv(sub_inv_fisher)\n\n x = scipy.ndimage.zoom(info.x_centers,info.interpolation_smoothing, mode='reflect')\n y = scipy.ndimage.zoom(info.y_centers,info.interpolation_smoothing, mode='reflect')\n\n z = np.zeros((len(x),len(y)), 'float64')\n\n #print(info.ref_names[info.native_index])\n #print(info.scales)\n #print(info.boundaries[info.native_index])\n #print(info.centers[info.native_index])\n\n for ix in range(len(x)):\n dx = (x[ix] - info.centers[info.native_index])\n for iy in range(len(y)):\n dy = (y[iy] - info.centers[info.native_second_index])\n z[ix,iy] = dx*inv_sub_inv_fisher[0,0]*dx + dy*inv_sub_inv_fisher[1,1]*dy + 2.*dx*inv_sub_inv_fisher[0,1]*dy\n\n ax2dsub.contour(y,x,z,\n extent=info.extent,\n levels=[2.3,6.18],\n #levels=[9.30,15.79],\n zorder=4, colors='k')\n\n ax2dsub.set_xticks(info.ticks[info.native_second_index])\n ax2dsub.set_yticks(info.ticks[info.native_index])\n ax2dsub.tick_params('both',direction='inout',top=True,bottom=True,left=True,right=True)\n if index == len(plotted_parameters)-1:\n ax2dsub.set_xticklabels(\n ['%.{0}g'.format(info.decimal) % s for s in\n info.ticks[info.native_second_index]],\n fontsize=info.ticksize)\n if conf.legend_style == 'sides':\n ax2dsub.set_xlabel(\n info.tex_names[info.native_second_index],\n fontsize=info.fontsize)\n else:\n ax2dsub.set_xticklabels([''])\n\n ax2dsub.set_yticks(info.ticks[info.native_index])\n if second_index == 0:\n ax2dsub.set_yticklabels(\n ['%.{0}g'.format(info.decimal) % s for s in\n info.ticks[info.native_index]],\n fontsize=info.ticksize)\n else:\n ax2dsub.set_yticklabels([''])\n\n if conf.legend_style == 'sides':\n if second_index == 0:\n ax2dsub.set_ylabel(\n info.tex_names[info.native_index],\n fontsize=info.fontsize)\n\n if conf.subplot is True:\n # Store the individual 2d plots.\n if conf.plot_2d:\n area = ax2dsub.get_window_extent().transformed(\n fig2d.dpi_scale_trans.inverted())\n # Pad the saved area by 10% in the x-direction and 20% in\n # the y-direction\n fig2d.savefig(os.path.join(\n conf.folder, 'plots',\n file_name+'_2d_%s-%s.%s' % (\n standard_name, second_standard_name,\n conf.extension)),\n bbox_inches=area.expanded(1.4, 1.4))\n\n # store the coordinates of the points for further\n # plotting.\n store_contour_coordinates(\n conf, standard_name, second_standard_name, contours)\n\n for info in information_instances:\n if not info.ignore_param and info.has_second_param:\n info.hist_file_name = os.path.join(\n info.folder, 'plots',\n '{0}_2d_{1}-{2}.hist'.format(\n info.basename,\n standard_name,\n second_standard_name))\n write_histogram_2d(\n info.hist_file_name, info.x_centers, info.y_centers,\n info.extent, info.n)\n\n print('-----------------------------------------------')\n if conf.plot:\n print('--> Saving figures to .{0} files'.format(info.extension))\n plot_name = '-vs-'.join([os.path.split(elem.folder)[-1]\n for elem in information_instances])\n\n if conf.plot_2d:\n # Legend of triangle plot\n if ((conf.plot_legend_2d == None) and (len(legends) > 1)) or (conf.plot_legend_2d == True):\n # Create a virtual subplot in the top right corner,\n # just to be able to anchor the legend nicely\n if conf.plot_diag:\n ax2d = fig2d.add_subplot(\n len(plotted_parameters),\n len(plotted_parameters),\n len(plotted_parameters))\n else:\n ax2d = fig2d.add_subplot(\n len(plotted_parameters)-1,\n len(plotted_parameters)-1,\n len(plotted_parameters)-1)\n ax2d.axis('off')\n try:\n ax2d.legend(legends, legend_names,\n loc='upper right',\n borderaxespad=0.,\n fontsize=info.legendsize)\n except TypeError:\n ax2d.legend(legends, legend_names,\n loc='upper right',\n borderaxespad=0.,\n prop={'fontsize': info.legendsize})\n fig2d.subplots_adjust(wspace=0, hspace=0)\n fig2d.savefig(\n os.path.join(\n conf.folder, 'plots', '{0}_triangle.{1}'.format(\n plot_name, info.extension)),\n bbox_inches='tight')\n # Legend of 1D plot\n if conf.plot:\n if ((conf.plot_legend_1d == None) and (len(legends) > 1)) or (conf.plot_legend_1d == True):\n # no space left: add legend to thr right\n if len(plotted_parameters)<num_columns*num_lines:\n fig1d.legend(legends, legend_names,\n loc= ((num_columns-0.9)/num_columns,0.1/num_columns),\n fontsize=info.legendsize)\n # space left in lower right part: add legend there\n else:\n fig1d.legend(legends, legend_names,\n loc= 'center right',\n bbox_to_anchor = (1.2,0.5),\n fontsize=info.legendsize)\n fig1d.tight_layout()\n fig1d.savefig(\n os.path.join(\n conf.folder, 'plots', '{0}_1d.{1}'.format(\n plot_name, info.extension)),\n bbox_inches='tight')\n\n\ndef ctr_level(histogram2d, lvl, infinite=False):\n \"\"\"\n Extract the contours for the 2d plots (Karim Benabed)\n\n \"\"\"\n\n hist = histogram2d.flatten()*1.\n hist.sort()\n cum_hist = np.cumsum(hist[::-1])\n cum_hist /= cum_hist[-1]\n\n alvl = np.searchsorted(cum_hist, lvl)[::-1]\n clist = [0]+[hist[-i] for i in alvl]+[hist.max()]\n if not infinite:\n return clist[1:]\n return clist\n\ndef minimum_credible_intervals(info):\n \"\"\"\n Extract minimum credible intervals (method from Jan Haman) FIXME\n \"\"\"\n histogram = info.hist\n bincenters = info.bincenters\n levels = info.levels\n\n bounds = np.zeros((len(levels), 2))\n j = 0\n delta = bincenters[1]-bincenters[0]\n left_edge = max(histogram[0] - 0.5*(histogram[1]-histogram[0]), 0.)\n right_edge = max(histogram[-1] + 0.5*(histogram[-1]-histogram[-2]), 0.)\n failed = False\n for level in levels:\n norm = float(\n (np.sum(histogram)-0.5*(histogram[0]+histogram[-1]))*delta)\n norm += 0.25*(left_edge+histogram[0])*delta\n norm += 0.25*(right_edge+histogram[-1])*delta\n water_level_up = np.max(histogram)*1.0\n water_level_down = np.min(histogram)*1.0\n top = 0.\n\n iterations = 0\n while (abs((top/norm)-level) > 0.0001) and not failed:\n top = 0.\n water_level = (water_level_up + water_level_down)/2.\n #ontop = [elem for elem in histogram if elem > water_level]\n indices = [i for i in range(len(histogram))\n if histogram[i] > water_level]\n # check for multimodal posteriors\n if ((indices[-1]-indices[0]+1) != len(indices)):\n warnings.warn(\n \"could not derive minimum credible intervals \" +\n \"for this multimodal posterior\")\n warnings.warn(\n \"please try running longer chains or reducing \" +\n \"the number of bins with --bins BINS (default: 20)\")\n failed = True\n break\n top = (np.sum(histogram[indices]) -\n 0.5*(histogram[indices[0]]+histogram[indices[-1]]))*(delta)\n\n # left\n if indices[0] > 0:\n top += (0.5*(water_level+histogram[indices[0]]) *\n delta*(histogram[indices[0]]-water_level) /\n (histogram[indices[0]]-histogram[indices[0]-1]))\n else:\n if (left_edge > water_level):\n top += 0.25*(left_edge+histogram[indices[0]])*delta\n else:\n top += (0.25*(water_level + histogram[indices[0]]) *\n delta*(histogram[indices[0]]-water_level) /\n (histogram[indices[0]]-left_edge))\n\n # right\n if indices[-1] < (len(histogram)-1):\n top += (0.5*(water_level + histogram[indices[-1]]) *\n delta*(histogram[indices[-1]]-water_level) /\n (histogram[indices[-1]]-histogram[indices[-1]+1]))\n else:\n if (right_edge > water_level):\n top += 0.25*(right_edge+histogram[indices[-1]])*delta\n else:\n top += (0.25*(water_level + histogram[indices[-1]]) *\n delta * (histogram[indices[-1]]-water_level) /\n (histogram[indices[-1]]-right_edge))\n\n if top/norm >= level:\n water_level_down = water_level\n else:\n water_level_up = water_level\n # safeguard, just in case\n iterations += 1\n if (iterations > 1000):\n warnings.warn(\n \"the loop to check for sigma deviations was \" +\n \"taking too long to converge\")\n failed = True\n break\n\n # min\n if failed:\n bounds[j][0] = np.nan\n elif indices[0] > 0:\n bounds[j][0] = bincenters[indices[0]] - delta*(histogram[indices[0]]-water_level)/(histogram[indices[0]]-histogram[indices[0]-1])\n else:\n if (left_edge > water_level):\n bounds[j][0] = bincenters[0]-0.5*delta\n else:\n bounds[j][0] = bincenters[indices[0]] - 0.5*delta*(histogram[indices[0]]-water_level)/(histogram[indices[0]]-left_edge)\n\n # max\n if failed:\n bounds[j][1] = np.nan\n elif indices[-1] < (len(histogram)-1):\n bounds[j][1] = bincenters[indices[-1]] + delta*(histogram[indices[-1]]-water_level)/(histogram[indices[-1]]-histogram[indices[-1]+1])\n else:\n if (right_edge > water_level):\n bounds[j][1] = bincenters[-1]+0.5*delta\n else:\n bounds[j][1] = bincenters[indices[-1]] + \\\n 0.5*delta*(histogram[indices[-1]]-water_level) / \\\n (histogram[indices[-1]]-right_edge)\n\n j += 1\n\n for elem in bounds:\n for j in (0, 1):\n elem[j] -= info.mean[info.native_index]\n return bounds\n\n\ndef write_h(info_file, indices, name, string, quantity, modifiers=None):\n \"\"\"\n Write one horizontal line of output\n\n \"\"\"\n info_file.write('\\n '+name+'\\t: ')\n for i in indices:\n info_file.write(string % quantity[i]+'\\t')\n\n\ndef cubic_interpolation(info, hist, bincenters):\n \"\"\"\n Small routine to accomodate the absence of the interpolate module\n\n \"\"\"\n\n # we start from a try becuase if anything goes wrong, we want to return the raw histogram rather than nothing\n try:\n\n # test that all elements are strictly positive, otherwise we could not take the log, and we must switch to the robust method\n for i,elem in enumerate(hist):\n if elem == 0.:\n hist[i] = 1.e-99\n elif elem <0:\n print(hist[i])\n raise exception()\n\n # One of our methods (using polyfit) does assume that the input histogram has a maximum value of 1.\n # If in a future version this is not guaranteedanymore, we should renormalise it here.\n # This is important for computing weights and thresholds.\n\n # The threshold below which the likelihood will be\n # approximated as zero is hard-codeed here (could become an\n # input parameter but that would not clearly be useful).:\n threshold = 1.e-3\n\n # prepare the interpolation on log(Like):\n ln_hist = np.log(hist)\n\n # define a finer grid on a wider range (assuming that the following method is fine both for inter- and extra-polation)\n left = bincenters[0]-2.5*(bincenters[1]-bincenters[0])\n if (info.boundaries[info.native_index][0] != None):\n if (info.boundaries[info.native_index][0] > left):\n left = info.boundaries[info.native_index][0]\n right = bincenters[-1]+2.5*(bincenters[-1]-bincenters[-2])\n if (info.boundaries[info.native_index][1] != None):\n if (info.boundaries[info.native_index][1] < right):\n right = info.boundaries[info.native_index][1]\n interp_grid = np.linspace(left, right, (len(bincenters)+4)*10+1)\n\n ######################################\n # polynomial fit method (default): #\n #####################################W\n if info.posterior_smoothing >= 2:\n # the points in the histogram with a very low likelihood (i.e. hist[i]<<1 hist is normalised to a maximum of one)\n # have a lot of Poisson noise and are unreliable. However, if we do nothing, they may dominate the outcome of the fitted polynomial.\n # Hence we can:\n # 1) give them less weight (weight = sqrt(hist) seems to work well)\n # 2) cut them at some threshold value and base the fit only on higher points\n # 3) both\n # the one working best seems to be 2). We also wrote 1) below, but copmmented out.\n\n # method 1):\n #f = np.poly1d(np.polyfit(bincenters,ln_hist,info.posterior_smoothing,w=np.sqrt(hist)))\n #interp_hist = f(interp_grid)\n\n # method 2):\n # find index values such that hist is negligble everywhere excepted in hist[sub_indices[0]], hist[sub_indices[-1]]\n sub_indices = [i for i,elem in enumerate(hist) if elem > threshold]\n # The interpolation is done precisely in this range: hist[sub_indices[0]] < x < hist[sub_indices[-1]]\n g = np.poly1d(np.polyfit(bincenters[sub_indices],ln_hist[sub_indices],info.posterior_smoothing)) #,w=np.sqrt(hist[sub_indices])))\n # The extrapolation is done in a range including one more bin on each side, excepted when the boundary is hit\n if (info.boundaries[info.native_index][0] == None):\n extrapolation_range_left = [bincenters[sub_indices[0]] if sub_indices[0] == 0 else bincenters[sub_indices[0]-1]]\n else:\n extrapolation_range_left = [info.boundaries[info.native_index][0] if sub_indices[0] == 0 else bincenters[sub_indices[0]-1]]\n if (info.boundaries[info.native_index][1] == None):\n extrapolation_range_right = [bincenters[sub_indices[-1]] if sub_indices[-1] == len(hist)-1 else bincenters[sub_indices[-1]+1]]\n else:\n extrapolation_range_right = [info.boundaries[info.native_index][1] if sub_indices[-1] == len(hist)-1 else bincenters[sub_indices[-1]+1]]\n # outside of this range, log(L) is brutally set to a negligible value,e, log(1.e-10)\n interp_hist = [g(elem) if (elem > extrapolation_range_left and elem < extrapolation_range_right) else np.log(1.e-10) for elem in interp_grid]\n\n elif info.posterior_smoothing<0:\n raise io_mp.AnalyzeError(\n \"You passed --posterior-smoothing %d, this value is not understood\"%info.posterior_smoothing)\n\n ############################################################\n # other methods: #\n # - linear inter/extra-polation if posterior_smoothing = 0 #\n # - cubic inter/extra-polation if posterior_smoothing = 0 #\n ############################################################\n else:\n\n # try first inter/extra-polation\n try:\n # prepare to interpolate and extrapolate:\n if info.posterior_smoothing == 0:\n f = scipy.interpolate.interp1d(bincenters, ln_hist, kind='linear', fill_value='extrapolate')\n else:\n f = scipy.interpolate.interp1d(bincenters, ln_hist, kind='cubic', fill_value='extrapolate')\n interp_hist = f(interp_grid)\n\n # failure probably caused by old scipy not having the fill_value='extrapolate' argument. Then, only interpoolate.\n except:\n # define a finer grid but not a wider one\n left = bincenters[0]\n if (info.boundaries[info.native_index][0] != None):\n if (info.boundaries[info.native_index][0] > left):\n left = info.boundaries[info.native_index][0]\n right = bincenters[-1]\n if (info.boundaries[info.native_index][1] != None):\n if (info.boundaries[info.native_index][1] < right):\n right = info.boundaries[info.native_index][1]\n interp_grid = np.linspace(left, right, len(bincenters)*10+1)\n # prepare to interpolate only:\n if info.posterior_smoothing == 0:\n f = scipy.interpolate.interp1d(bincenters, ln_hist, kind='linear')\n else:\n f = scipy.interpolate.interp1d(bincenters, ln_hist, kind='cubic')\n interp_hist = f(interp_grid)\n\n # final steps used b y all methods\n\n # go back from ln_Like to Like\n interp_hist = np.exp(interp_hist)\n\n # re-normalise the interpolated curve\n interp_hist = interp_hist / interp_hist.max()\n\n return interp_hist, interp_grid\n\n except:\n # we will end up here if anything went wrong before\n # do nothing (raw histogram)\n warnings.warn(\n \"The 1D posterior could not be processed normally, probably\" +\n \"due to incomplete or obsolete numpy and/or scipy versions.\" +\n \"So the raw histograms will be plotted.\")\n return hist, bincenters\n\ndef write_histogram(hist_file_name, x_centers, hist):\n \"\"\"\n Store the posterior distribution to a file\n\n \"\"\"\n with open(hist_file_name, 'w') as hist_file:\n hist_file.write(\"# 1d posterior distribution\\n\")\n hist_file.write(\"\\n# x_centers\\n\")\n hist_file.write(\", \".join(\n [str(elem) for elem in x_centers])+\"\\n\")\n hist_file.write(\"\\n# Histogram\\n\")\n hist_file.write(\", \".join(\n [str(elem) for elem in hist])+\"\\n\")\n print('wrote ', hist_file_name)\n\n\ndef read_histogram(histogram_path):\n \"\"\"\n Recover a stored 1d posterior\n\n \"\"\"\n with open(histogram_path, 'r') as hist_file:\n for line in hist_file:\n if line:\n if line.find(\"# x_centers\") != -1:\n x_centers = [float(elem) for elem in\n hist_file.next().split(\",\")]\n elif line.find(\"# Histogram\") != -1:\n hist = [float(elem) for elem in\n hist_file.next().split(\",\")]\n x_centers = np.array(x_centers)\n hist = np.array(hist)\n\n return x_centers, hist\n\n\ndef write_histogram_2d(hist_file_name, x_centers, y_centers, extent, hist):\n \"\"\"\n Store the histogram information to a file, to plot it later\n\n \"\"\"\n with open(hist_file_name, 'w') as hist_file:\n hist_file.write(\"# Interpolated histogram\\n\")\n hist_file.write(\"\\n# x_centers\\n\")\n hist_file.write(\", \".join(\n [str(elem) for elem in x_centers])+\"\\n\")\n\n hist_file.write(\"\\n# y_centers\\n\")\n hist_file.write(\", \".join(\n [str(elem) for elem in y_centers])+\"\\n\")\n\n hist_file.write(\"\\n# Extent\\n\")\n hist_file.write(\", \".join(\n [str(elem) for elem in extent])+\"\\n\")\n\n hist_file.write(\"\\n# Histogram\\n\")\n for line in hist:\n hist_file.write(\", \".join(\n [str(elem) for elem in line])+\"\\n\")\n\n\ndef read_histogram_2d(histogram_path):\n \"\"\"\n Read the histogram information that was stored in a file.\n\n To use it, call something like this:\n\n .. code::\n\n x_centers, y_centers, extent, hist = read_histogram_2d_from_file(path)\n fig, ax = plt.subplots()\n ax.contourf(\n y_centers, x_centers, hist, extent=extent,\n levels=ctr_level(hist, [0.68, 0.95]),\n zorder=5, cma=plt.cm.autumn_r)\n plt.show()\n\n \"\"\"\n with open(histogram_path, 'r') as hist_file:\n length = 0\n for line in hist_file:\n if line:\n if line.find(\"# x_centers\") != -1:\n x_centers = [float(elem) for elem in\n hist_file.next().split(\",\")]\n length = len(x_centers)\n elif line.find(\"# y_centers\") != -1:\n y_centers = [float(elem) for elem in\n hist_file.next().split(\",\")]\n elif line.find(\"# Extent\") != -1:\n extent = [float(elem) for elem in\n hist_file.next().split(\",\")]\n elif line.find(\"# Histogram\") != -1:\n hist = []\n for index in range(length):\n hist.append([float(elem) for elem in\n hist_file.next().split(\",\")])\n x_centers = np.array(x_centers)\n y_centers = np.array(y_centers)\n extent = np.array(extent)\n hist = np.array(hist)\n\n return x_centers, y_centers, extent, hist\n\n\ndef clean_conversion(module_name, tag, folder):\n \"\"\"\n Execute the methods \"convert\" from the different sampling algorithms\n\n Returns True if something was made, False otherwise\n \"\"\"\n has_module = False\n subfolder_name = tag+\"_subfolder\"\n try:\n # Don't try to import the wrong (unrequested) module, in case it's not installed\n if not folder.lower().endswith(tag.lower()):\n raise ImportError\n module = importlib.import_module(module_name)\n subfolder = getattr(module, subfolder_name)\n has_module = True\n except ImportError:\n # The module is not installed, the conversion can not take place\n pass\n\n if has_module and os.path.isdir(folder):\n # Remove any potential trailing slash\n folder = os.path.join(\n *[elem for elem in folder.split(os.path.sep) if elem])\n if folder.split(os.path.sep)[-1] == subfolder:\n try:\n getattr(module, 'from_%s_output_to_chains' % tag)(folder)\n except IOError:\n raise io_mp.AnalyzeError(\n \"You asked to analyze a %s folder which \" % tag +\n \"seems to come from an unfinished run, or to be empty \" +\n \"or corrupt. Please make sure the run went smoothly \" +\n \"enough.\")\n warnings.warn(\n \"The content of the %s subfolder has been \" % tag +\n \"translated for Monte Python. Please run an \"\n \"analysis of the entire folder now.\")\n return True\n else:\n return False\n\n\ndef separate_files(files):\n \"\"\"\n Separate the input files in folder\n\n Given all input arguments to the command line files entry, separate them in\n a list of lists, grouping them by folders. The number of identified folders\n will determine the number of information instances to create\n \"\"\"\n final_list = []\n temp = [files[0]]\n folder = (os.path.dirname(files[0]) if os.path.isfile(files[0])\n else files[0])\n if len(files) > 1:\n for elem in files[1:]:\n new_folder = (os.path.dirname(elem) if os.path.isfile(elem)\n else elem)\n if new_folder == folder:\n temp.append(elem)\n else:\n folder = new_folder\n final_list.append(temp)\n temp = [elem]\n final_list.append(temp)\n\n return final_list\n\n\ndef recover_folder_and_files(files):\n \"\"\"\n Distinguish the cases when analyze is called with files or folder\n\n Note that this takes place chronologically after the function\n `separate_files`\"\"\"\n # The following list defines the substring that a chain should contain for\n # the code to recognise it as a proper chain.\n substrings = ['.txt', '__']\n limit = 10\n # If the first element is a folder, grab all chain files inside\n if os.path.isdir(files[0]):\n folder = os.path.normpath(files[0])\n files = [os.path.join(folder, elem) for elem in os.listdir(folder)\n if not os.path.isdir(os.path.join(folder, elem))\n and not os.path.getsize(os.path.join(folder, elem)) < limit\n and all([x in elem for x in substrings])]\n # Otherwise, extract the folder from the chain file-name.\n else:\n # If the name is completely wrong, say it\n if not os.path.exists(files[0]):\n raise io_mp.AnalyzeError(\n \"You provided a non-existant folder/file to analyze\")\n folder = os.path.relpath(\n os.path.dirname(os.path.realpath(files[0])), os.path.curdir)\n files = [os.path.join(folder, elem) for elem in os.listdir(folder)\n if os.path.join(folder, elem) in np.copy(files)\n and not os.path.isdir(os.path.join(folder, elem))\n and not os.path.getsize(os.path.join(folder, elem)) < limit\n and all([x in elem for x in substrings])]\n basename = os.path.basename(folder)\n return folder, files, basename\n\n\ndef extract_array(line):\n \"\"\"\n Return the array on the RHS of the line\n\n >>> extract_array(\"toto = ['one', 'two']\\n\")\n ['one', 'two']\n >>> extract_array('toto = [\"one\", 0.2]\\n')\n ['one', 0.2]\n\n \"\"\"\n # Recover RHS of the equal sign, and remove surrounding spaces\n rhs = line.split('=')[-1].strip()\n # Remove array signs\n rhs = rhs.strip(']').lstrip('[')\n # Recover each element of the list\n sequence = [e.strip().strip('\"').strip(\"'\") for e in rhs.split(',')]\n for index, elem in enumerate(sequence):\n try:\n sequence[index] = int(elem)\n except ValueError:\n try:\n sequence[index] = float(elem)\n except ValueError:\n pass\n return sequence\n\n\ndef extract_dict(line):\n \"\"\"\n Return the key and value of the dictionary element contained in line\n\n >>> extract_dict(\"something['toto'] = [0, 1, 2, -2, 'cosmo']\")\n 'toto', [0, 1, 2, -2, 'cosmo']\n\n \"\"\"\n # recovering the array\n sequence = extract_array(line)\n # Recovering only the LHS\n lhs = line.split('=')[0].strip()\n # Recovering the name from the LHS\n name = lhs.split('[')[-1].strip(']')\n name = name.strip('\"').strip(\"'\")\n\n return name, sequence\n\n\ndef extract_parameter_names(info):\n \"\"\"\n Reading the log.param, store in the Information instance the names\n \"\"\"\n backup_names = []\n plotted_parameters = []\n boundaries = []\n ref_names = []\n tex_names = []\n scales = []\n rescales = []\n centers = []\n with open(info.param_path, 'r') as param:\n for line in param:\n if line.find('#') == -1:\n if line.find('data.experiments') != -1:\n info.experiments = extract_array(line)\n if line.find('data.parameters') != -1:\n name, array = extract_dict(line)\n original = name\n # Rename the names according the .extra file (opt)\n if name in dictkeys(info.to_change):\n name = info.to_change[name]\n # If the name corresponds to a varying parameter (fourth\n # entry in the initial array being non-zero, or a derived\n # parameter (could be designed as fixed, it does not make\n # any difference)), then continue the process of analyzing.\n if array[3] != 0 or array[5] == 'derived' or array[5] == 'derived_lkl':\n # The real name is always kept, to have still the class\n # names in the covmat\n backup_names.append(original)\n # With the list \"to_plot\", we can potentially restrict\n # the variables plotted. If it is empty, though, simply\n # all parameters will be plotted.\n if info.to_plot == []:\n plotted_parameters.append(name)\n else:\n if name in info.to_plot:\n plotted_parameters.append(name)\n\n # Append to the boundaries array\n boundaries.append([\n None if elem == 'None' or (isinstance(elem, int)\n and elem == -1)\n else elem for elem in array[1:3]])\n ref_names.append(name)\n # Take care of the scales\n scale = array[4]\n rescale = 1.\n if name in dictkeys(info.new_scales):\n rescale = info.new_scales[name]/array[4]\n scales.append(scale)\n rescales.append(rescale)\n\n # Given the scale, decide for the pretty tex name\n number = 1./(scale*rescale)\n tex_names.append(\n io_mp.get_tex_name(name, number=number))\n\n # Read starting values (useful for plotting Fisher)\n centers.append(array[0])\n\n scales = np.diag(scales)\n rescales = np.diag(rescales)\n\n info.ref_names = ref_names\n info.tex_names = tex_names\n info.boundaries = boundaries\n info.backup_names = backup_names\n info.scales = scales\n info.rescales = rescales\n # Beware, the following two numbers are different. The first is the total\n # number of parameters stored in the chain, whereas the second is for\n # plotting purpose only.\n info.number_parameters = len(ref_names)\n info.plotted_parameters = plotted_parameters\n\n info.centers = centers\n\n\ndef find_maximum_of_likelihood(info):\n \"\"\"\n Finding the global maximum of likelihood\n\n min_minus_lkl will be appended with all the maximum likelihoods of files,\n then will be replaced by its own maximum. This way, the global\n maximum likelihood will be used as a reference, and not each chain's\n maximum.\n \"\"\"\n min_minus_lkl = []\n for chain_file in info.files:\n # cheese will brutally contain everything (- log likelihood) in the\n # file chain_file being scanned.\n # This could potentially be faster with pandas, but is already quite\n # fast\n #\n # This would read the chains including comment lines:\n #cheese = (np.array([float(line.split()[1].strip())\n # for line in open(chain_file, 'r')]))\n #\n # This reads the chains excluding comment lines:\n with open(chain_file, 'r') as f:\n cheese = (np.array([float(line.split()[1].strip())\n for line in py_filterfalse(iscomment,f)]))\n\n try:\n min_minus_lkl.append(cheese[:].min())\n except ValueError:\n pass\n # beware, it is the min because we are talking about\n # '- log likelihood'\n # Selecting only the true maximum.\n try:\n min_minus_lkl = min(min_minus_lkl)\n except ValueError:\n raise io_mp.AnalyzeError(\n \"No decently sized chain was found in the desired folder. \" +\n \"Please wait to have more accepted point before trying \" +\n \"to analyze it.\")\n\n info.min_minus_lkl = min_minus_lkl\n\n\ndef remove_bad_points(info):\n \"\"\"\n Create an array with all the points from the chains, after removing non-markovian, burn-in and fixed fraction\n\n \"\"\"\n # spam will brutally contain all the chains with sufficient number of\n # points, after the burn-in was removed.\n spam = list()\n\n # Recover the longest file name, for pleasing display\n max_name_length = max([len(e) for e in info.files])\n\n # Total number of steps done:\n steps = 0\n accepted_steps = 0\n\n # Open the log file\n log = open(info.log_path, 'w')\n\n for index, chain_file in enumerate(info.files):\n # To improve presentation, and print only once the full path of the\n # analyzed folder, we recover the length of the path name, and\n # create an empty complementary string of this length\n total_length = 18+max_name_length\n empty_length = 18+len(os.path.dirname(chain_file))+1\n\n basename = os.path.basename(chain_file)\n if index == 0:\n exec(\"sys.stdout.write('--> Scanning file %-{0}s' % chain_file)\".format(\n max_name_length))\n else:\n exec(\"sys.stdout.write('%{0}s%-{1}s' % ('', basename))\".format(\n empty_length, total_length-empty_length))\n # cheese will brutally contain everything in the chain chain_file being\n # scanned\n #\n # This would read the chains including comment lines:\n #cheese = (np.array([[float(elem) for elem in line.split()]\n # for line in open(chain_file, 'r')]))\n #\n # This read the chains excluding comment lines:\n with open(chain_file, 'r') as f:\n cheese = (np.array([[float(elem) for elem in line.split()]\n for line in py_filterfalse(iscomment,f)]))\n # If the file contains a broken line with a different number of\n # elements, the previous array generation might fail, and will not have\n # the correct shape. Hence the following command will fail. To avoid\n # that, the error is caught.\n try:\n local_min_minus_lkl = cheese[:, 1].min()\n except IndexError:\n raise io_mp.AnalyzeError(\n \"Error while scanning %s.\" % chain_file +\n \" This file most probably contains \"\n \"an incomplete line, rendering the analysis impossible. \"\n \"I think that the following line(s) is(are) wrong:\\n %s\" % (\n '\\n '.join(\n ['-> %s' % line for line in\n open(chain_file, 'r') if\n len(line.split()) != len(info.backup_names)+2])))\n line_count = float(sum(1 for line in open(chain_file, 'r')))\n\n # Logging the information obtained until now.\n number_of_steps = cheese[:, 0].sum()\n log.write(\"%s\\t \" % os.path.basename(chain_file))\n log.write(\" Number of steps:%d\\t\" % number_of_steps)\n log.write(\" Steps accepted:%d\\t\" % line_count)\n log.write(\" acc = %.2g\\t\" % (float(line_count)/number_of_steps))\n log.write(\"min(-loglike) = %.2f\\n\" % local_min_minus_lkl)\n steps += number_of_steps\n accepted_steps += line_count\n\n # check if analyze() is called directly by the user, or by the mcmc loop during an updating phase\n try:\n # command_line.update is defined when called by the mcmc loop\n info.update\n except:\n # in case it was not defined (i.e. when analyze() is called directly by user), set it to False\n info.update = 0\n # check if analyze() is called directly by the user, or by the mcmc loop during an updating phase\n try:\n # command_line.adaptive is defined when called by the mcmc loop\n info.adaptive\n except:\n # in case it was not defined (i.e. when analyze() is called directly by user), set it to False\n info.adaptive = 0\n\n # Removing non-markovian part, burn-in, and fraction= (1 - keep-fraction)\n start = 0\n markovian=0\n try:\n # Read all comments in chains about times when proposal was updated\n # The last of these comments gives the number of lines to be skipped in the files\n if info.markovian and not info.update:\n with open(chain_file, 'r') as f:\n for line in py_filter(iscomment,f):\n if info.only_markovian or ('update proposal' in line):\n start = int(line.split()[2])\n else:\n pass\n markovian = start\n\n # Remove burn-in, defined as all points until the likelhood reaches min_minus_lkl+LOG_LKL_CUTOFF\n # except when it is run in adaptive mode\n if not info.adaptive:\n while cheese[start, 1] > info.min_minus_lkl+LOG_LKL_CUTOFF:\n start += 1\n burnin = start-markovian\n\n # Remove fixed fraction as requested by user (usually not useful if non-markovian is also removed)\n if info.keep_fraction < 1:\n start = start + int((1.-info.keep_fraction)*(line_count - start))\n\n sys.stdout.write(\": Removed \")\n if info.markovian:\n sys.stdout.write(\"%d non-markovian points, \" % markovian)\n sys.stdout.write(\"%d points of burn-in, \" % burnin)\n if info.keep_fraction < 1:\n sys.stdout.write(\"and first %.0f percent, \" % (100.*(1-info.keep_fraction)))\n print(\"keep %d steps\" % (line_count-start))\n\n except IndexError:\n print(': Removed everything: chain not converged')\n\n\n # ham contains cheese without the burn-in, if there are any points\n # left (more than 5)\n if np.shape(cheese)[0] > start+5:\n ham = np.copy(cheese[int(start)::])\n\n # Deal with single file case\n if len(info.files) == 1:\n warnings.warn(\"Convergence computed for a single file\")\n bacon = np.copy(ham[::3, :])\n egg = np.copy(ham[1::3, :])\n sausage = np.copy(ham[2::3, :])\n\n spam.append(bacon)\n spam.append(egg)\n spam.append(sausage)\n continue\n\n # Adding resulting table to spam\n spam.append(ham)\n\n # Test the length of the list\n if len(spam) == 0:\n raise io_mp.AnalyzeError(\n \"No decently sized chain was found. \" +\n \"Please wait a bit to analyze this folder\")\n\n # Applying now new rules for scales, if the name is contained in the\n # referenced names\n for name in dictkeys(info.new_scales):\n try:\n index = info.ref_names.index(name)\n for i in xrange(len(spam)):\n spam[i][:, index+2] *= 1./info.rescales[index, index]\n except ValueError:\n # there is nothing to do if the name is not contained in ref_names\n pass\n\n info.steps = steps\n info.accepted_steps = accepted_steps\n\n return spam\n\n\ndef compute_mean(mean, spam, total):\n \"\"\"\n \"\"\"\n for i in xrange(np.shape(mean)[1]):\n for j in xrange(len(spam)):\n submean = np.sum(spam[j][:, 0]*spam[j][:, i+2])\n mean[j+1, i] = submean / total[j+1]\n mean[0, i] += submean\n mean[0, i] /= total[0]\n\n\ndef compute_variance(var, mean, spam, total):\n \"\"\"\n \"\"\"\n for i in xrange(np.shape(var)[1]):\n for j in xrange(len(spam)):\n var[0, i] += np.sum(\n spam[j][:, 0]*(spam[j][:, i+2]-mean[0, i])**2)\n var[j+1, i] = np.sum(\n spam[j][:, 0]*(spam[j][:, i+2]-mean[j+1, i])**2) / \\\n (total[j+1]-1)\n var[0, i] /= (total[0]-1)\n\n\ndef compute_covariance_matrix(info):\n \"\"\"\n \"\"\"\n covar = np.zeros((len(info.ref_names), len(info.ref_names)))\n for i in xrange(len(info.ref_names)):\n for j in xrange(i, len(info.ref_names)):\n covar[i, j] = (\n info.chain[:, 0]*(\n (info.chain[:, i+2]-info.mean[i]) *\n (info.chain[:, j+2]-info.mean[j]))).sum()\n if i != j:\n covar[j, i] = covar[i, j]\n covar /= info.total\n\n # Removing scale factors in order to store true parameter covariance\n covar = np.dot(info.scales.T, np.dot(covar, info.scales))\n\n return covar\n\n\ndef adjust_ticks(param, information_instances):\n \"\"\"\n \"\"\"\n if len(information_instances) == 1:\n return\n # Recovering all x_range and ticks entries from the concerned information\n # instances\n x_ranges = []\n ticks = []\n for info in information_instances:\n if not info.ignore_param:\n x_ranges.append(info.x_range[info.native_index])\n ticks.append(info.ticks[info.native_index])\n\n # The new x_range and tick should min/max all the existing ones\n new_x_range = np.array(\n [min([e[0] for e in x_ranges]), max([e[1] for e in x_ranges])])\n\n temp_ticks = np.array(\n [min([e[0] for e in ticks]), max([e[-1] for e in ticks])])\n\n new_ticks = np.linspace(temp_ticks[0],\n temp_ticks[1],\n info.ticknumber)\n\n for info in information_instances:\n if not info.ignore_param:\n info.x_range[info.native_index] = new_x_range\n info.ticks[info.native_index] = new_ticks\n\n\ndef store_contour_coordinates(info, name1, name2, contours):\n \"\"\"docstring\"\"\"\n file_name = os.path.join(\n info.folder, 'plots', '{0}_2d_{1}-{2}.dat'.format(\n info.basename, name1, name2))\n\n with open(file_name, 'w') as plot_file:\n plot_file.write(\n '# contour for confidence level {0}\\n'.format(\n info.levels[1]))\n for elem in contours.collections[0].get_paths():\n points = elem.vertices\n for k in range(np.shape(points)[0]):\n plot_file.write(\"%.8g\\t %.8g\\n\" % (\n points[k, 0], points[k, 1]))\n # stop to not include the inner contours\n if k != 0:\n if all(points[k] == points[0]):\n plot_file.write(\"\\n\")\n break\n plot_file.write(\"\\n\\n\")\n plot_file.write(\n '# contour for confidence level {0}\\n'.format(\n info.levels[0]))\n for elem in contours.collections[1].get_paths():\n points = elem.vertices\n for k in range(np.shape(points)[0]):\n plot_file.write(\"%.8g\\t %.8g\\n\" % (\n points[k, 0], points[k, 1]))\n if k != 0:\n if all(points[k] == points[0]):\n plot_file.write(\"\\n\")\n break\n plot_file.write(\"\\n\\n\")\n\ndef iscomment(s):\n \"\"\"\n Define what we call a comment in MontePython chain files\n \"\"\"\n return s.startswith('#')\n\nclass Information(object):\n \"\"\"\n Hold all information for analyzing runs\n\n \"\"\"\n # Counting the number of instances, to choose the color map\n _ids = count(0)\n # Flag checking the absence or presence of the interp1d function\n has_interpolate_module = False\n\n # Actual pairs of colors used by MP.\n # For each pair, the first color is for the 95% contour,\n # and the second for the 68% contour + the 1d probability.\n # Note that, as with the other customisation options, you can specify new\n # values for this in the extra plot_file.\n MP_color = {\n 'Red':['#E37C80','#CE121F'],\n 'Blue':['#7A98F6','#1157EF'],\n 'Green':['#88B27A','#297C09'],\n 'Orange':['#F3BE82','#ED920F'],\n 'Grey':['#ABABAB','#737373'],\n 'Purple':['#B87294','#88004C']\n }\n # order used when several directories are analysed\n MP_color_cycle = [\n MP_color['Red'],\n MP_color['Blue'],\n MP_color['Green'],\n MP_color['Orange'],\n MP_color['Grey'],\n MP_color['Purple']\n ]\n # in the same order, list of transparency levels\n alphas = [0.9, 0.9, 0.9, 0.9, 0.9, 0.9]\n\n def __init__(self, command_line, other=None):\n \"\"\"\n The following initialization creates the three tables that can be\n customized in an extra plot_file (see :mod:`parser_mp`).\n\n Parameters\n ----------\n command_line : Namespace\n it contains the initialised command line arguments\n \"\"\"\n self.to_change = {}\n \"\"\"\n Dictionary whose keys are the old parameter names, and values are the\n new ones. For instance :code:`{'beta_plus_lambda':'beta+lambda'}`\n\n \"\"\"\n self.to_derive = {}\n \"\"\"\n Array of names to re-order in the plotting. Names not included in this list\n will appear at the end in their usual ordering\n\n \"\"\"\n self.to_reorder = []\n \"\"\"\n Dictionary whose keys are new parameter names and values are formulas to calculate them.\n For instance :code:`{'beta_plus_lambda':'beta+lambda'}`\n\n \"\"\"\n self.to_plot = []\n \"\"\"\n Array of names of parameters to plot. If left empty, all will be\n plotted.\n\n .. warning::\n If you changed a parameter name with :attr:`to_change`, you need to\n give the new name to this array\n\n \"\"\"\n self.new_scales = {}\n \"\"\"\n Dictionary that redefines some scales. The keys will be the parameter\n name, and the value its scale.\n\n \"\"\"\n\n # Assign a unique id to this instance\n self.id = next(self._ids)\n\n # Defining the sigma contours (1, 2 and 3-sigma, and 95% CL)\n self.levels = np.concatenate([scipy.special.erf(np.array([1, 2, 3])/np.sqrt(2)),[0.95]])\n\n # Follows a bunch of initialisation to provide default members\n self.ref_names, self.backup_names = [], []\n self.scales, self.plotted_parameters = [], []\n self.spam = []\n\n # Store directly all information from the command_line object into this\n # instance, except the protected members (begin and end with __)\n for elem in dir(command_line):\n if elem.find('__') == -1:\n setattr(self, elem, getattr(command_line, elem))\n\n # initialise the legend flags\n self.plot_legend_1d = None\n self.plot_legend_2d = None\n\n # initialize the legend size to be the same as fontsize, but can be\n # altered in the extra file\n self.legendsize = self.fontsize\n self.legendnames = []\n\n # initialize the customisation script flags\n self.custom1d = []\n self.custom2d = []\n\n # initialise the dictionary enmforcing limit\n self.force_limits = {}\n\n # Read a potential file describing changes to be done for the parameter\n # names, and number of paramaters plotted (can be let empty, all will\n # then be plotted), but also the style of the plot. Note that this\n # overrides the command line options\n if command_line.optional_plot_file:\n plot_file_vars = {'info': self,'plt': plt}\n exec(open(command_line.optional_plot_file).read(), plot_file_vars)\n\n # check and store keep_fraction\n if command_line.keep_fraction<=0 or command_line.keep_fraction>1:\n raise io_mp.AnalyzeError(\"after --keep-fraction you should pass a float >0 and <=1\")\n self.keep_fraction = command_line.keep_fraction\n\n def remap_parameters(self, spam):\n \"\"\"\n Perform substitutions of parameters for analyzing\n\n .. note::\n\n for arbitrary combinations of parameters, the prior will not\n necessarily be flat.\n\n \"\"\"\n if hasattr(self, 'redefine'):\n for key, value in dictitems(self.redefine):\n # Check that the key was an original name\n if key in self.backup_names:\n print(' /|\\ Transforming', key, 'into', value)\n # We recover the indices of the key\n index_to_change = self.backup_names.index(key)+2\n print('/_o_\\ The new variable will be called ' +\n self.ref_names[self.backup_names.index(key)])\n # Recover all indices of all variables present in the\n # remapping\n variable_names = [elem for elem in self.backup_names if\n value.find(elem) != -1]\n indices = [self.backup_names.index(name)+2 for name in\n variable_names]\n # Now loop over all files in spam\n for i in xrange(len(spam)):\n # Assign variables to their values\n for index, name in zip(indices, variable_names):\n exec(\"%s = spam[i][:, %i]\" % (name, index))\n # Assign to the desired index the combination\n exec(\"spam[i][:, %i] = %s\" % (index_to_change, value))\n if hasattr(self, 'to_derive'):\n for key, value in dictitems(self.to_derive):\n print(' /|\\ Creating new parameter', key)\n print('/_o_\\ with formula ' + key + \" = \"+value)\n # Recover all indices of all variables present in the\n # remapping\n variable_names = [elem for elem in self.backup_names if\n value.find(elem) != -1]\n indices = [self.backup_names.index(name)+2 for name in\n variable_names]\n # Now loop over all files in spam\n for i in xrange(len(spam)):\n # For each file expand the dimension of spam by one\n spam[i] = np.hstack([spam[i],np.empty((len(spam[i]),1))])\n # Assign local variables to their values\n for index, name in zip(indices, variable_names):\n exec(\"%s = spam[i][:, %i]\" % (name, index))\n # Assign to to the appended array the combination\n exec(\"spam[i][:,-1] = %s\" % (value))\n\n # If everything was successfull, add the corresponding info\n self.ref_names.append(key)\n self.tex_names.append(io_mp.get_tex_name(key,number=1))\n self.backup_names.append(key)\n self.boundaries.append([None,None])\n N = len(self.scales)\n self.scales = np.vstack([np.hstack([self.scales,np.zeros((N,1))]),np.zeros((N+1,1)).T])\n self.scales[-1,-1]=1\n self.rescales = np.vstack([np.hstack([self.rescales,np.zeros((N,1))]),np.zeros((N+1,1)).T])\n self.rescales[-1,-1]=1\n self.number_parameters +=1\n self.plotted_parameters.append(key)\n self.centers = np.append(self.centers,0)\n if hasattr(self, 'to_reorder'):\n if(len(self.to_reorder)>0):\n indices = [self.backup_names.index(name) for name in self.to_reorder]\n missing_indices = [x for x in np.arange(len(self.backup_names)) if x not in indices]\n indices = np.concatenate([indices,missing_indices])\n self.ref_names = [self.ref_names[i] for i in indices]\n self.tex_names = [self.tex_names[i] for i in indices]\n self.backup_names = [self.backup_names[i] for i in indices]\n self.boundaries = [self.boundaries[i] for i in indices]\n self.scales = self.scales[indices][:,indices]\n self.rescales = self.rescales[indices][:,indices]\n self.centers = self.centers[indices]\n # Re-sort spam (barely any overhead, due to numpy's internal memory views)\n for i in xrange(len(spam)):\n spam[i][:,2:] = spam[i][:,indices+2]\n # Play the same game independently for plotted_parameters\n # since these might be a lot fewer\n indices = [self.plotted_parameters.index(name) for name in self.to_reorder]\n if(len(indices)>0):\n missing_indices = [x for x in np.arange(len(self.plotted_parameters)) if x not in indices]\n indices = np.concatenate([indices,missing_indices])\n self.plotted_parameters = [self.plotted_parameters[i] for i in indices]\n\n def define_ticks(self):\n \"\"\"\n \"\"\"\n self.max_values = self.chain[:, 2:].max(axis=0)\n self.min_values = self.chain[:, 2:].min(axis=0)\n self.span = (self.max_values-self.min_values)\n # Define the place of ticks, given the number of ticks desired, stored\n # in conf.ticknumber\n self.ticks = np.array(\n [np.linspace(self.min_values[i]+self.span[i]*0.1,\n self.max_values[i]-self.span[i]*0.1,\n self.ticknumber) for i in range(len(self.span))])\n # Define the x range (ticks start not exactly at the range boundary to\n # avoid display issues)\n self.x_range = np.array((self.min_values, self.max_values)).T\n\n # In case the exploration hit a boundary (as defined in the parameter\n # file), at the level of precision defined by the number of bins, the\n # ticks and x_range should be altered in order to display this\n # meaningful number instead.\n for i in range(np.shape(self.ticks)[0]):\n x_range = self.x_range[i]\n bounds = self.boundaries[i]\n # Left boundary\n if bounds[0] is not None:\n if abs(x_range[0]-bounds[0]) < self.span[i]/self.bins:\n self.ticks[i][0] = bounds[0]\n self.x_range[i][0] = bounds[0]\n # Right boundary\n if bounds[-1] is not None:\n if abs(x_range[-1]-bounds[-1]) < self.span[i]/self.bins:\n self.ticks[i][-1] = bounds[-1]\n self.x_range[i][-1] = bounds[-1]\n\n def write_information_files(self):\n\n # Store in info_names only the tex_names that were plotted, for this\n # instance, and in indices the corresponding list of indices. It also\n # removes the $ signs, for clarity\n self.info_names = [\n name for index, name in enumerate(self.tex_names) if\n self.ref_names[index] in self.plotted_parameters]\n self.indices = [self.tex_names.index(name) for name in self.info_names]\n self.tex_names = [name for index, name in enumerate(self.tex_names) if\n self.ref_names[index] in self.plotted_parameters]\n self.info_names = [name.replace('$', '') for name in self.info_names]\n\n # Define the bestfit array\n self.bestfit = np.zeros(len(self.ref_names))\n for i in xrange(len(self.ref_names)):\n self.bestfit[i] = self.chain[self.sorted_indices[0], :][2+i]\n\n # Write down to the .h_info file all necessary information\n self.write_h_info()\n self.write_v_info()\n self.write_tex()\n\n def write_h_info(self):\n\n with open(self.h_info_path, 'w') as h_info:\n h_info.write(' param names\\t: ')\n for name in self.info_names:\n h_info.write(\"%-14s\" % name)\n\n write_h(h_info, self.indices, 'R-1 values', '% .6f', self.R)\n write_h(h_info, self.indices, 'Best Fit ', '% .6e', self.bestfit)\n write_h(h_info, self.indices, 'mean ', '% .6e', self.mean)\n write_h(h_info, self.indices, 'sigma ', '% .6e',\n (self.bounds[:, 0, 1]-self.bounds[:, 0, 0])/2.)\n h_info.write('\\n')\n write_h(h_info, self.indices, '1-sigma - ', '% .6e',\n self.bounds[:, 0, 0])\n write_h(h_info, self.indices, '1-sigma + ', '% .6e',\n self.bounds[:, 0, 1])\n write_h(h_info, self.indices, '2-sigma - ', '% .6e',\n self.bounds[:, 1, 0])\n write_h(h_info, self.indices, '2-sigma + ', '% .6e',\n self.bounds[:, 1, 1])\n write_h(h_info, self.indices, '3-sigma - ', '% .6e',\n self.bounds[:, 2, 0])\n write_h(h_info, self.indices, '3-sigma + ', '% .6e',\n self.bounds[:, 2, 1])\n\n # bounds\n h_info.write('\\n')\n write_h(h_info, self.indices, '1-sigma > ', '% .6e',\n self.mean+self.bounds[:, 0, 0])\n write_h(h_info, self.indices, '1-sigma < ', '% .6e',\n self.mean+self.bounds[:, 0, 1])\n write_h(h_info, self.indices, '2-sigma > ', '% .6e',\n self.mean+self.bounds[:, 1, 0])\n write_h(h_info, self.indices, '2-sigma < ', '% .6e',\n self.mean+self.bounds[:, 1, 1])\n write_h(h_info, self.indices, '3-sigma > ', '% .6e',\n self.mean+self.bounds[:, 2, 0])\n write_h(h_info, self.indices, '3-sigma < ', '% .6e',\n self.mean+self.bounds[:, 2, 1])\n write_h(h_info, self.indices, '95% > ', '% .6e',\n self.mean+self.bounds[:, -1, 0])\n write_h(h_info, self.indices, '95% < ', '% .6e',\n self.mean+self.bounds[:, -1, 1])\n\n def write_v_info(self):\n \"\"\"Write vertical info file\"\"\"\n with open(self.v_info_path, 'w') as v_info:\n v_info.write('%-15s\\t: %-11s' % ('param names', 'R-1'))\n v_info.write(' '.join(['%-11s' % elem for elem in [\n 'Best fit', 'mean', 'sigma', '1-sigma -', '1-sigma +',\n '2-sigma -', '2-sigma +', '1-sigma >', '1-sigma <',\n '2-sigma >', '2-sigma <', '95% CL >', '95% CL <']]))\n for index, name in zip(self.indices, self.info_names):\n v_info.write('\\n%-15s\\t: % .4e' % (name, self.R[index]))\n v_info.write(' '.join(['% .4e' % elem for elem in [\n self.bestfit[index], self.mean[index],\n (self.bounds[index, 0, 1]-self.bounds[index, 0, 0])/2.,\n self.bounds[index, 0, 0], self.bounds[index, 0, 1],\n self.bounds[index, 1, 0], self.bounds[index, 1, 1],\n self.mean[index]+self.bounds[index, 0, 0],\n self.mean[index]+self.bounds[index, 0, 1],\n self.mean[index]+self.bounds[index, 1, 0],\n self.mean[index]+self.bounds[index, 1, 1],\n self.mean[index]+self.bounds[index, -1, 0],\n self.mean[index]+self.bounds[index, -1, 1]]]))\n\n def write_tex(self):\n \"\"\"Write a tex table containing the main results \"\"\"\n with open(self.tex_path, 'w') as tex:\n tex.write(\"\\\\begin{tabular}{|l|c|c|c|c|} \\n \\\\hline \\n\")\n tex.write(\"Param & best-fit & mean$\\pm\\sigma$ \")\n tex.write(\"& 95\\% lower & 95\\% upper \\\\\\\\ \\\\hline \\n\")\n for index, name in zip(self.indices, self.tex_names):\n tex.write(\"%s &\" % name)\n tex.write(\"$%.4g$ & $%.4g_{%.2g}^{+%.2g}$ \" % (\n self.bestfit[index], self.mean[index],\n self.bounds[index, 0, 0], self.bounds[index, 0, 1]))\n tex.write(\"& $%.4g$ & $%.4g$ \\\\\\\\ \\n\" % (\n self.mean[index]+self.bounds[index, -1, 0],\n self.mean[index]+self.bounds[index, -1, 1]))\n\n tex.write(\"\\\\hline \\n \\\\end{tabular} \\\\\\\\ \\n\")\n tex.write(\"$-\\ln{\\cal L}_\\mathrm{min} =%.6g$, \" % (\n self.min_minus_lkl))\n tex.write(\"minimum $\\chi^2=%.4g$ \\\\\\\\ \\n\" % (\n self.min_minus_lkl*2.))\n"
] |
[
[
"numpy.diag",
"numpy.dot",
"numpy.polyfit",
"numpy.amax",
"numpy.sqrt",
"numpy.linspace",
"numpy.cumsum",
"numpy.concatenate",
"numpy.max",
"numpy.searchsorted",
"numpy.exp",
"numpy.histogram",
"numpy.copy",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.log",
"numpy.min",
"numpy.linalg.inv",
"numpy.append",
"numpy.array",
"numpy.sum",
"matplotlib.rc",
"numpy.histogram2d",
"matplotlib.pyplot.Rectangle",
"matplotlib.use",
"numpy.shape",
"numpy.vstack"
]
] |
georgesbarron/qiskit-terra
|
[
"221dfffe058951c9c493d346583d20b560a414f5"
] |
[
"test/python/circuit/test_library.py"
] |
[
"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Test library of quantum circuits.\"\"\"\n\nimport unittest\nfrom collections import defaultdict\nfrom ddt import ddt, data, unpack\nimport numpy as np\n\nfrom qiskit.test.base import QiskitTestCase\nfrom qiskit import BasicAer, execute, transpile\nfrom qiskit.circuit import (QuantumCircuit, QuantumRegister, Parameter, ParameterExpression,\n ParameterVector)\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.circuit.library import (BlueprintCircuit, Permutation, QuantumVolume, XOR,\n InnerProduct, OR, AND, QFT, IQP,\n LinearPauliRotations, PolynomialPauliRotations,\n IntegerComparator, PiecewiseLinearPauliRotations,\n WeightedAdder, Diagonal, NLocal, TwoLocal, RealAmplitudes,\n EfficientSU2, ExcitationPreserving, PauliFeatureMap,\n ZFeatureMap, ZZFeatureMap, MCMT, MCMTVChain, GMS,\n HiddenLinearFunction)\nfrom qiskit.circuit.random.utils import random_circuit\nfrom qiskit.converters.circuit_to_dag import circuit_to_dag\nfrom qiskit.exceptions import QiskitError\nfrom qiskit.circuit.library import (XGate, RXGate, RYGate, RZGate, CRXGate, CCXGate, SwapGate,\n RXXGate, RYYGate, HGate, ZGate, CXGate, CZGate, CHGate)\nfrom qiskit.quantum_info import Statevector, Operator\nfrom qiskit.quantum_info.random import random_unitary\nfrom qiskit.quantum_info.states import state_fidelity\n\n\nclass MockBlueprint(BlueprintCircuit):\n \"\"\"A mock blueprint class.\"\"\"\n\n def __init__(self, num_qubits):\n super().__init__(name='mock')\n self.num_qubits = num_qubits\n\n @property\n def num_qubits(self):\n return self._num_qubits\n\n @num_qubits.setter\n def num_qubits(self, num_qubits):\n self._invalidate()\n self._num_qubits = num_qubits\n self.qregs = [QuantumRegister(self.num_qubits, name='q')]\n\n def _check_configuration(self, raise_on_failure=True):\n valid = True\n if self.num_qubits is None:\n valid = False\n if raise_on_failure:\n raise AttributeError('The number of qubits was not set.')\n\n if self.num_qubits < 1:\n valid = False\n if raise_on_failure:\n raise ValueError('The number of qubits must at least be 1.')\n\n return valid\n\n def _build(self):\n super()._build()\n\n # pylint: disable=no-member\n self.rx(Parameter('angle'), 0)\n self.h(self.qubits)\n\n\nclass TestBlueprintCircuit(QiskitTestCase):\n \"\"\"Test the blueprint circuit.\"\"\"\n\n def test_invalidate_rebuild(self):\n \"\"\"Test that invalidate and build reset and set _data and _parameter_table.\"\"\"\n mock = MockBlueprint(5)\n mock._build()\n\n with self.subTest(msg='after building'):\n self.assertGreater(len(mock._data), 0)\n self.assertEqual(len(mock._parameter_table), 1)\n\n mock._invalidate()\n with self.subTest(msg='after invalidating'):\n self.assertTrue(mock._data is None)\n self.assertEqual(len(mock._parameter_table), 0)\n\n mock._build()\n with self.subTest(msg='after re-building'):\n self.assertGreater(len(mock._data), 0)\n self.assertEqual(len(mock._parameter_table), 1)\n\n def test_calling_attributes_works(self):\n \"\"\"Test that the circuit is constructed when attributes are called.\"\"\"\n properties = ['data']\n for prop in properties:\n with self.subTest(prop=prop):\n circuit = MockBlueprint(3)\n getattr(circuit, prop)\n self.assertGreater(len(circuit._data), 0)\n\n methods = ['qasm', 'count_ops', 'num_connected_components', 'num_nonlocal_gates',\n 'depth', '__len__', 'copy']\n for method in methods:\n with self.subTest(method=method):\n circuit = MockBlueprint(3)\n getattr(circuit, method)()\n self.assertGreater(len(circuit._data), 0)\n\n with self.subTest(method='__get__[0]'):\n circuit = MockBlueprint(3)\n _ = circuit[2]\n self.assertGreater(len(circuit._data), 0)\n\n\nclass TestPermutationLibrary(QiskitTestCase):\n \"\"\"Test library of permutation logic quantum circuits.\"\"\"\n\n def test_permutation(self):\n \"\"\"Test permutation circuit.\"\"\"\n circuit = Permutation(num_qubits=4, pattern=[1, 0, 3, 2])\n expected = QuantumCircuit(4)\n expected.swap(0, 1)\n expected.swap(2, 3)\n expected = Operator(expected)\n simulated = Operator(circuit)\n self.assertTrue(expected.equiv(simulated))\n\n def test_permutation_bad(self):\n \"\"\"Test that [0,..,n-1] permutation is required (no -1 for last element).\"\"\"\n self.assertRaises(CircuitError, Permutation, 4, [1, 0, -1, 2])\n\n\n@ddt\nclass TestHiddenLinearFunctionLibrary(QiskitTestCase):\n \"\"\"Test library of Hidden Linear Function circuits.\"\"\"\n\n def assertHLFIsCorrect(self, hidden_function, hlf):\n \"\"\"Assert that the HLF circuit produces the correct matrix.\n\n Number of qubits is equal to the number of rows (or number of columns)\n of hidden_function.\n \"\"\"\n num_qubits = len(hidden_function)\n hidden_function = np.asarray(hidden_function)\n simulated = Operator(hlf)\n\n expected = np.zeros((2**num_qubits, 2**num_qubits), dtype=complex)\n for i in range(2**num_qubits):\n i_qiskit = int(bin(i)[2:].zfill(num_qubits)[::-1], 2)\n x_vec = np.asarray(list(map(int, bin(i)[2:].zfill(num_qubits)[::-1])))\n expected[i_qiskit, i_qiskit] = 1j**(np.dot(x_vec.transpose(),\n np.dot(hidden_function, x_vec)))\n\n qc = QuantumCircuit(num_qubits)\n qc.h(range(num_qubits))\n qc = Operator(qc)\n expected = qc.compose(Operator(expected)).compose(qc)\n self.assertTrue(expected.equiv(simulated))\n\n @data(\n [[1, 1, 0], [1, 0, 1], [0, 1, 1]]\n )\n def test_hlf(self, hidden_function):\n \"\"\"Test if the HLF matrix produces the right matrix.\"\"\"\n hlf = HiddenLinearFunction(hidden_function)\n self.assertHLFIsCorrect(hidden_function, hlf)\n\n def test_non_symmetric_raises(self):\n \"\"\"Test that adjacency matrix is required to be symmetric.\"\"\"\n with self.assertRaises(CircuitError):\n HiddenLinearFunction([[1, 1, 0], [1, 0, 1], [1, 1, 1]])\n\n\nclass TestIQPLibrary(QiskitTestCase):\n \"\"\"Test library of IQP quantum circuits.\"\"\"\n\n def test_iqp(self):\n \"\"\"Test iqp circuit.\"\"\"\n circuit = IQP(interactions=np.array([[6, 5, 1], [5, 4, 3], [1, 3, 2]]))\n expected = QuantumCircuit(3)\n expected.h([0, 1, 2])\n expected.cu1(5*np.pi/2, 0, 1)\n expected.cu1(3*np.pi/2, 1, 2)\n expected.cu1(1*np.pi/2, 0, 2)\n expected.u1(6*np.pi/8, 0)\n expected.u1(4*np.pi/8, 1)\n expected.u1(2*np.pi/8, 2)\n expected.h([0, 1, 2])\n expected = Operator(expected)\n simulated = Operator(circuit)\n self.assertTrue(expected.equiv(simulated))\n\n def test_iqp_bad(self):\n \"\"\"Test that [0,..,n-1] permutation is required (no -1 for last element).\"\"\"\n self.assertRaises(CircuitError, IQP, [[6, 5], [2, 4]])\n\n\n@ddt\nclass TestGMSLibrary(QiskitTestCase):\n \"\"\"Test library of Global Mølmer–Sørensen gate.\"\"\"\n\n def test_twoq_equivalence(self):\n \"\"\"Test GMS on 2 qubits is same as RXX.\"\"\"\n circuit = GMS(num_qubits=2, theta=[[0, np.pi/3], [0, 0]])\n expected = RXXGate(np.pi/3)\n expected = Operator(expected)\n simulated = Operator(circuit)\n self.assertTrue(expected.equiv(simulated))\n\n\n@ddt\nclass TestQuantumVolumeLibrary(QiskitTestCase):\n \"\"\"Test library of quantum volume quantum circuits.\"\"\"\n\n def test_qv(self):\n \"\"\"Test qv circuit.\"\"\"\n circuit = QuantumVolume(2, 2, seed=2, classical_permutation=False)\n expected = QuantumCircuit(2)\n expected.swap(0, 1)\n expected.append(random_unitary(4, seed=837), [0, 1])\n expected.append(random_unitary(4, seed=262), [0, 1])\n expected = Operator(expected)\n simulated = Operator(circuit)\n self.assertTrue(expected.equiv(simulated))\n\n\n@ddt\nclass TestBooleanLogicLibrary(QiskitTestCase):\n \"\"\"Test library of boolean logic quantum circuits.\"\"\"\n\n def assertBooleanFunctionIsCorrect(self, boolean_circuit, reference):\n \"\"\"Assert that ``boolean_circuit`` implements the reference boolean function correctly.\"\"\"\n circuit = QuantumCircuit(boolean_circuit.num_qubits)\n circuit.h(list(range(boolean_circuit.num_variable_qubits)))\n circuit.append(boolean_circuit.to_instruction(), list(range(boolean_circuit.num_qubits)))\n\n # compute the statevector of the circuit\n statevector = Statevector.from_label('0' * circuit.num_qubits)\n statevector = statevector.evolve(circuit)\n\n # trace out ancillas\n probabilities = statevector.probabilities(\n qargs=list(range(boolean_circuit.num_variable_qubits + 1))\n )\n\n # compute the expected outcome by computing the entries of the statevector that should\n # have a 1 / sqrt(2**n) factor\n expectations = np.zeros_like(probabilities)\n for x in range(2 ** boolean_circuit.num_variable_qubits):\n bits = np.array(list(bin(x)[2:].zfill(boolean_circuit.num_variable_qubits)), dtype=int)\n result = reference(bits[::-1])\n\n entry = int(str(int(result)) + bin(x)[2:].zfill(boolean_circuit.num_variable_qubits), 2)\n expectations[entry] = 1 / 2 ** boolean_circuit.num_variable_qubits\n\n np.testing.assert_array_almost_equal(probabilities, expectations)\n\n def test_xor(self):\n \"\"\"Test xor circuit.\n\n TODO add a test using assertBooleanFunctionIsCorrect\n \"\"\"\n circuit = XOR(num_qubits=3, amount=4)\n expected = QuantumCircuit(3)\n expected.x(2)\n self.assertEqual(circuit, expected)\n\n def test_inner_product(self):\n \"\"\"Test inner product circuit.\n\n TODO add a test using assertBooleanFunctionIsCorrect\n \"\"\"\n circuit = InnerProduct(num_qubits=3)\n expected = QuantumCircuit(*circuit.qregs)\n expected.cz(0, 3)\n expected.cz(1, 4)\n expected.cz(2, 5)\n self.assertEqual(circuit, expected)\n\n @data(\n (2, None, 'noancilla'),\n (5, None, 'noancilla'),\n (2, [-1, 1], 'v-chain'),\n (2, [-1, 1], 'noancilla'),\n (5, [0, 0, -1, 1, -1], 'noancilla'),\n (5, [-1, 0, 0, 1, 1], 'v-chain'),\n )\n @unpack\n def test_or(self, num_variables, flags, mcx_mode):\n \"\"\"Test the or circuit.\"\"\"\n or_circuit = OR(num_variables, flags, mcx_mode=mcx_mode)\n flags = flags or [1] * num_variables\n\n def reference(bits):\n flagged = []\n for flag, bit in zip(flags, bits):\n if flag < 0:\n flagged += [1 - bit]\n elif flag > 0:\n flagged += [bit]\n return np.any(flagged)\n\n self.assertBooleanFunctionIsCorrect(or_circuit, reference)\n\n @data(\n (2, None, 'noancilla'),\n (2, [-1, 1], 'v-chain'),\n (5, [0, 0, -1, 1, -1], 'noancilla'),\n (5, [-1, 0, 0, 1, 1], 'v-chain'),\n )\n @unpack\n def test_and(self, num_variables, flags, mcx_mode):\n \"\"\"Test the and circuit.\"\"\"\n and_circuit = AND(num_variables, flags, mcx_mode=mcx_mode)\n flags = flags or [1] * num_variables\n\n def reference(bits):\n flagged = []\n for flag, bit in zip(flags, bits):\n if flag < 0:\n flagged += [1 - bit]\n elif flag > 0:\n flagged += [bit]\n return np.all(flagged)\n\n self.assertBooleanFunctionIsCorrect(and_circuit, reference)\n\n\n@ddt\nclass TestBasisChanges(QiskitTestCase):\n \"\"\"Test the basis changes.\"\"\"\n\n def assertQFTIsCorrect(self, qft, num_qubits=None, inverse=False, add_swaps_at_end=False):\n \"\"\"Assert that the QFT circuit produces the correct matrix.\n\n Can be provided with an explicit number of qubits, if None is provided the number\n of qubits is set to ``qft.num_qubits``.\n \"\"\"\n if add_swaps_at_end:\n circuit = QuantumCircuit(*qft.qregs)\n for i in range(circuit.num_qubits // 2):\n circuit.swap(i, circuit.num_qubits - i - 1)\n\n qft = qft + circuit\n\n simulated = Operator(qft)\n\n num_qubits = num_qubits or qft.num_qubits\n expected = np.empty((2 ** num_qubits, 2 ** num_qubits), dtype=complex)\n for i in range(2 ** num_qubits):\n i_qiskit = int(bin(i)[2:].zfill(num_qubits)[::-1], 2)\n for j in range(i, 2 ** num_qubits):\n entry = np.exp(2 * np.pi * 1j * i * j / 2 ** num_qubits) / 2 ** (num_qubits / 2)\n j_qiskit = int(bin(j)[2:].zfill(num_qubits)[::-1], 2)\n expected[i_qiskit, j_qiskit] = entry\n if i != j:\n expected[j_qiskit, i_qiskit] = entry\n\n if inverse:\n expected = np.conj(expected)\n\n expected = Operator(expected)\n\n self.assertTrue(expected.equiv(simulated))\n\n @data(True, False)\n def test_qft_matrix(self, inverse):\n \"\"\"Test the matrix representation of the QFT.\"\"\"\n num_qubits = 5\n qft = QFT(num_qubits)\n if inverse:\n qft = qft.inverse()\n self.assertQFTIsCorrect(qft, inverse=inverse)\n\n def test_qft_is_inverse(self):\n \"\"\"Test the is_inverse() method.\"\"\"\n qft = QFT(2)\n\n with self.subTest(msg='initial object is not inverse'):\n self.assertFalse(qft.is_inverse())\n\n qft = qft.inverse()\n with self.subTest(msg='inverted'):\n self.assertTrue(qft.is_inverse())\n\n qft = qft.inverse()\n with self.subTest(msg='re-inverted'):\n self.assertFalse(qft.is_inverse())\n\n def test_qft_mutability(self):\n \"\"\"Test the mutability of the QFT circuit.\"\"\"\n qft = QFT()\n\n with self.subTest(msg='empty initialization'):\n self.assertEqual(qft.num_qubits, 0)\n self.assertEqual(qft.data, [])\n\n with self.subTest(msg='changing number of qubits'):\n qft.num_qubits = 3\n self.assertQFTIsCorrect(qft, num_qubits=3)\n\n with self.subTest(msg='test diminishing the number of qubits'):\n qft.num_qubits = 1\n self.assertQFTIsCorrect(qft, num_qubits=1)\n\n with self.subTest(msg='test with swaps'):\n qft.num_qubits = 4\n qft.do_swaps = False\n self.assertQFTIsCorrect(qft, add_swaps_at_end=True)\n\n with self.subTest(msg='inverse'):\n qft = qft.inverse()\n qft.do_swaps = True\n self.assertQFTIsCorrect(qft, inverse=True)\n\n with self.subTest(msg='double inverse'):\n qft = qft.inverse()\n self.assertQFTIsCorrect(qft)\n\n with self.subTest(msg='set approximation'):\n qft.approximation_degree = 2\n qft.do_swaps = True\n with self.assertRaises(AssertionError):\n self.assertQFTIsCorrect(qft)\n\n @data(\n (4, 0, False),\n (3, 0, True),\n (6, 2, False),\n (4, 5, True),\n )\n @unpack\n def test_qft_num_gates(self, num_qubits, approximation_degree, insert_barriers):\n \"\"\"Test the number of gates in the QFT and the approximated QFT.\"\"\"\n basis_gates = ['h', 'swap', 'cu1']\n\n qft = QFT(num_qubits, approximation_degree=approximation_degree,\n insert_barriers=insert_barriers)\n ops = transpile(qft, basis_gates=basis_gates).count_ops()\n\n with self.subTest(msg='assert H count'):\n self.assertEqual(ops['h'], num_qubits)\n\n with self.subTest(msg='assert swap count'):\n self.assertEqual(ops['swap'], num_qubits // 2)\n\n with self.subTest(msg='assert CU1 count'):\n expected = sum(max(0, min(num_qubits - 1 - k, num_qubits - 1 - approximation_degree))\n for k in range(num_qubits))\n self.assertEqual(ops.get('cu1', 0), expected)\n\n with self.subTest(msg='assert barrier count'):\n expected = qft.num_qubits if insert_barriers else 0\n self.assertEqual(ops.get('barrier', 0), expected)\n\n\n@ddt\nclass TestFunctionalPauliRotations(QiskitTestCase):\n \"\"\"Test the functional Pauli rotations.\"\"\"\n\n def assertFunctionIsCorrect(self, function_circuit, reference):\n \"\"\"Assert that ``function_circuit`` implements the reference function ``reference``.\"\"\"\n num_state_qubits = function_circuit.num_state_qubits\n num_ancilla_qubits = function_circuit.num_ancilla_qubits\n circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits)\n circuit.h(list(range(num_state_qubits)))\n circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))\n\n backend = BasicAer.get_backend('statevector_simulator')\n statevector = execute(circuit, backend).result().get_statevector()\n\n probabilities = defaultdict(float)\n for i, statevector_amplitude in enumerate(statevector):\n i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:]\n probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)\n\n unrolled_probabilities = []\n unrolled_expectations = []\n for i, probability in probabilities.items():\n x, last_qubit = int(i[1:], 2), i[0]\n if last_qubit == '0':\n expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)\n else:\n expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)\n\n unrolled_probabilities += [probability]\n unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]\n\n np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations)\n\n @data(\n ([1, 0.1], 3),\n ([0, 0.4, 2], 2),\n )\n @unpack\n def test_polynomial_function(self, coeffs, num_state_qubits):\n \"\"\"Test the polynomial rotation.\"\"\"\n def poly(x):\n res = sum(coeff * x**i for i, coeff in enumerate(coeffs))\n return res\n\n polynome = PolynomialPauliRotations(num_state_qubits, [2 * coeff for coeff in coeffs])\n self.assertFunctionIsCorrect(polynome, poly)\n\n def test_polynomial_rotations_mutability(self):\n \"\"\"Test the mutability of the linear rotations circuit.\"\"\"\n\n polynomial_rotations = PolynomialPauliRotations()\n\n with self.subTest(msg='missing number of state qubits'):\n with self.assertRaises(AttributeError): # no state qubits set\n print(polynomial_rotations.draw())\n\n with self.subTest(msg='default setup, just setting number of state qubits'):\n polynomial_rotations.num_state_qubits = 2\n self.assertFunctionIsCorrect(polynomial_rotations, lambda x: x / 2)\n\n with self.subTest(msg='setting non-default values'):\n polynomial_rotations.coeffs = [0, 1.2 * 2, 0.4 * 2]\n self.assertFunctionIsCorrect(polynomial_rotations, lambda x: 1.2 * x + 0.4 * x ** 2)\n\n with self.subTest(msg='changing of all values'):\n polynomial_rotations.num_state_qubits = 4\n polynomial_rotations.coeffs = [1 * 2, 0, 0, -0.5 * 2]\n self.assertFunctionIsCorrect(polynomial_rotations, lambda x: 1 - 0.5 * x**3)\n\n @data(\n (2, 0.1, 0),\n (4, -2, 2),\n (1, 0, 0)\n )\n @unpack\n def test_linear_function(self, num_state_qubits, slope, offset):\n \"\"\"Test the linear rotation arithmetic circuit.\"\"\"\n def linear(x):\n return offset + slope * x\n\n linear_rotation = LinearPauliRotations(num_state_qubits, slope * 2, offset * 2)\n self.assertFunctionIsCorrect(linear_rotation, linear)\n\n def test_linear_rotations_mutability(self):\n \"\"\"Test the mutability of the linear rotations circuit.\"\"\"\n\n linear_rotation = LinearPauliRotations()\n\n with self.subTest(msg='missing number of state qubits'):\n with self.assertRaises(AttributeError): # no state qubits set\n print(linear_rotation.draw())\n\n with self.subTest(msg='default setup, just setting number of state qubits'):\n linear_rotation.num_state_qubits = 2\n self.assertFunctionIsCorrect(linear_rotation, lambda x: x / 2)\n\n with self.subTest(msg='setting non-default values'):\n linear_rotation.slope = -2.3 * 2\n linear_rotation.offset = 1 * 2\n self.assertFunctionIsCorrect(linear_rotation, lambda x: 1 - 2.3 * x)\n\n with self.subTest(msg='changing all values'):\n linear_rotation.num_state_qubits = 4\n linear_rotation.slope = 0.2 * 2\n linear_rotation.offset = 0.1 * 2\n self.assertFunctionIsCorrect(linear_rotation, lambda x: 0.1 + 0.2 * x)\n\n @data(\n (1, [0], [1], [0]),\n (2, [0, 2], [-0.5, 1], [2, 1]),\n (3, [0, 2, 5], [1, 0, -1], [0, 2, 2]),\n (2, [1, 2], [1, -1], [2, 1]),\n (3, [0, 1], [1, 0], [0, 1])\n )\n @unpack\n def test_piecewise_linear_function(self, num_state_qubits, breakpoints, slopes, offsets):\n \"\"\"Test the piecewise linear rotations.\"\"\"\n def pw_linear(x):\n for i, point in enumerate(reversed(breakpoints)):\n if x >= point:\n return offsets[-(i + 1)] + slopes[-(i + 1)] * (x - point)\n return 0\n\n pw_linear_rotations = PiecewiseLinearPauliRotations(num_state_qubits, breakpoints,\n [2 * slope for slope in slopes],\n [2 * offset for offset in offsets])\n\n self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear)\n\n def test_piecewise_linear_rotations_mutability(self):\n \"\"\"Test the mutability of the linear rotations circuit.\"\"\"\n\n pw_linear_rotations = PiecewiseLinearPauliRotations()\n\n with self.subTest(msg='missing number of state qubits'):\n with self.assertRaises(AttributeError): # no state qubits set\n print(pw_linear_rotations.draw())\n\n with self.subTest(msg='default setup, just setting number of state qubits'):\n pw_linear_rotations.num_state_qubits = 2\n self.assertFunctionIsCorrect(pw_linear_rotations, lambda x: x / 2)\n\n with self.subTest(msg='setting non-default values'):\n pw_linear_rotations.breakpoints = [0, 2]\n pw_linear_rotations.slopes = [-1 * 2, 1 * 2]\n pw_linear_rotations.offsets = [0, -1.2 * 2]\n self.assertFunctionIsCorrect(pw_linear_rotations,\n lambda x: -1.2 + (x - 2) if x >= 2 else -x)\n\n with self.subTest(msg='changing all values'):\n pw_linear_rotations.num_state_qubits = 4\n pw_linear_rotations.breakpoints = [1, 3, 6]\n pw_linear_rotations.slopes = [-1 * 2, 1 * 2, -0.2 * 2]\n pw_linear_rotations.offsets = [0, -1.2 * 2, 2 * 2]\n\n def pw_linear(x):\n if x >= 6:\n return 2 - 0.2 * (x - 6)\n if x >= 3:\n return -1.2 + (x - 3)\n if x >= 1:\n return -(x - 1)\n return 0\n\n self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear)\n\n\n@ddt\nclass TestIntegerComparator(QiskitTestCase):\n \"\"\"Text Fixed Value Comparator\"\"\"\n\n def assertComparisonIsCorrect(self, comp, num_state_qubits, value, geq):\n \"\"\"Assert that the comparator output is correct.\"\"\"\n qc = QuantumCircuit(comp.num_qubits) # initialize circuit\n qc.h(list(range(num_state_qubits))) # set equal superposition state\n qc.append(comp, list(range(comp.num_qubits))) # add comparator\n\n # run simulation\n backend = BasicAer.get_backend('statevector_simulator')\n statevector = execute(qc, backend).result().get_statevector()\n for i, amplitude in enumerate(statevector):\n prob = np.abs(amplitude)**2\n if prob > 1e-6:\n # equal superposition\n self.assertEqual(True, np.isclose(1.0, prob * 2.0**num_state_qubits))\n b_value = '{0:b}'.format(i).rjust(qc.width(), '0')\n x = int(b_value[(-num_state_qubits):], 2)\n comp_result = int(b_value[-num_state_qubits-1], 2)\n if geq:\n self.assertEqual(x >= value, comp_result == 1)\n else:\n self.assertEqual(x < value, comp_result == 1)\n\n @data(\n # n, value, geq\n [1, 0, True],\n [1, 1, True],\n [2, -1, True],\n [3, 5, True],\n [3, 2, True],\n [3, 2, False],\n [4, 6, False]\n )\n @unpack\n def test_fixed_value_comparator(self, num_state_qubits, value, geq):\n \"\"\"Test the fixed value comparator circuit.\"\"\"\n # build the circuit with the comparator\n comp = IntegerComparator(num_state_qubits, value, geq=geq)\n self.assertComparisonIsCorrect(comp, num_state_qubits, value, geq)\n\n def test_mutability(self):\n \"\"\"Test changing the arguments of the comparator.\"\"\"\n\n comp = IntegerComparator()\n\n with self.subTest(msg='missing num state qubits and value'):\n with self.assertRaises(AttributeError):\n print(comp.draw())\n\n comp.num_state_qubits = 2\n\n with self.subTest(msg='missing value'):\n with self.assertRaises(AttributeError):\n print(comp.draw())\n\n comp.value = 0\n comp.geq = True\n\n with self.subTest(msg='updating num state qubits'):\n comp.num_state_qubits = 1\n self.assertComparisonIsCorrect(comp, 1, 0, True)\n\n with self.subTest(msg='updating the value'):\n comp.num_state_qubits = 3\n comp.value = 2\n self.assertComparisonIsCorrect(comp, 3, 2, True)\n\n with self.subTest(msg='updating geq'):\n comp.geq = False\n self.assertComparisonIsCorrect(comp, 3, 2, False)\n\n\nclass TestAquaApplications(QiskitTestCase):\n \"\"\"Test applications of the arithmetic library in Aqua use-cases.\"\"\"\n\n def test_asian_barrier_spread(self):\n \"\"\"Test the asian barrier spread model.\"\"\"\n try:\n from qiskit.aqua.circuits import WeightedSumOperator, FixedValueComparator as Comparator\n from qiskit.aqua.components.uncertainty_problems import (\n UnivariatePiecewiseLinearObjective as PwlObjective,\n MultivariateProblem\n )\n from qiskit.aqua.components.uncertainty_models import MultivariateLogNormalDistribution\n except ImportError:\n import warnings\n warnings.warn('Qiskit Aqua is not installed, skipping the application test.')\n return\n\n # number of qubits per dimension to represent the uncertainty\n num_uncertainty_qubits = 2\n\n # parameters for considered random distribution\n spot_price = 2.0 # initial spot price\n volatility = 0.4 # volatility of 40%\n interest_rate = 0.05 # annual interest rate of 5%\n time_to_maturity = 40 / 365 # 40 days to maturity\n\n # resulting parameters for log-normal distribution\n # pylint: disable=invalid-name\n mu = ((interest_rate - 0.5 * volatility**2) * time_to_maturity + np.log(spot_price))\n sigma = volatility * np.sqrt(time_to_maturity)\n mean = np.exp(mu + sigma**2/2)\n variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)\n stddev = np.sqrt(variance)\n\n # lowest and highest value considered for the spot price; in between,\n # an equidistant discretization is considered.\n low = np.maximum(0, mean - 3*stddev)\n high = mean + 3*stddev\n\n # map to higher dimensional distribution\n # for simplicity assuming dimensions are independent and identically distributed)\n dimension = 2\n num_qubits = [num_uncertainty_qubits]*dimension\n low = low * np.ones(dimension)\n high = high * np.ones(dimension)\n mu = mu * np.ones(dimension)\n cov = sigma ** 2 * np.eye(dimension)\n\n # construct circuit factory\n distribution = MultivariateLogNormalDistribution(num_qubits=num_qubits,\n low=low,\n high=high,\n mu=mu,\n cov=cov)\n\n # determine number of qubits required to represent total loss\n weights = []\n for n in num_qubits:\n for i in range(n):\n weights += [2**i]\n\n num_sum_qubits = WeightedSumOperator.get_required_sum_qubits(weights)\n\n # create circuit factoy\n agg = WeightedSumOperator(sum(num_qubits), weights)\n\n # set the strike price (should be within the low and the high value of the uncertainty)\n strike_price_1 = 3\n strike_price_2 = 4\n\n # set the barrier threshold\n barrier = 2.5\n\n # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}\n max_value = 2**num_sum_qubits - 1\n low_ = low[0]\n high_ = high[0]\n\n mapped_strike_price_1 = (strike_price_1 - dimension*low_) / \\\n (high_ - low_) * (2**num_uncertainty_qubits - 1)\n mapped_strike_price_2 = (strike_price_2 - dimension*low_) / \\\n (high_ - low_) * (2**num_uncertainty_qubits - 1)\n mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)\n\n conditions = []\n for i in range(dimension):\n # target dimension of random distribution and corresponding condition\n conditions += [(i, Comparator(num_qubits[i], mapped_barrier[i] + 1, geq=False))]\n\n # set the approximation scaling for the payoff function\n c_approx = 0.25\n\n # setup piecewise linear objective fcuntion\n breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]\n slopes = [0, 1, 0]\n offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]\n f_min = 0\n f_max = mapped_strike_price_2 - mapped_strike_price_1\n bull_spread_objective = PwlObjective(\n num_sum_qubits, 0, max_value, breakpoints, slopes, offsets, f_min, f_max, c_approx)\n\n # define overall multivariate problem\n asian_barrier_spread = MultivariateProblem(\n distribution, agg, bull_spread_objective, conditions=conditions)\n\n num_req_qubits = asian_barrier_spread.num_target_qubits\n num_req_ancillas = asian_barrier_spread.required_ancillas()\n\n qr = QuantumRegister(num_req_qubits, name='q')\n qr_ancilla = QuantumRegister(num_req_ancillas, name='q_a')\n qc = QuantumCircuit(qr, qr_ancilla)\n\n asian_barrier_spread.build(qc, qr, qr_ancilla)\n job = execute(qc, backend=BasicAer.get_backend('statevector_simulator'))\n\n # evaluate resulting statevector\n value = 0\n for i, amplitude in enumerate(job.result().get_statevector()):\n b = ('{0:0%sb}' % asian_barrier_spread.num_target_qubits).format(\n i)[-asian_barrier_spread.num_target_qubits:]\n prob = np.abs(amplitude)**2\n if prob > 1e-4 and b[0] == '1':\n value += prob\n # all other states should have zero probability due to ancilla qubits\n if i > 2**num_req_qubits:\n break\n\n # map value to original range\n mapped_value = asian_barrier_spread.value_to_estimation(\n value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)\n expected = 0.83188\n self.assertAlmostEqual(mapped_value, expected, places=5)\n\n\n@ddt\nclass TestWeightedAdder(QiskitTestCase):\n \"\"\"Test the weighted adder circuit.\"\"\"\n\n def assertSummationIsCorrect(self, adder):\n \"\"\"Assert that ``adder`` correctly implements the summation w.r.t. its set weights.\"\"\"\n\n circuit = QuantumCircuit(adder.num_qubits)\n circuit.h(list(range(adder.num_state_qubits)))\n circuit.append(adder.to_instruction(), list(range(adder.num_qubits)))\n\n backend = BasicAer.get_backend('statevector_simulator')\n statevector = execute(circuit, backend).result().get_statevector()\n\n probabilities = defaultdict(float)\n for i, statevector_amplitude in enumerate(statevector):\n i = bin(i)[2:].zfill(circuit.num_qubits)[adder.num_ancilla_qubits:]\n probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)\n\n expectations = defaultdict(float)\n for x in range(2**adder.num_state_qubits):\n bits = np.array(list(bin(x)[2:].zfill(adder.num_state_qubits)), dtype=int)\n summation = bits.dot(adder.weights[::-1])\n\n entry = bin(summation)[2:].zfill(adder.num_sum_qubits) \\\n + bin(x)[2:].zfill(adder.num_state_qubits)\n expectations[entry] = 1 / 2 ** adder.num_state_qubits\n\n for state, probability in probabilities.items():\n self.assertAlmostEqual(probability, expectations[state])\n\n @data(\n [0],\n [1, 2, 1],\n [4],\n )\n def test_summation(self, weights):\n \"\"\"Test the weighted adder on some examples.\"\"\"\n adder = WeightedAdder(len(weights), weights)\n self.assertSummationIsCorrect(adder)\n\n def test_mutability(self):\n \"\"\"Test the mutability of the weighted adder.\"\"\"\n adder = WeightedAdder()\n\n with self.subTest(msg='missing number of state qubits'):\n with self.assertRaises(AttributeError):\n print(adder.draw())\n\n with self.subTest(msg='default weights'):\n adder.num_state_qubits = 3\n default_weights = 3 * [1]\n self.assertListEqual(adder.weights, default_weights)\n\n with self.subTest(msg='specify weights'):\n adder.weights = [3, 2, 1]\n self.assertSummationIsCorrect(adder)\n\n with self.subTest(msg='mismatching number of state qubits and weights'):\n with self.assertRaises(ValueError):\n adder.weights = [0, 1, 2, 3]\n print(adder.draw())\n\n with self.subTest(msg='change all attributes'):\n adder.num_state_qubits = 4\n adder.weights = [2, 0, 1, 1]\n self.assertSummationIsCorrect(adder)\n\n\n@ddt\nclass TestMCMT(QiskitTestCase):\n \"\"\"Test the multi-controlled multi-target circuit.\"\"\"\n\n @data(MCMT, MCMTVChain)\n def test_mcmt_as_normal_control(self, mcmt_class):\n \"\"\"Test that the MCMT can act as normal control gate.\"\"\"\n qc = QuantumCircuit(2)\n mcmt = mcmt_class(gate=CHGate(), num_ctrl_qubits=1, num_target_qubits=1)\n qc = qc.compose(mcmt, [0, 1])\n\n ref = QuantumCircuit(2)\n ref.ch(0, 1)\n\n self.assertEqual(qc, ref)\n\n def test_missing_qubits(self):\n \"\"\"Test that an error is raised if qubits are missing.\"\"\"\n with self.subTest(msg='no control qubits'):\n with self.assertRaises(AttributeError):\n _ = MCMT(XGate(), num_ctrl_qubits=0, num_target_qubits=1)\n\n with self.subTest(msg='no target qubits'):\n with self.assertRaises(AttributeError):\n _ = MCMT(ZGate(), num_ctrl_qubits=4, num_target_qubits=0)\n\n def test_different_gate_types(self):\n \"\"\"Test the different supported input types for the target gate.\"\"\"\n x_circ = QuantumCircuit(1)\n x_circ.x(0)\n for input_gate in [x_circ, QuantumCircuit.cx, QuantumCircuit.x, 'cx', 'x', CXGate()]:\n with self.subTest(input_gate=input_gate):\n mcmt = MCMT(input_gate, 2, 2)\n if isinstance(input_gate, QuantumCircuit):\n self.assertEqual(mcmt.gate.definition[0][0], XGate())\n self.assertEqual(len(mcmt.gate.definition), 1)\n else:\n self.assertEqual(mcmt.gate, XGate())\n\n def test_mcmt_v_chain_ancilla_test(self):\n \"\"\"Test too few and too many ancillas for the MCMT V-chain mode.\"\"\"\n with self.subTest(msg='insufficient number of ancillas on gate'):\n qc = QuantumCircuit(5)\n mcmt = MCMTVChain(ZGate(), 3, 1)\n with self.assertRaises(QiskitError):\n qc.append(mcmt, [0, 1, 2, 3, 4])\n\n with self.subTest(msg='insufficient number of ancillas on method'):\n qc = QuantumCircuit(5)\n mcmt = MCMTVChain(ZGate(), 3, 1)\n with self.assertRaises(QiskitError):\n qc.append(mcmt, [0, 1, 2, 3, 4], [])\n\n with self.subTest(msg='too many ancillas works on method'):\n qc = QuantumCircuit(8)\n qc.mcmt(CZGate(), [0, 1, 2], 3, [4, 5, 6, 7])\n\n @data(\n [CZGate(), 1, 1], [CHGate(), 1, 1],\n [CZGate(), 3, 3], [CHGate(), 3, 3],\n [CZGate(), 1, 5], [CHGate(), 1, 5],\n [CZGate(), 5, 1], [CHGate(), 5, 1],\n )\n @unpack\n def test_mcmt_v_chain_simulation(self, cgate, num_controls, num_targets):\n \"\"\"Test the MCMT V-chain implementation test on a simulation.\"\"\"\n controls = QuantumRegister(num_controls)\n targets = QuantumRegister(num_targets)\n\n subsets = [tuple(range(i)) for i in range(num_controls + 1)]\n for subset in subsets:\n qc = QuantumCircuit(targets, controls)\n # Initialize all targets to 1, just to be sure that\n # the generic gate has some effect (f.e. Z gate has no effect\n # on a 0 state)\n qc.x(targets)\n\n num_ancillas = max(0, num_controls - 1)\n\n if num_ancillas > 0:\n ancillas = QuantumRegister(num_ancillas)\n qc.add_register(ancillas)\n qubits = controls[:] + targets[:] + ancillas[:]\n else:\n qubits = controls[:] + targets[:]\n\n for i in subset:\n qc.x(controls[i])\n\n mcmt = MCMTVChain(cgate, num_controls, num_targets)\n qc.compose(mcmt, qubits, inplace=True)\n\n for i in subset:\n qc.x(controls[i])\n\n vec = Statevector.from_label('0' * qc.num_qubits).evolve(qc)\n\n # target register is initially |11...1>, with length equal to 2**(n_targets)\n vec_exp = np.array([0] * (2**(num_targets) - 1) + [1])\n\n if isinstance(cgate, CZGate):\n # Z gate flips the last qubit only if it's applied an odd number of times\n if len(subset) == num_controls and (num_controls % 2) == 1:\n vec_exp[-1] = -1\n elif isinstance(cgate, CHGate):\n # if all the control qubits have been activated,\n # we repeatedly apply the kronecker product of the Hadamard\n # with itself and then multiply the results for the original\n # state of the target qubits\n if len(subset) == num_controls:\n h_i = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]])\n h_tot = np.array([1])\n for _ in range(num_targets):\n h_tot = np.kron(h_tot, h_i)\n vec_exp = np.dot(h_tot, vec_exp)\n else:\n raise ValueError('Test not implement for gate: {}'.format(cgate))\n\n # append the remaining part of the state\n vec_exp = np.concatenate(\n (vec_exp,\n [0] * (2**(num_controls + num_ancillas + num_targets) - vec_exp.size))\n )\n f_i = state_fidelity(vec, vec_exp)\n self.assertAlmostEqual(f_i, 1)\n\n\n@ddt\nclass TestNLocal(QiskitTestCase):\n \"\"\"Test the n-local circuit class.\"\"\"\n\n def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):\n \"\"\"An equality test specialized to circuits.\"\"\"\n if transpiled:\n basis_gates = ['id', 'u1', 'u3', 'cx']\n qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)\n qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)\n qc1, qc2 = qc1_transpiled, qc2_transpiled\n\n if visual:\n self.assertEqual(qc1.draw(), qc2.draw())\n else:\n self.assertEqual(qc1, qc2)\n\n def test_empty_nlocal(self):\n \"\"\"Test the creation of an empty NLocal.\"\"\"\n nlocal = NLocal()\n self.assertEqual(nlocal.num_qubits, 0)\n self.assertEqual(nlocal.num_parameters_settable, 0)\n self.assertEqual(nlocal.reps, 1)\n\n self.assertEqual(nlocal, QuantumCircuit())\n\n for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]:\n self.assertEqual(len(attribute), 0)\n\n @data(\n (XGate(), [[0], [2], [1]]),\n (XGate(), [[0]]),\n (CRXGate(-0.2), [[2, 0], [1, 3]]),\n )\n @unpack\n def test_add_layer_to_empty_nlocal(self, block, entangler_map):\n \"\"\"Test appending gates to an empty nlocal.\"\"\"\n nlocal = NLocal()\n nlocal.add_layer(block, entangler_map)\n\n max_num_qubits = max(max(indices) for indices in entangler_map)\n reference = QuantumCircuit(max_num_qubits + 1)\n for indices in entangler_map:\n reference.append(block, indices)\n\n self.assertCircuitEqual(nlocal, reference)\n\n @data(\n [5, 3], [1, 5], [1, 1], [1, 2, 3, 10],\n )\n def test_append_circuit(self, num_qubits):\n \"\"\"Test appending circuits to an nlocal works normally.\"\"\"\n # fixed depth of 3 gates per circuit\n depth = 3\n\n # keep track of a reference circuit\n reference = QuantumCircuit(max(num_qubits))\n\n # construct the NLocal from the first circuit\n first_circuit = random_circuit(num_qubits[0], depth)\n # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate\n nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)\n reference.append(first_circuit, list(range(num_qubits[0])))\n\n # append the rest\n for num in num_qubits[1:]:\n circuit = random_circuit(num, depth)\n nlocal.append(circuit, list(range(num)))\n reference.append(circuit, list(range(num)))\n\n self.assertCircuitEqual(nlocal, reference)\n\n @data(\n [5, 3], [1, 5], [1, 1], [1, 2, 3, 10],\n )\n def test_add_nlocal(self, num_qubits):\n \"\"\"Test adding an nlocal to an nlocal (using add_layer).\"\"\"\n # fixed depth of 3 gates per circuit\n depth = 3\n\n # keep track of a reference circuit\n reference = QuantumCircuit(max(num_qubits))\n\n # construct the NLocal from the first circuit\n first_circuit = random_circuit(num_qubits[0], depth)\n # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate\n nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)\n reference.append(first_circuit, list(range(num_qubits[0])))\n\n # append the rest\n for num in num_qubits[1:]:\n circuit = random_circuit(num, depth)\n nlocal.add_layer(NLocal(num, entanglement_blocks=circuit, reps=1))\n reference.append(circuit, list(range(num)))\n\n self.assertCircuitEqual(nlocal, reference)\n\n @unittest.skip('Feature missing')\n def test_iadd_overload(self):\n \"\"\"Test the overloaded + operator.\"\"\"\n num_qubits, depth = 2, 2\n\n # construct two circuits for adding\n first_circuit = random_circuit(num_qubits, depth)\n circuit = random_circuit(num_qubits, depth)\n\n # get a reference\n reference = first_circuit + circuit\n\n # convert the object to be appended to different types\n others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)]\n\n # try adding each type\n for other in others:\n nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1)\n nlocal += other\n with self.subTest(msg='type: {}'.format(type(other))):\n self.assertCircuitEqual(nlocal, reference)\n\n def test_parameter_getter_from_automatic_repetition(self):\n \"\"\"Test getting and setting of the nlocal parameters.\"\"\"\n circuit = QuantumCircuit(2)\n circuit.ry(Parameter('a'), 0)\n circuit.crx(Parameter('b'), 0, 1)\n\n # repeat circuit and check that parameters are duplicated\n reps = 3\n nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)\n self.assertTrue(nlocal.num_parameters, 6)\n self.assertTrue(len(nlocal.parameters), 6)\n\n @data(list(range(6)), ParameterVector('θ', length=6), [0, 1, Parameter('theta'), 3, 4, 5])\n def test_parameter_setter_from_automatic_repetition(self, params):\n \"\"\"Test getting and setting of the nlocal parameters.\"\"\"\n circuit = QuantumCircuit(2)\n circuit.ry(Parameter('a'), 0)\n circuit.crx(Parameter('b'), 0, 1)\n\n # repeat circuit and check that parameters are duplicated\n reps = 3\n nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)\n nlocal.assign_parameters(params, inplace=True)\n\n param_set = set(p for p in params if isinstance(p, ParameterExpression))\n with self.subTest(msg='Test the parameters of the non-transpiled circuit'):\n # check the parameters of the final circuit\n self.assertEqual(nlocal.parameters, param_set)\n\n with self.subTest(msg='Test the parameters of the transpiled circuit'):\n basis_gates = ['id', 'u1', 'u2', 'u3', 'cx']\n transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)\n self.assertEqual(transpiled_circuit.parameters, param_set)\n\n @data(list(range(6)), ParameterVector('θ', length=6), [0, 1, Parameter('theta'), 3, 4, 5])\n def test_parameters_setter(self, params):\n \"\"\"Test setting the parameters via list.\"\"\"\n # construct circuit with some parameters\n initial_params = ParameterVector('p', length=6)\n circuit = QuantumCircuit(1)\n for i, initial_param in enumerate(initial_params):\n circuit.ry(i * initial_param, 0)\n\n # create an NLocal from the circuit and set the new parameters\n nlocal = NLocal(1, entanglement_blocks=circuit, reps=1)\n nlocal.assign_parameters(params, inplace=True)\n\n param_set = set(p for p in params if isinstance(p, ParameterExpression))\n with self.subTest(msg='Test the parameters of the non-transpiled circuit'):\n # check the parameters of the final circuit\n self.assertEqual(nlocal.parameters, param_set)\n\n with self.subTest(msg='Test the parameters of the transpiled circuit'):\n basis_gates = ['id', 'u1', 'u2', 'u3', 'cx']\n transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)\n self.assertEqual(transpiled_circuit.parameters, param_set)\n\n def test_repetetive_parameter_setting(self):\n \"\"\"Test alternate setting of parameters and circuit construction.\"\"\"\n x = Parameter('x')\n circuit = QuantumCircuit(1)\n circuit.rx(x, 0)\n\n nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True)\n with self.subTest(msg='immediately after initialization'):\n self.assertEqual(len(nlocal.parameters), 3)\n\n with self.subTest(msg='after circuit construction'):\n self.assertEqual(len(nlocal.parameters), 3)\n\n q = Parameter('q')\n nlocal.assign_parameters([x, q, q], inplace=True)\n with self.subTest(msg='setting parameter to Parameter objects'):\n self.assertEqual(nlocal.parameters, set({x, q}))\n\n nlocal.assign_parameters([0, -1], inplace=True)\n with self.subTest(msg='setting parameter to numbers'):\n self.assertEqual(nlocal.parameters, set())\n\n def test_skip_unentangled_qubits(self):\n \"\"\"Test skipping the unentangled qubits.\"\"\"\n num_qubits = 6\n entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]]\n skipped_1 = [2, 4]\n\n entanglement_2 = [\n entanglement_1,\n [[0, 1, 2], [2, 3, 5]]\n ]\n skipped_2 = [4]\n\n for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]):\n with self.subTest(entanglement=entanglement, skipped=skipped):\n nlocal = NLocal(num_qubits, rotation_blocks=XGate(), entanglement_blocks=CCXGate(),\n entanglement=entanglement, reps=3, skip_unentangled_qubits=True)\n\n skipped_set = set(nlocal.qubits[i] for i in skipped)\n dag = circuit_to_dag(nlocal)\n idle = set(dag.idle_wires())\n self.assertEqual(skipped_set, idle)\n\n @data('linear', 'full', 'circular', 'sca',\n ['linear', 'full'],\n ['circular', 'linear', 'sca']\n )\n def test_entanglement_by_str(self, entanglement):\n \"\"\"Test setting the entanglement of the layers by str.\"\"\"\n reps = 3\n nlocal = NLocal(5, rotation_blocks=XGate(), entanglement_blocks=CCXGate(),\n entanglement=entanglement, reps=reps)\n\n def get_expected_entangler_map(rep_num, mode):\n if mode == 'linear':\n return [(0, 1, 2), (1, 2, 3), (2, 3, 4)]\n elif mode == 'full':\n return [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4),\n (1, 2, 3), (1, 2, 4), (1, 3, 4),\n (2, 3, 4)]\n else:\n circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)]\n if mode == 'circular':\n return circular\n sca = circular[-rep_num:] + circular[:-rep_num]\n if rep_num % 2 == 1:\n sca = [tuple(reversed(indices)) for indices in sca]\n return sca\n\n for rep_num in range(reps):\n entangler_map = nlocal.get_entangler_map(rep_num, 0, 3)\n if isinstance(entanglement, list):\n mode = entanglement[rep_num % len(entanglement)]\n else:\n mode = entanglement\n expected = get_expected_entangler_map(rep_num, mode)\n\n with self.subTest(rep_num=rep_num):\n # using a set here since the order does not matter\n self.assertEqual(set(entangler_map), set(expected))\n\n def test_entanglement_by_list(self):\n \"\"\"Test setting the entanglement by list.\n\n This is the circuit we test (times 2, with final X layer)\n ┌───┐ ┌───┐┌───┐ ┌───┐\n q_0: |0>┤ X ├──■────■───X────┤ X ├┤ X ├──■───X─────── .. ┤ X ├\n ├───┤ │ │ │ ├───┤└─┬─┘ │ │ ├───┤\n q_1: |0>┤ X ├──■────┼───┼──X─┤ X ├──■────┼───X──X──── .. ┤ X ├\n ├───┤┌─┴─┐ │ │ │ ├───┤ │ │ │ x2 ├───┤\n q_2: |0>┤ X ├┤ X ├──■───┼──X─┤ X ├──■────■──────X──X─ .. ┤ X ├\n ├───┤└───┘┌─┴─┐ │ ├───┤ ┌─┴─┐ │ ├───┤\n q_3: |0>┤ X ├─────┤ X ├─X────┤ X ├─────┤ X ├───────X─ .. ┤ X ├\n └───┘ └───┘ └───┘ └───┘ └───┘\n \"\"\"\n circuit = QuantumCircuit(4)\n for _ in range(2):\n circuit.x([0, 1, 2, 3])\n circuit.barrier()\n circuit.ccx(0, 1, 2)\n circuit.ccx(0, 2, 3)\n circuit.swap(0, 3)\n circuit.swap(1, 2)\n circuit.barrier()\n circuit.x([0, 1, 2, 3])\n circuit.barrier()\n circuit.ccx(2, 1, 0)\n circuit.ccx(0, 2, 3)\n circuit.swap(0, 1)\n circuit.swap(1, 2)\n circuit.swap(2, 3)\n circuit.barrier()\n circuit.x([0, 1, 2, 3])\n\n layer_1_ccx = [(0, 1, 2), (0, 2, 3)]\n layer_1_swap = [(0, 3), (1, 2)]\n layer_1 = [layer_1_ccx, layer_1_swap]\n\n layer_2_ccx = [(2, 1, 0), (0, 2, 3)]\n layer_2_swap = [(0, 1), (1, 2), (2, 3)]\n layer_2 = [layer_2_ccx, layer_2_swap]\n\n entanglement = [layer_1, layer_2]\n\n nlocal = NLocal(4, rotation_blocks=XGate(), entanglement_blocks=[CCXGate(), SwapGate()],\n reps=4, entanglement=entanglement, insert_barriers=True)\n\n self.assertCircuitEqual(nlocal, circuit)\n\n\n@ddt\nclass TestTwoLocal(QiskitTestCase):\n \"\"\"Tests for the TwoLocal circuit.\"\"\"\n\n def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):\n \"\"\"An equality test specialized to circuits.\"\"\"\n if transpiled:\n basis_gates = ['id', 'u1', 'u3', 'cx']\n qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)\n qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)\n qc1, qc2 = qc1_transpiled, qc2_transpiled\n\n if visual:\n self.assertEqual(qc1.draw(), qc2.draw())\n else:\n self.assertEqual(qc1, qc2)\n\n def test_skip_final_rotation_layer(self):\n \"\"\"Test skipping the final rotation layer works.\"\"\"\n two = TwoLocal(3, ['ry', 'h'], ['cz', 'cx'], reps=2, skip_final_rotation_layer=True)\n self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer\n\n @data(\n (5, 'rx', 'cx', 'full', 2, 15),\n (3, 'x', 'z', 'linear', 1, 0),\n (3, ['rx', 'ry'], ['cry', 'cx'], 'circular', 2, 24)\n )\n @unpack\n def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected):\n \"\"\"Test the number of parameters.\"\"\"\n two = TwoLocal(num_qubits, rotation_blocks=rot, entanglement_blocks=ent,\n entanglement=ent_mode, reps=reps)\n\n with self.subTest(msg='num_parameters_settable'):\n self.assertEqual(two.num_parameters_settable, expected)\n\n with self.subTest(msg='num_parameters'):\n self.assertEqual(two.num_parameters, expected)\n\n def test_empty_two_local(self):\n \"\"\"Test the setup of an empty two-local circuit.\"\"\"\n two = TwoLocal()\n\n with self.subTest(msg='0 qubits'):\n self.assertEqual(two.num_qubits, 0)\n\n with self.subTest(msg='no blocks are set'):\n self.assertListEqual(two.rotation_blocks, [])\n self.assertListEqual(two.entanglement_blocks, [])\n\n with self.subTest(msg='equal to empty circuit'):\n self.assertEqual(two, QuantumCircuit())\n\n @data('rx', RXGate(Parameter('p')), RXGate, 'circuit')\n def test_various_block_types(self, rot):\n \"\"\"Test setting the rotation blocks to various type and assert the output type is RX.\"\"\"\n if rot == 'circuit':\n rot = QuantumCircuit(1)\n rot.rx(Parameter('angle'), 0)\n\n two = TwoLocal(3, rot, 'cz', reps=1)\n self.assertEqual(len(two.rotation_blocks), 1)\n rotation = two.rotation_blocks[0]\n\n # decompose\n self.assertIsInstance(rotation.data[0][0], RXGate)\n\n def test_parameter_setters(self):\n \"\"\"Test different possibilities to set parameters.\"\"\"\n two = TwoLocal(3, rotation_blocks='rx', entanglement='cz', reps=2)\n params = [0, 1, 2, Parameter('x'), Parameter('y'), Parameter('z'), 6, 7, 0]\n params_set = set(param for param in params if isinstance(param, Parameter))\n\n with self.subTest(msg='dict assign and copy'):\n ordered = two.ordered_parameters\n bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False)\n self.assertEqual(bound.parameters, params_set)\n self.assertEqual(two.num_parameters, 9)\n\n with self.subTest(msg='list assign and copy'):\n ordered = two.ordered_parameters\n bound = two.assign_parameters(params, inplace=False)\n self.assertEqual(bound.parameters, params_set)\n self.assertEqual(two.num_parameters, 9)\n\n with self.subTest(msg='list assign inplace'):\n ordered = two.ordered_parameters\n two.assign_parameters(params, inplace=True)\n self.assertEqual(two.parameters, params_set)\n self.assertEqual(two.num_parameters, 3)\n self.assertEqual(two.num_parameters_settable, 9)\n\n def test_parameters_settable_is_constant(self):\n \"\"\"Test the attribute num_parameters_settable does not change on parameter change.\"\"\"\n two = TwoLocal(3, rotation_blocks='rx', entanglement='cz', reps=2)\n ordered_params = two.ordered_parameters\n\n x = Parameter('x')\n two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True)\n\n with self.subTest(msg='num_parameters collapsed to 1'):\n self.assertEqual(two.num_parameters, 1)\n\n with self.subTest(msg='num_parameters_settable remained constant'):\n self.assertEqual(two.num_parameters_settable, len(ordered_params))\n\n def test_iadd_to_circuit(self):\n \"\"\"Test adding a two-local to an existing circuit.\"\"\"\n two = TwoLocal(3, ['ry', 'rz'], 'cz', 'full', reps=1, insert_barriers=True)\n circuit = QuantumCircuit(3)\n circuit += two\n\n reference = QuantumCircuit(3)\n param_iter = iter(two.ordered_parameters)\n for i in range(3):\n reference.ry(next(param_iter), i)\n for i in range(3):\n reference.rz(next(param_iter), i)\n reference.barrier()\n reference.cz(0, 1)\n reference.cz(0, 2)\n reference.cz(1, 2)\n reference.barrier()\n for i in range(3):\n reference.ry(next(param_iter), i)\n for i in range(3):\n reference.rz(next(param_iter), i)\n\n self.assertCircuitEqual(circuit, reference)\n\n def test_adding_two(self):\n \"\"\"Test adding two two-local circuits.\"\"\"\n entangler_map = [[0, 3], [0, 2]]\n two = TwoLocal(4, [], 'cry', entangler_map, reps=1)\n circuit = two + two\n\n reference = QuantumCircuit(4)\n params = two.ordered_parameters\n for _ in range(2):\n reference.cry(params[0], 0, 3)\n reference.cry(params[1], 0, 2)\n\n self.assertCircuitEqual(reference, circuit)\n\n def test_ry_blocks(self):\n \"\"\"Test that the RealAmplitudes circuit is instantiated correctly.\"\"\"\n two = RealAmplitudes(4)\n with self.subTest(msg='test rotation gate'):\n self.assertEqual(len(two.rotation_blocks), 1)\n self.assertIsInstance(two.rotation_blocks[0].data[0][0], RYGate)\n\n with self.subTest(msg='test parameter bounds'):\n expected = [(-np.pi, np.pi)] * two.num_parameters\n np.testing.assert_almost_equal(two.parameter_bounds, expected)\n\n def test_ry_circuit(self):\n \"\"\"Test an RealAmplitudes circuit.\"\"\"\n num_qubits = 3\n reps = 2\n entanglement = 'full'\n parameters = ParameterVector('theta', num_qubits * (reps + 1))\n param_iter = iter(parameters)\n\n expected = QuantumCircuit(3)\n for _ in range(reps):\n for i in range(num_qubits):\n expected.ry(next(param_iter), i)\n expected.cx(0, 1)\n expected.cx(0, 2)\n expected.cx(1, 2)\n for i in range(num_qubits):\n expected.ry(next(param_iter), i)\n\n library = RealAmplitudes(num_qubits, reps=reps,\n entanglement=entanglement).assign_parameters(parameters)\n\n self.assertCircuitEqual(library, expected)\n\n def test_ryrz_blocks(self):\n \"\"\"Test that the EfficientSU2 circuit is instantiated correctly.\"\"\"\n two = EfficientSU2(3)\n with self.subTest(msg='test rotation gate'):\n self.assertEqual(len(two.rotation_blocks), 2)\n self.assertIsInstance(two.rotation_blocks[0].data[0][0], RYGate)\n self.assertIsInstance(two.rotation_blocks[1].data[0][0], RZGate)\n\n with self.subTest(msg='test parameter bounds'):\n expected = [(-np.pi, np.pi)] * two.num_parameters\n np.testing.assert_almost_equal(two.parameter_bounds, expected)\n\n def test_ryrz_circuit(self):\n \"\"\"Test an EfficientSU2 circuit.\"\"\"\n num_qubits = 3\n reps = 2\n entanglement = 'circular'\n parameters = ParameterVector('theta', 2 * num_qubits * (reps + 1))\n param_iter = iter(parameters)\n\n expected = QuantumCircuit(3)\n for _ in range(reps):\n for i in range(num_qubits):\n expected.ry(next(param_iter), i)\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n expected.cx(2, 0)\n expected.cx(0, 1)\n expected.cx(1, 2)\n for i in range(num_qubits):\n expected.ry(next(param_iter), i)\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n\n library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters(\n parameters\n )\n\n self.assertCircuitEqual(library, expected)\n\n def test_swaprz_blocks(self):\n \"\"\"Test that the ExcitationPreserving circuit is instantiated correctly.\"\"\"\n two = ExcitationPreserving(5)\n with self.subTest(msg='test rotation gate'):\n self.assertEqual(len(two.rotation_blocks), 1)\n self.assertIsInstance(two.rotation_blocks[0].data[0][0], RZGate)\n\n with self.subTest(msg='test entanglement gate'):\n self.assertEqual(len(two.entanglement_blocks), 1)\n block = two.entanglement_blocks[0]\n self.assertEqual(len(block.data), 2)\n self.assertIsInstance(block.data[0][0], RXXGate)\n self.assertIsInstance(block.data[1][0], RYYGate)\n\n with self.subTest(msg='test parameter bounds'):\n expected = [(-np.pi, np.pi)] * two.num_parameters\n np.testing.assert_almost_equal(two.parameter_bounds, expected)\n\n def test_swaprz_circuit(self):\n \"\"\"Test a ExcitationPreserving circuit in iswap mode.\"\"\"\n num_qubits = 3\n reps = 2\n entanglement = 'linear'\n parameters = ParameterVector('theta', num_qubits * (reps + 1) + reps * (num_qubits - 1))\n param_iter = iter(parameters)\n\n expected = QuantumCircuit(3)\n for _ in range(reps):\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n shared_param = next(param_iter)\n expected.rxx(shared_param, 0, 1)\n expected.ryy(shared_param, 0, 1)\n shared_param = next(param_iter)\n expected.rxx(shared_param, 1, 2)\n expected.ryy(shared_param, 1, 2)\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n\n library = ExcitationPreserving(num_qubits, reps=reps,\n entanglement=entanglement).assign_parameters(parameters)\n\n self.assertCircuitEqual(library, expected)\n\n def test_fsim_circuit(self):\n \"\"\"Test a ExcitationPreserving circuit in fsim mode.\"\"\"\n num_qubits = 3\n reps = 2\n entanglement = 'linear'\n # need the parameters in the entanglement blocks to be the same because the order\n # can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits)\n parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits))\n param_iter = iter(parameters)\n\n expected = QuantumCircuit(3)\n for _ in range(reps):\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n shared_param = next(param_iter)\n expected.rxx(shared_param, 0, 1)\n expected.ryy(shared_param, 0, 1)\n expected.cu1(next(param_iter), 0, 1)\n shared_param = next(param_iter)\n expected.rxx(shared_param, 1, 2)\n expected.ryy(shared_param, 1, 2)\n expected.cu1(next(param_iter), 1, 2)\n for i in range(num_qubits):\n expected.rz(next(param_iter), i)\n\n library = ExcitationPreserving(num_qubits, reps=reps, mode='fsim',\n entanglement=entanglement).assign_parameters(parameters)\n\n self.assertCircuitEqual(library, expected)\n\n\n@ddt\nclass TestDataEncoding(QiskitTestCase):\n \"\"\"Test the data encoding circuits.\"\"\"\n\n def test_pauli_empty(self):\n \"\"\"Test instantiating an empty Pauli expansion.\"\"\"\n encoding = PauliFeatureMap()\n\n with self.subTest(msg='equal to empty circuit'):\n self.assertTrue(Operator(encoding).equiv(QuantumCircuit()))\n\n with self.subTest(msg='rotation blocks is H gate'):\n self.assertEqual(len(encoding.rotation_blocks), 1)\n self.assertIsInstance(encoding.rotation_blocks[0].data[0][0], HGate)\n\n @data((2, 3, ['X', 'YY']), (5, 2, ['ZZZXZ', 'XZ']))\n @unpack\n def test_num_parameters(self, num_qubits, reps, pauli_strings):\n \"\"\"Test the number of parameters equals the number of qubits, independent of reps.\"\"\"\n encoding = PauliFeatureMap(num_qubits, paulis=pauli_strings, reps=reps)\n self.assertEqual(encoding.num_parameters, num_qubits)\n self.assertEqual(encoding.num_parameters_settable, num_qubits)\n\n def test_pauli_evolution(self):\n \"\"\"Test the generation of Pauli blocks.\"\"\"\n encoding = PauliFeatureMap()\n time = 1.4\n with self.subTest(pauli_string='ZZ'):\n evo = QuantumCircuit(2)\n evo.cx(0, 1)\n evo.u1(2 * time, 1)\n evo.cx(0, 1)\n\n pauli = encoding.pauli_evolution('ZZ', time)\n self.assertTrue(Operator(pauli).equiv(evo))\n\n with self.subTest(pauli_string='XYZ'):\n evo = QuantumCircuit(3)\n # X on the most-significant, bottom qubit, Z on the top\n evo.h(2)\n evo.rx(np.pi / 2, 1)\n evo.cx(0, 1)\n evo.cx(1, 2)\n evo.u1(2 * time, 2)\n evo.cx(1, 2)\n evo.cx(0, 1)\n evo.rx(-np.pi / 2, 1)\n evo.h(2)\n\n pauli = encoding.pauli_evolution('XYZ', time)\n self.assertTrue(Operator(pauli).equiv(evo))\n\n with self.subTest(pauli_string='I'):\n evo = QuantumCircuit(1)\n pauli = encoding.pauli_evolution('I', time)\n self.assertTrue(Operator(pauli).equiv(evo))\n\n def test_first_order_circuit(self):\n \"\"\"Test a first order expansion circuit.\"\"\"\n times = [0.2, 1, np.pi, -1.2]\n encoding = ZFeatureMap(4, reps=3).assign_parameters(times)\n\n ref = QuantumCircuit(4)\n for _ in range(3):\n ref.h([0, 1, 2, 3])\n for i in range(4):\n ref.u1(2 * times[i], i)\n\n self.assertTrue(Operator(encoding).equiv(ref))\n\n def test_second_order_circuit(self):\n \"\"\"Test a second order expansion circuit.\"\"\"\n times = [0.2, 1, np.pi]\n encoding = ZZFeatureMap(3, reps=2).assign_parameters(times)\n\n def zz_evolution(circuit, qubit1, qubit2):\n time = (np.pi - times[qubit1]) * (np.pi - times[qubit2])\n circuit.cx(qubit1, qubit2)\n circuit.u1(2 * time, qubit2)\n circuit.cx(qubit1, qubit2)\n\n ref = QuantumCircuit(3)\n for _ in range(2):\n ref.h([0, 1, 2])\n for i in range(3):\n ref.u1(2 * times[i], i)\n zz_evolution(ref, 0, 1)\n zz_evolution(ref, 0, 2)\n zz_evolution(ref, 1, 2)\n\n self.assertTrue(Operator(encoding).equiv(ref))\n\n\n@ddt\nclass TestDiagonalGate(QiskitTestCase):\n \"\"\"Test diagonal circuit.\"\"\"\n\n @data(\n [0, 0],\n [0, 0.8],\n [0, 0, 1, 1],\n [0, 1, 0.5, 1],\n (2 * np.pi * np.random.rand(2 ** 3)),\n (2 * np.pi * np.random.rand(2 ** 4)),\n (2 * np.pi * np.random.rand(2 ** 5))\n )\n def test_diag_gate(self, phases):\n \"\"\"Test correctness of diagonal decomposition.\"\"\"\n diag = [np.exp(1j * ph) for ph in phases]\n qc = Diagonal(diag)\n simulated_diag = Statevector(Operator(qc).data.diagonal())\n ref_diag = Statevector(diag)\n\n self.assertTrue(simulated_diag.equiv(ref_diag))\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"numpy.asarray",
"numpy.kron",
"numpy.all",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.any",
"numpy.exp",
"numpy.eye",
"numpy.testing.assert_almost_equal",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"numpy.isclose",
"numpy.log",
"numpy.random.rand",
"numpy.array",
"numpy.maximum",
"numpy.conj",
"numpy.abs",
"numpy.ones",
"numpy.empty"
]
] |
yannbouteiller/rlrd
|
[
"391925c2a243f602599b74c2a168b669a8233066"
] |
[
"rlrd/wrappers_rd.py"
] |
[
"from collections import deque\nfrom random import sample\nimport itertools\n\nimport gym\nfrom gym.spaces import Tuple, Discrete\n\nimport numpy as np\n\n\nclass RandomDelayWrapper(gym.Wrapper):\n \"\"\"\n Wrapper for any non-RTRL environment, modelling random observation and action delays\n NB: alpha refers to the abservation delay, it is >= 0\n NB: The state-space now contains two different action delays:\n kappa is such that alpha+kappa is the index of the first action that was going to be applied when the observation started being captured, it is useful for the model\n (when kappa==0, it means that the delay is actually 1)\n beta is such that alpha+beta is the index of the last action that is known to have influenced the observation, it is useful for credit assignment (e.g. AC/DC)\n (alpha+beta is often 1 step bigger than the action buffer, and it is always >= 1)\n Kwargs:\n obs_delay_range: range in which alpha is sampled\n act_delay_range: range in which kappa is sampled\n initial_action: action (default None): action with which the action buffer is filled at reset() (if None, sampled in the action space)\n \"\"\"\n\n def __init__(self, env, obs_delay_range=range(0, 8), act_delay_range=range(0, 2), initial_action=None, skip_initial_actions=False):\n super().__init__(env)\n self.wrapped_env = env\n self.obs_delay_range = obs_delay_range\n self.act_delay_range = act_delay_range\n\n self.observation_space = Tuple((\n env.observation_space, # most recent observation\n Tuple([env.action_space] * (obs_delay_range.stop + act_delay_range.stop - 1)), # action buffer\n Discrete(obs_delay_range.stop), # observation delay int64\n Discrete(act_delay_range.stop), # action delay int64\n ))\n\n self.initial_action = initial_action\n self.skip_initial_actions = skip_initial_actions\n self.past_actions = deque(maxlen=obs_delay_range.stop + act_delay_range.stop)\n self.past_observations = deque(maxlen=obs_delay_range.stop)\n self.arrival_times_actions = deque(maxlen=act_delay_range.stop)\n self.arrival_times_observations = deque(maxlen=obs_delay_range.stop)\n\n self.t = 0\n self.done_signal_sent = False\n self.next_action = None\n self.cum_rew_actor = 0.\n self.cum_rew_brain = 0.\n self.prev_action_idx = 0 # TODO : initialize this better\n\n def reset(self, **kwargs):\n self.cum_rew_actor = 0.\n self.cum_rew_brain = 0.\n self.prev_action_idx = 0 # TODO : initialize this better\n self.done_signal_sent = False\n first_observation = super().reset(**kwargs)\n\n # fill up buffers\n self.t = - (self.obs_delay_range.stop + self.act_delay_range.stop) # this is <= -2\n while self.t < 0:\n act = self.action_space.sample() if self.initial_action is None else self.initial_action\n self.send_action(act, init=True) # TODO : initialize this better\n self.send_observation((first_observation, 0., False, {}, 0, 1)) # TODO : initialize this better\n self.t += 1\n self.receive_action() # an action has to be applied\n\n assert self.t == 0\n received_observation, *_ = self.receive_observation()\n # print(\"DEBUG: end of reset ---\")\n # print(f\"DEBUG: self.past_actions:{self.past_actions}\")\n # print(f\"DEBUG: self.past_observations:{self.past_observations}\")\n # print(f\"DEBUG: self.arrival_times_actions:{self.arrival_times_actions}\")\n # print(f\"DEBUG: self.arrival_times_observations:{self.arrival_times_observations}\")\n # print(f\"DEBUG: self.t:{self.t}\")\n # print(\"DEBUG: ---\")\n return received_observation\n\n def step(self, action):\n \"\"\"\n When kappa is 0 and alpha is 0, this is equivalent to the RTRL setting\n (The inference time is NOT considered part of beta or kappa)\n \"\"\"\n\n # at the brain\n self.send_action(action)\n\n # at the remote actor\n if self.t < self.act_delay_range.stop and self.skip_initial_actions:\n # assert False, \"skip_initial_actions==True is not supported\"\n # do nothing until the brain's first actions arrive at the remote actor\n self.receive_action()\n elif self.done_signal_sent:\n # just resend the last observation until the brain gets it\n self.send_observation(self.past_observations[0])\n else:\n m, r, d, info = self.env.step(self.next_action) # before receive_action (e.g. rtrl setting with 0 delays)\n kappa, beta = self.receive_action()\n self.cum_rew_actor += r\n self.done_signal_sent = d\n self.send_observation((m, self.cum_rew_actor, d, info, kappa, beta))\n\n # at the brain again\n m, cum_rew_actor_delayed, d, info = self.receive_observation()\n r = cum_rew_actor_delayed - self.cum_rew_brain\n self.cum_rew_brain = cum_rew_actor_delayed\n\n self.t += 1\n\n # print(\"DEBUG: end of step ---\")\n # print(f\"DEBUG: self.past_actions:{self.past_actions}\")\n # print(f\"DEBUG: self.past_observations:{self.past_observations}\")\n # print(f\"DEBUG: self.arrival_times_actions:{self.arrival_times_actions}\")\n # print(f\"DEBUG: self.arrival_times_observations:{self.arrival_times_observations}\")\n # print(f\"DEBUG: self.t:{self.t}\")\n # print(\"DEBUG: ---\")\n return m, r, d, info\n\n def send_action(self, action, init=False):\n \"\"\"\n Appends action to the left of self.past_actions\n Simulates the time at which it will reach the agent and stores it on the left of self.arrival_times_actions\n \"\"\"\n # at the brain\n kappa, = sample(self.act_delay_range, 1) if not init else [0, ] # TODO: change this if we implement a different initialization\n self.arrival_times_actions.appendleft(self.t + kappa)\n self.past_actions.appendleft(action)\n\n def receive_action(self):\n \"\"\"\n Looks for the last created action that has arrived before t at the agent\n NB: since it is the most recently created action that the agent got, this is the one that is to be applied\n Returns:\n next_action_idx: int: the index of the action that is going to be applied\n prev_action_idx: int: the index of the action previously being applied (i.e. of the action that influenced the observation since it is retrieved instantaneously in usual Gym envs)\n \"\"\"\n # CAUTION: from the brain point of view, the \"previous action\"'s age (kappa_t) is not like the previous \"next action\"'s age (beta_{t-1}) (e.g. repeated observations)\n prev_action_idx = self.prev_action_idx + 1 # + 1 is to account for the fact that this was the right idx 1 time-step before\n next_action_idx = next(i for i, t in enumerate(self.arrival_times_actions) if t <= self.t)\n self.prev_action_idx = next_action_idx\n self.next_action = self.past_actions[next_action_idx]\n # print(f\"DEBUG: next_action_idx:{next_action_idx}, prev_action_idx:{prev_action_idx}\")\n return next_action_idx, prev_action_idx\n\n def send_observation(self, obs):\n \"\"\"\n Appends obs to the left of self.past_observations\n Simulates the time at which it will reach the brain and appends it in self.arrival_times_observations\n \"\"\"\n # at the remote actor\n alpha, = sample(self.obs_delay_range, 1)\n self.arrival_times_observations.appendleft(self.t + alpha)\n self.past_observations.appendleft(obs)\n\n def receive_observation(self):\n \"\"\"\n Looks for the last created observation at the agent/observer that reached the brain at time t\n NB: since this is the most recently created observation that the brain got, this is the one currently being considered as the last observation\n Returns:\n augmented_obs: tuple:\n m: object: last observation that reached the brain\n past_actions: tuple: the history of actions that the brain sent so far\n alpha: int: number of micro time steps it took the last observation to travel from the agent/observer to the brain\n kappa: int: action travel delay + number of micro time-steps for which the next action has been applied at the agent\n beta: int: action travel delay + number of micro time-steps for which the previous action has been applied at the agent\n r: float: delayed reward corresponding to the transition that created m\n d: bool: delayed done corresponding to the transition that created m\n info: dict: delayed info corresponding to the transition that created m\n \"\"\"\n # at the brain\n alpha = next(i for i, t in enumerate(self.arrival_times_observations) if t <= self.t)\n m, r, d, info, kappa, beta = self.past_observations[alpha]\n return (m, tuple(itertools.islice(self.past_actions, 0, self.past_actions.maxlen - 1)), alpha, kappa, beta), r, d, info\n\n\nclass UnseenRandomDelayWrapper(RandomDelayWrapper):\n \"\"\"\n Wrapper that translates the RandomDelayWrapper back to the usual RL setting\n Use this wrapper to see what happens to vanilla RL algorithms facing random delays\n \"\"\"\n\n def __init__(self, env, **kwargs):\n super().__init__(env, **kwargs)\n self.observation_space = env.observation_space\n\n def reset(self, **kwargs):\n t = super().reset(**kwargs) # t: (m, tuple(self.past_actions), alpha, kappa, beta)\n return t[0]\n\n def step(self, action):\n t, *aux = super().step(action) # t: (m, tuple(self.past_actions), alpha, kappa, beta)\n return (t[0], *aux)\n\n\ndef simple_wifi_sampler1():\n return np.random.choice([1, 2, 3, 4, 5, 6], p=[0.3082, 0.5927, 0.0829, 0.0075, 0.0031, 0.0056])\n\n\ndef simple_wifi_sampler2():\n return np.random.choice([1, 2, 3, 4], p=[0.3082, 0.5927, 0.0829, 0.0162])\n\n\nclass WifiDelayWrapper1(RandomDelayWrapper):\n \"\"\"\n Simple sampler built from a dataset of 10000 real-world wifi communications\n The atomic time-step is 0.02s\n All communication times above 0.1s have been clipped to 0.1s\n \"\"\"\n\n def __init__(self, env, initial_action=None, skip_initial_actions=False):\n super().__init__(env, obs_delay_range=range(0, 7), act_delay_range=range(0, 7), initial_action=initial_action, skip_initial_actions=skip_initial_actions)\n\n def send_observation(self, obs):\n # at the remote actor\n alpha = simple_wifi_sampler1()\n self.arrival_times_observations.appendleft(self.t + alpha)\n self.past_observations.appendleft(obs)\n\n def send_action(self, action, init=False):\n # at the brain\n kappa = simple_wifi_sampler1() if not init else 0 # TODO: change this if we implement a different initialization\n self.arrival_times_actions.appendleft(self.t + kappa)\n self.past_actions.appendleft(action)\n\n\nclass WifiDelayWrapper2(RandomDelayWrapper):\n \"\"\"\n Simple sampler built from a dataset of 10000 real-world wifi communications\n The atomic time-step is 0.02s\n All communication times above 0.1s have been clipped to 0.1s\n \"\"\"\n\n def __init__(self, env, initial_action=None, skip_initial_actions=False):\n super().__init__(env, obs_delay_range=range(0, 5), act_delay_range=range(0, 5), initial_action=initial_action, skip_initial_actions=skip_initial_actions)\n\n def send_observation(self, obs):\n # at the remote actor\n alpha = simple_wifi_sampler2()\n self.arrival_times_observations.appendleft(self.t + alpha)\n self.past_observations.appendleft(obs)\n\n def send_action(self, action, init=False):\n # at the brain\n kappa = simple_wifi_sampler2() if not init else 0 # TODO: change this if we implement a different initialization\n self.arrival_times_actions.appendleft(self.t + kappa)\n self.past_actions.appendleft(action)\n"
] |
[
[
"numpy.random.choice"
]
] |
timothyb0912/checkrs
|
[
"213ac39b5dccc0c38d984a66286174de070af00d"
] |
[
"src/checkrs/market.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nFunctions for plotting simulated vs observed market shares of each alternative.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sbn\n\nfrom .plot_utils import _label_despine_save_and_show_plot\nfrom .utils import progress\n\n\ndef _get_objects_for_market_share_plot(\n x, sim_y, obs_y, x_label, y_label, display_dict=None\n):\n \"\"\"\n Creates dataframes needed for the market share plot.\n\n Parameters\n ----------\n x : 1D ndarray.\n Should contain the values of the discrete random value for each\n alternative for each observation.\n sim_y : 2D ndarray of zeros and ones.\n Denotes the simulated choices based on one's model. `sim_y.shape[0]`\n MUST equal `x.shape[0]`. There should be one column per simulation.\n obs_y : 1D ndarray of zeros and ones.\n The observed choices used to estimate one's model.\n x_label, y_label : str, optional.\n Denotes the x-axis and y-axis labels used on the plot. Defaults are 'X'\n and 'Counts'.\n display_dict : dict or None, optional.\n If passed, will be used to override the default xtick-labels. Each key\n should be a unique value in `x`. Each value should be the label to be\n plotted.\n\n Returns\n -------\n boxplot_df : pandas DataFrame.\n Will contain an `x_label` and `y_label` column. There will be one row\n per unique value in `x_label` per simulation. The `y_label` column will\n contain the counts of the number of times the associated value in the\n `x_label` column was simulated to be chosen.\n obs_df : pandas DataFrame.\n Will contain the same two columns as boxplot_df. There will be one row\n per unique value in `x_label`. The values in the `y_label` column will\n be the number of observations with the row's corresponding `x_label`\n value.\n \"\"\"\n # Get the positions and counts of the chosen values of x\n unique_pos = np.unique(x, return_index=True)[1]\n\n # Determine the unique values in the x-array, in their original order.\n unique_vals = x[np.sort(unique_pos)]\n\n # Get the counts of the chosen values of x\n _val_names, _val_counts = np.unique(x[obs_y == 1], return_counts=True)\n obs_df = pd.DataFrame({x_label: _val_names, y_label: _val_counts})\n\n # Initialize an array of the simulated number of observations per value\n num_per_value_per_sim = np.empty((unique_vals.size, sim_y.shape[1]))\n\n # Create the iterable for populating `num_per_value_per_sim`\n iterator = progress(unique_vals, desc=\"Unique x-values\")\n\n # Populate the created array\n for pos, val in enumerate(iterator):\n # Determine the rows of x that have values of `val`.\n row_idxs = np.where(x == val)[0]\n # Get the simulated y values for the given value.\n current_sim_y = sim_y[row_idxs, :]\n # Store the total simulated number of observations equaling `val`\n num_per_value_per_sim[pos, :] = current_sim_y.sum(axis=0)\n\n ####\n # Convert the array of simulated counts per value of X to a dataframe\n ####\n # Create an array with 1 row per unique value of x per simulation\n long_vals = np.repeat(unique_vals, sim_y.shape[1])\n # Convert the counts per unique value per simulation into a 1D array\n long_counts = num_per_value_per_sim.ravel()\n # Create a dataframe of the unique values of x and the simulated counts\n boxplot_df = pd.DataFrame({x_label: long_vals, y_label: long_counts})\n # Convert the unique values to names the user wants to display on the plot\n if display_dict is not None:\n boxplot_df[x_label] = boxplot_df[x_label].map(display_dict)\n obs_df[x_label] = obs_df[x_label].map(display_dict)\n\n # Also make the x_label values the index for the observed dataframe for\n # later sorting.\n obs_df.index = [str(v) for v in obs_df[x_label].values]\n return boxplot_df, obs_df\n\n\ndef plot_simulated_market_shares(\n x,\n sim_y,\n obs_y,\n x_label=\"X\",\n y_label=\"Counts\",\n display_dict=None,\n fig_and_ax=None,\n figsize=(10, 6),\n fontsize=12,\n title=None,\n box_color=\"white\",\n obs_color=\"#045a8d\",\n obs_marker=\"*\",\n obs_size=12,\n obs_label=\"Observed\",\n output_file=None,\n dpi=500,\n show=True,\n):\n \"\"\"\n Makes a 'market share' boxplot of the simulated distributions of a discrete\n random variable versus the observed values of that variable. In particular,\n plots the observed number of observations that had a given value of a\n discrete variable versus the simulated distributions of how many\n observations had the same value.\n\n Parameters\n ----------\n x : 1D ndarray.\n Should contain the values of the discrete random value for each\n alternative for each observation.\n sim_y : 2D ndarray of zeros and ones.\n Denotes the simulated choices based on one's model. `sim_y.shape[0]`\n MUST equal `x.shape[0]`. There should be one column per simulation.\n obs_y : 1D ndarray of zeros and ones.\n The observed choices used to estimate one's model.\n x_label, y_label : str, optional.\n Denotes the x-axis and y-axis labels used on the plot. Defaults are 'X'\n and 'Counts'.\n display_dict : dict or None, optional.\n If passed, will be used to override the default xtick-labels. Each key\n should be a unique value in `x`. Each value should be the label to be\n plotted.\n fig_and_ax : list of matplotlib figure and axis, or `None`, optional.\n Determines whether a new figure will be created for the plot or whether\n the plot will be drawn on existing axes. If None, a new figure will be\n created. Default is `None`.\n figsize : 2-tuple of positive ints.\n Determines the size of the created figure. Default == (10, 6).\n fontsize : int or None, optional.\n The fontsize to be used in the plot. Default is 12.\n title : string or None, optional.\n Denotes the title to be displayed for the plot. Default is None.\n box_color, obs_color : valid matplotlib color argument, optional.\n Denotes the color of the boxes on the boxplot and the color used to\n plot the observed distribution of `x`. Default == 'white', '#045a8d'.\n obs_marker : valid matplotlib marker argument, optional.\n Determines the marker used to plot the observed distribution of `x`.\n Default is '*'.\n obs_size : int, optional.\n Determines the size of the marker for the observed distribution\n of `x`. Default is 12.\n obs_label : str, optional.\n Denotes the legend label used for the markers of the observed\n distribution of `x`. Default is 'Observed'.\n output_file : str, or None, optional.\n Denotes the relative or absolute filepath (including the file format)\n that is to be used to save the plot. If None, the plot will not be\n saved to file. Default is None.\n dpi : positive int, optional.\n Denotes the number of 'dots per inch' for the saved figure. Will only\n be used if `output_file is not None`. Default == 500.\n show : bool, optional.\n Determines whether the figure is shown after plotting is complete.\n Default == True.\n\n Returns\n -------\n None\n \"\"\"\n # Ensure the display dict has all possible values that are in x.\n if display_dict is not None:\n safe_display = {k: k for k in np.unique(x)}\n safe_display.update(display_dict)\n else:\n safe_display = None\n\n # Get the data needed for the plot\n boxplot_df, obs_df = _get_objects_for_market_share_plot(\n x, sim_y, obs_y, x_label, y_label, display_dict=safe_display\n )\n\n # Create or access the figure and axis on which the plot is to be drawn.\n if fig_and_ax is None:\n fig, ax = plt.subplots(1, figsize=figsize)\n fig_and_ax = [fig, ax]\n else:\n fig, ax = fig_and_ax\n\n # Create the desired boxplot plot\n sbn.boxplot(x=x_label, y=y_label, data=boxplot_df, color=box_color, ax=ax)\n # Reorder the observed values according to the order of the plot\n plot_labels = [v.get_text() for v in ax.get_xticklabels()]\n obs_df = obs_df.loc[plot_labels]\n # Add the observed values on top the boxplot\n sbn.stripplot(\n x=x_label,\n y=y_label,\n data=obs_df,\n ax=ax,\n color=obs_color,\n s=obs_size,\n marker=obs_marker,\n label=obs_label,\n )\n\n # Ensure that the xticklabels are of the correct fontsize\n ax.set_xticklabels(ax.get_xticklabels(), fontsize=fontsize)\n\n # Draw the legend, ensuring that we only have one entry.\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles[:1], labels[:1], loc=\"best\", fontsize=fontsize)\n\n # Take care of boilerplate plotting necessities\n _label_despine_save_and_show_plot(\n x_label=x_label,\n y_label=y_label,\n fig_and_ax=fig_and_ax,\n fontsize=fontsize,\n y_rot=0,\n y_pad=40,\n title=title,\n output_file=output_file,\n show=show,\n dpi=dpi,\n )\n return None\n"
] |
[
[
"numpy.unique",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"numpy.sort",
"numpy.repeat",
"numpy.where",
"numpy.empty"
]
] |
rebekka-burkholz/hidden-networks
|
[
"04b07bfdf4500b58886ee9093ec4283846404be8"
] |
[
"simple_mnist_example.py"
] |
[
"# General structure from https://github.com/pytorch/examples/blob/master/mnist/main.py\nfrom __future__ import print_function\nimport argparse\nimport os\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nimport torch.autograd as autograd\n\nargs = None\n\nclass GetSubnet(autograd.Function):\n @staticmethod\n def forward(ctx, scores, k):\n # Get the supermask by sorting the scores and using the top k%\n out = scores.clone()\n _, idx = scores.flatten().sort()\n j = int((1 - k) * scores.numel())\n\n # flat_out and out access the same memory.\n flat_out = out.flatten()\n flat_out[idx[:j]] = 0\n flat_out[idx[j:]] = 1\n\n return out\n\n @staticmethod\n def backward(ctx, g):\n # send the gradient g straight-through on the backward pass.\n return g, None\n#def percentile(t, q):\n# k = 1 + round(.01 * float(q) * (t.numel() - 1))\n# return t.view(-1).kthvalue(k).values.item()\n# \n#class GetSubnet(torch.autograd.Function):\n# @staticmethod\n# def forward(ctx, scores, zeros, ones, sparsity):\n# k_val = percentile(scores, sparsity*100)\n# return torch.where(scores < k_val, zeros.to(scores.device), ones.to(scores.device))\n#\n# @staticmethod\n# def backward(ctx, g):\n# return g, None, None, None\n\nclass SupermaskConv(nn.Conv2d):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # initialize the scores\n self.scores = nn.Parameter(torch.Tensor(self.weight.size()))\n nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))\n\n # NOTE: initialize the weights like this.\n nn.init.kaiming_normal_(self.weight, mode=\"fan_in\", nonlinearity=\"relu\")\n\n # NOTE: turn the gradient on the weights off\n self.weight.requires_grad = False\n\n def forward(self, x):\n subnet = GetSubnet.apply(self.scores.abs(), args.sparsity)\n w = self.weight * subnet\n x = F.conv2d(\n x, w, self.bias, self.stride, self.padding, self.dilation, self.groups\n )\n return x\n\nclass SupermaskLinear(nn.Linear):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # initialize the scores\n self.scores = nn.Parameter(torch.Tensor(self.weight.size()))\n nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))\n\n # NOTE: initialize the weights like this.\n nn.init.kaiming_normal_(self.weight, mode=\"fan_in\", nonlinearity=\"relu\")\n\n # NOTE: turn the gradient on the weights off\n self.weight.requires_grad = False\n\n def forward(self, x):\n subnet = GetSubnet.apply(self.scores.abs(), args.sparsity)\n w = self.weight * subnet\n return F.linear(x, w, self.bias)\n return x\n\n# NOTE: not used here but we use NON-AFFINE Normalization!\n# So there is no learned parameters for your nomralization layer.\nclass NonAffineBatchNorm(nn.BatchNorm2d):\n def __init__(self, dim):\n super(NonAffineBatchNorm, self).__init__(dim, affine=False)\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = SupermaskConv(1, 32, 3, 1, bias=False)\n self.conv2 = SupermaskConv(32, 64, 3, 1, bias=False)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = SupermaskLinear(9216, 128, bias=False)\n self.fc2 = SupermaskLinear(128, 10, bias=False)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\ndef train(model, device, train_loader, optimizer, criterion, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\n\ndef test(model, device, criterion, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target)\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef main():\n global args\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=14, metavar='N',\n help='number of epochs to train (default: 14)')\n parser.add_argument('--lr', type=float, default=0.1, metavar='LR',\n help='learning rate (default: 0.1)')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='Momentum (default: 0.9)')\n parser.add_argument('--wd', type=float, default=0.0005, metavar='M',\n help='Weight decay (default: 0.0005)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n parser.add_argument('--data', type=str, default='../data', help='Location to store data')\n parser.add_argument('--sparsity', type=float, default=0.5,\n help='how sparse is each layer')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(args.data, 'mnist'), train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(args.data, 'mnist'), train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.test_batch_size, shuffle=True, **kwargs)\n\n model = Net().to(device)\n # NOTE: only pass the parameters where p.requires_grad == True to the optimizer! Important!\n optimizer = optim.SGD(\n [p for p in model.parameters() if p.requires_grad],\n lr=args.lr,\n momentum=args.momentum,\n weight_decay=args.wd,\n )\n criterion = nn.CrossEntropyLoss().to(device)\n scheduler = CosineAnnealingLR(optimizer, T_max=args.epochs)\n for epoch in range(1, args.epochs + 1):\n train(model, device, train_loader, optimizer, criterion, epoch)\n test(model, device, criterion, test_loader)\n scheduler.step()\n\n if args.save_model:\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.Dropout2d",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.nn.functional.log_softmax",
"torch.manual_seed",
"torch.nn.functional.conv2d",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.cuda.is_available",
"torch.flatten",
"torch.device",
"torch.nn.functional.max_pool2d",
"torch.nn.functional.linear",
"torch.nn.init.kaiming_normal_"
]
] |
c-benko/HHG_phasematching_fsEC
|
[
"ea8029ceaa47fb62957eadfa8634d5d9b319cecb"
] |
[
"src/laser.py"
] |
[
"import numpy as np\n\nclass laser:\n '''\n The laser class, very basic. Takes intensity and pulse width, contains function form of pulse.\n\n Takes pulse_FWHM in [s], Int in [10**14 W cm**-2], lam is wavelength in [nm], spot is w0 in [um].\n pulse(self, t, strength, sigma) outputs a sin**2 pulse for the normalized strength and sigma.\n\n It also contains a few functions for general gaussian beam properties. \n\n '''\n def __init__(self, pulse_FWHM = 100e-15 , Int = 1, lam = 1.07e-6, spot = 17e-6):\n self.pulse_FWHM = pulse_FWHM\n self.Int = Int\n self.lam = lam\n self.spot = spot\n self.zr = np.pi*self.spot ** 2 / self.lam\n self.p0 = self.Int * np.pi / 2 * self.spot ** 2\n\n def pulse(self, t):\n '''\n Gaussian laser pulse.\n '''\n p = self.Int * np.exp(-2.77 * (t / self.pulse_FWHM ) ** 2 )\n \n return p\n\n def pulse_s2(self, t):\n '''\n IMPORTANT:\n only valid for t >= - self.pulse_FWHM and t <= self.pulse_FWHM\n '''\n p = self.Int * np.sin( np.pi * (t - self.pulse_FWHM) / 2 / self.pulse_FWHM ) ** 2\n \n return p\n\n def int_z(self, z):\n '''\n returns intensity as function of distance from focus. \n '''\n return 2 * self.p0 / np.pi / self.spot ** 2 / (1 + (z / self.zr) ** 2 )\n\n def d_int_z(self, z):\n '''\n returns dI / dz\n '''\n return -2 * self.p0 / np.pi / self.spot ** 2 * z / (self.zr * (1 + (z/self.zr) ** 2 ) ** 2 )\n\n"
] |
[
[
"numpy.exp",
"numpy.sin"
]
] |
bpbpublications/Natural-Computing-with--Python
|
[
"6338976b5d3edef026d9387d005d246b6160b508"
] |
[
"Chapter_04/ACO.py"
] |
[
"import math\nimport random\nfrom bisect import bisect_left\nfrom random import randint\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nclass colony:\n\tclass ant:\n\t\tdef __init__(self, colony):\n\t\t\tself.visited_food_locations = [colony.start]\n\t\t\tself.traveled_distance = 0\n\t\t\t\n\t\t\tself.unvisited_food_locations = \\\n colony.food_locations.difference\\\n (self.visited_food_locations)\n\t\t\tself.colony = colony\n\t\t\tself.current_location = colony.start\n\n\t\tdef collect_food(self):\n\t\t\twhile(self.unvisited_food_locations):\n\t\t\t\tself.visit_location()\n\t\t\t\n\t\tdef reset(self, colony):\n\t\t\tself.__init__(colony)\n\t\t\t\n\t\t\t\n\t\tdef visit_location(self):\n\t\t\troulette_wheel = [0]\n\t\t\tlocations = []\n\n\t\t\tfor new_location in self.unvisited_food_locations:\n\t\t\t\tlocations.append(new_location)\n\t\t\t\troulette_wheel.append(roulette_wheel[-1] +\n math.pow(colony.get_pheromones\\\n (self.current_location,\\\n new_location),\n colony.alpha)*\n math.pow((1.0/colony.distance\\\n (self.current_location,\\\n new_location)),\\\n colony.beta))\n\t\t\t\n\t\t\tran = random.uniform(0, roulette_wheel[-1])\n\t\t\ti = bisect_left(roulette_wheel, ran)\n\t\t\tself.traveled_distance += colony.distance(self.current_location,\\\n locations[i-1])\n\t\t\tself.current_location = locations[i-1]\n\t\t\tself.unvisited_food_locations.remove(self.current_location)\n\t\t\tself.visited_food_locations.append(self.current_location)\n\t\t\treturn\n\t\t\t\n\t\t\n\tdef __init__(self, food_locations, distance_callback, \\\n start, ant_count=50, iterations=80,\\\n alpha=.5, beta=1.2, \\\n pheromone_evaporation_coefficient=.40, pheromone_constant=1.0):\n\t\tself.shortest_path_distance = float('inf')\n\t\tself.shortest_path = []\n\t\t\n\t\tself.food_locations = food_locations\n\t\tself.distance = distance_callback\n\t\tself.start = start\n\t\tif start not in food_locations: food_locations.add(start)\n\t\tself.ant_count = ant_count\n\t\tself.iterations = iterations\n\t\tself.alpha = alpha\n\t\tself.beta = beta\n\t\tself.pheromone_evaporation_coefficient = pheromone_evaporation_coefficient\n\t\tself.pheromone_constant = pheromone_constant\n\t\tself.pheromones = self.init_pheromones(food_locations)\n\t\tself.new_pheromones = self.init_pheromones(food_locations)\n\n\tdef run(self):\n\t\tant = self.ant(self)\n\t\tfor _ in range(self.iterations):\n\t\t\tfor ant_number in range(self.ant_count):\n\t\t\t\tant.collect_food()\n\t\t\t\tif ant.traveled_distance < self.shortest_path_distance: \n\t\t\t\t\tself.shortest_path_distance = ant.traveled_distance\n\t\t\t\t\tself.shortest_path = ant.visited_food_locations\n\t\t\t\tself.leave_pheromones_trail(ant.visited_food_locations,\\\n ant.traveled_distance)\n\t\t\t\tant.reset(self)\n\t\t\tself.pheromone_evaporate()\n\t\t\t\n\t\n\tdef init_pheromones(self, food_locations):\n\t\treturn dict.fromkeys([(source_location,destination_location)\\\n for source_location in food_locations \\\n for destination_location in food_locations \\\n if source_location != destination_location], 0.1)\t\n\n\n\tdef get_pheromones(self, source_location, destination_location):\n\t\treturn self.pheromones[(source_location, destination_location)]\n\n\n\tdef leave_pheromones_trail(self, path, traveled_distance):\n\t\tfor i in range(len(path) - 1):\n\t\t\tself.new_pheromones[(path[i], path[i+1])] += \\\n self.pheromone_constant/traveled_distance\n\t\t\t\n\t\t\n\tdef pheromone_evaporate(self):\n\t\tfor k in self.new_pheromones.keys():\n\t\t\tself.new_pheromones[k] = \\\n self.new_pheromones[k] * \\\n self.pheromone_evaporation_coefficient\n\t\n\n\ndef draw_multiple_points(coord_list):\n for i in range(0,len(coord_list)):\n plt.scatter(coord_list[i][0], coord_list[i][1], s=10)\n plt.title(\"Food Locations \", fontsize=8)\n plt.xlabel(\"x Coord\", fontsize=8)\n plt.ylabel(\"y Coord\", fontsize=8)\n # plt.ion()\n plt.show()\n\ndef draw_line(coord_list):\n lenList = len(coord_list)\n x_number_values = []\n y_number_values = []\n for i in range(0,lenList):\n x_number_values.append(coord_list[i][0])\n y_number_values.append(coord_list[i][1])\n plt.plot(x_number_values, y_number_values, 'o-' , linewidth=1)\n plt.title(\"Best Route\", fontsize=8)\n plt.xlabel(\"x Coord\", fontsize=8)\n plt.ylabel(\"y Coord\", fontsize=8)\n plt.tick_params(axis='both', labelsize=8)\n #plt.ion()\n plt.show()\n\n\nif __name__ == '__main__':\n def distance_callback(source_location, destination_location):\n return abs(source_location[0] - destination_location[0]) + \\\n abs(source_location[1] - destination_location[1])\n start = (0,0)\n food_locations = {start}\n for i in range(0,30):\n food_locations.add((randint(0,200),randint(0,200)))\n\n draw_multiple_points(list(food_locations))\n colony = colony(food_locations, \\\n distance_callback,\\\n start, \\\n 50, \\\n 80, \\\n .5, \\\n 1.2, \\\n .40, \\\n 1.0)\n colony.run()\n print(\"shortest path distance = \" , colony.shortest_path_distance)\n print(\"colony shortest distance = \" ,colony.shortest_path)\n draw_line(list(colony.shortest_path))\n"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.ylabel"
]
] |
lchen23/xraylarch
|
[
"6861ad36a24cceef5e4e3e9d1260c818a4e661ec",
"6861ad36a24cceef5e4e3e9d1260c818a4e661ec"
] |
[
"larch/xsw/YongsCode/SimpleParratt.py",
"larch/xsw/SimpleParratt.py"
] |
[
"import math\nimport cmath\nimport numpy\n#import fluo # used in Layer.get_index, change to readf1f2, stop using fluo\nimport readf1f2a\n\n# 9/20/2010: Y.Choi.\n# Reflectivity calculation using Parratt's recursive formula\n# Calculate reflected intensity as a function of angle or energy\n# Needs accesss to index of refraction data\n# layer0 is vaccum, layer1 is top film layer ...\n\nclass Layer:\n def __init__(self, tag, composition='Si', density=2.33, thickness=1000.1234, rms=1e-3):\n self.tag=tag # layer name, ex), 'top layer','film1'...\n self.composition=composition # chemical formula ex) SiO2\n self.density=density # nominal density in g/cm^3\n self.relden=1.0 # relative density 1.0=100% of nominal density\n self.thickness=thickness # in Angstroms 1e8 A = 1cm\n if rms==0: rms=1e-9 # cannot handle 0 roughness.\n self.rms=rms # rms interface roughness in Agnstroms\n self.la=1.0 # absoprtion length in cm, for inicident x-ray\n self.laFY=1.0 # absorption length in Angstrom, for emitted fluorescence\n self.trans=0.5 # transmission coefficient\n self.absrp=0.5 # absorption coefficient\n self.delta=0.1 # index of refraction, real part\n self.beta=0.1 # index of refraction, imaginary part\n self.kz=1.0+1.0J # wavenumber, complex [wavenumZ]\n self.rr=0+0J # Fresnel coefficient, [FresnelR]\n self.rf=0+0J # Fresnel coefficient with roughness, refl:[FresnelR]+[RoughGauss]\n self.rrr=0+0J # reflectivity, [Reflect]\n self.tt=0+0J # Fresnel coeffcient, [FresnelT]\n self.tf=0+0J # Fresnel coefficient with roughness, for transmission\n self.ttt=0+0J # transmission, [Transmit]\n self.E_t=0+0J # electric field, transmission\n self.E_r=0+0J # electric field, relfection\n self.interface=0 # interface depth, air/film is 0 for air layer\n self.index=-1 # air=0, film1=1, ...substrate=n\n self.Nat=1 # atomic number density for element of interest \n def set_DenThickRms(self, RelativeDensity, thickness, roughness):\n self.relden=RelativeDensity\n self.thickness=thickness\n self.rms=roughness\n def get_index(self, energy=8370.0, indexNat=0): # x-ray energy in eV, relative density\n temp=readf1f2a.get_delta(self.composition, self.density*self.relden, energy, indexNat) # used to be fluo\n self.delta=temp[0]\n self.beta=temp[1]\n self.la=temp[2] # in cm,\n self.Nat=temp[3]\n self.trans=math.exp(-self.thickness*1e8/self.la)\n #la attenuation length cm, NumLayer for multiple layers\n self.absrp=1.0-self.trans\n def cal_kz(self, k0, th_rad): # calculate wavenumber in each layer\n temp = cmath.sqrt((math.sin(th_rad))**2 - 2.0*self.delta - 2.0*self.beta*1.0j)\n self.kz = k0*(temp.real + abs(temp.imag)*1.0J)\n #kz = k0 * sqrt((sin(th_rad))^2 - 2*delta - 2*beta*i)\n def cal_rr(self, kz0, kz1):\n # Fresnel coefficient, [FresnelR] input: kz_(j), kz_(j+1)\n temp = (kz0-kz1)/(kz0+kz1) \n self.rr = temp\n def cal_rf(self, rr, kz0, kz1):\n # add roughness effect to Fresnel coefficient, [RoughGauss], input:kz_(j), kz_(j+1), rr, rms\n temp = rr*cmath.exp(-2.0*kz0*kz1*self.rms) \n self.rf = temp\n def cal_rrr(self, rf0, rrr1, kz1, d1): # reflectivity, [Reflect]\n v = 2.0*kz1*d1\n u = -v.imag + v.real*1.0J\n z1 = rrr1*cmath.exp(u) + rf0\n z2 = 1.0 + rf0*rrr1*cmath.exp(u)\n z=z1/z2\n self.rrr=z\n def cal_tt(self, kz0, kz1):\n #Fresnel coefficient [FresnelT], upto here 0: ThisLayer_(i), 1: BelowLayer_(i+1)\n temp = 2*kz0/(kz0+kz1)\n self.tt=temp\n def cal_ttt(self, tf2, rf2, rrr0, d0, ttt2, kz0):\n #Fresnel coefficient [FresnelT], 0:ThisLayer_(i), 2: AboveLayer_(i-1)\n v1 = -2.0*d0*kz0.imag + (2.0*d0*kz0.real)*1.0J\n v2 = cmath.exp(v1)\n v3 = -d0*kz0.imag + (d0*kz0.real)*1.0J\n v4 = cmath.exp(v3)\n v5 = tf2*(ttt2*v4)\n v6 = rf2*(rrr0*v2)\n v7 = v6.real+1.0 + (v6.imag)*1.0J\n z=v5/v7\n self.ttt=z\n\n\ndef reflectivity(eV0=14000.0, th_deg=[], mat=[], thick=[], den=[], rough=[], tag=[], depths=[], xsw_mode=0):\n# --------------------set default values------------------------\n if th_deg==[]: # set default th list\n th_min=0.0 # minimum th\n th_max=1.0 # maximum th\n th_step=0.002 # stepsize th\n th_deg=numpy.arange(th_min, th_max+th_step, th_step) \t\n th=[] # theta(incident angle) in radian\n qz=[] # momentum transfer (1/Angstrom)\n if mat==[] or thick==[] or den==[] or rough==[]:\n #set defalut layer material, air, film1, film2, substrate\n tag=['air', 'film', 'underlayer', 'substrate'] \n mat=['N1.56O0.48C0.03Ar0.01Kr0.000001Xe0.0000009', 'Pt', 'Cr', 'Si'] \n thick=[0., 200., 50., 10000] # air, film1, film2, substrate\n den=[1.e-10, 21.45, 7.19, 2.33]\n rough=[1.0, 1.0, 1.0, 1.0]\n if depths==[]: # set default depth list\n depths=[0.0] # in Angstroms\n depth_num=len(depths)\n layers=[] \n for (ii, d) in enumerate(thick):\n layer0=Layer(tag[ii], mat[ii], den[ii])\n layer0.set_DenThickRms(1.0, thick[ii], rough[ii])\n layers.append(layer0)\n NumLayers=len(layers) # this value is (# of film layer + 2[air, substrate])\n FilmThick=0.0 # film thickness\n for (ix, item) in enumerate(layers):\n item.get_index(eV0) # get index of refraction, delta, beta for eV0\n FilmThick+=item.thickness # get total film thickness\n item.interface=FilmThick # interface location: depth from surface\n item.index=ix # layer index\n WaveLength=12.39842/(eV0/1000.0) # in Angstroms, 1e-8cm = 1 Angstrom\n k0=2.*math.pi/WaveLength\n for (ix, angle) in enumerate(th_deg): # convert th_deg to th(rad) and qz(1/A)\n temp=angle/180.0*math.pi\n th.append(temp) # th in radian\n temp1=4.*math.pi/WaveLength*math.sin(temp) #qz=4pi/lambda*sin(th)*2k0sin(th)\n qz.append(temp1)\n NumTh=len(th)\n out_parratt='SimpleParratt.txt' # output file name\n fp=open(out_parratt, 'w')\n ListOut=[]\n for angle in th:\n # define wavenumber within each layer\n for layer in layers: \n layer.cal_kz(k0, angle)\n # calculate reflection and transmission coefficients\n for ix in range(NumLayers-1): \n layer=layers[ix]\n kz0=layers[ix].kz\n kz1=layers[ix+1].kz\n layer.cal_rr(kz0, kz1) # Fresnel coefficient, rr\n layer.cal_rf( layer.rr, kz0, kz1) # Fresnel coefficient with roughness, rf\n layer.cal_tt(kz0, kz1) # Fresnel coefficient, tt, in e-field intensity\n layer.tf=layer.rf+1.0 # T=1+R\n # calculate reflectivity\n layers[NumLayers-1].rrr=0.0 # nothing reflects back from below the substrate\n layers[NumLayers-2].rrr=layers[NumLayers-2].rf # interface between the substrate and layer above it\n ixs=numpy.arange(NumLayers-3, -1, -1) # start from second interface from the substrate to 0\n for ix in ixs: # calculate RRR\n BelowLayer=layers[ix+1]\n ThisLayer=layers[ix]\n ThisLayer.cal_rrr(ThisLayer.rf, BelowLayer.rrr, BelowLayer.kz, BelowLayer.thickness)\n intenR = (layers[0].rrr.real)**2 + (layers[0].rrr.imag)**2\n # intenR is reflected intensity\n # calculate transmission\n layers[0].ttt=1.0 + 0J\n ixs=numpy.arange(1, NumLayers-1, 1) # from 1 to <(NumLayers-1)\n for ix in ixs: # Calculate TTT\n ThisLayer=layers[ix]\n AboveLayer=layers[ix-1]\n ThisLayer.cal_ttt(AboveLayer.tf, AboveLayer.rf, ThisLayer.rrr, \\\n ThisLayer.thickness, AboveLayer.ttt, ThisLayer.kz)\n ixs=numpy.arange(0, NumLayers-1, 1) # from 1 to <(NumLayers-1)\n for ix in ixs:\n ThisLayer=layers[ix]\n ThisLayer.E_t=ThisLayer.ttt\n ThisLayer.E_r=ThisLayer.ttt*ThisLayer.rrr\n layers[NumLayers-1].E_t = layers[NumLayers-2].tf*layers[NumLayers-2].ttt\n## Next, the current depth within the film structure is searched.\n## depth=0 is air/film, depth>0 film, depth<0 above film\n## xx=0 is film/substrate, xx<0 inside substrate, xx>0 above substrate\n## for reflectivity only, fix depth=0 and skip full xsw calculation\n layer_index=0 # air/layer1\n netFY=0.0; EFIat0=0.0; FY=0.0\n TransFY=1.0; TransFYList=[]\n EFI_atTH=[] # EFI as a function of depth at current th\n EFI = 0\n #print(depth_num)\n for depth in depths:\n # calculate e-field intensity at each depth\n xx=FilmThick-depth\n ThisLayer = layers[layer_index]\n if layer_index==(NumLayers-1): #inside substrate\n cph = -xx*ThisLayer.kz\n cph_t = cmath.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t\n elif layer_index==(NumLayers-2): # layer above the substrate\n d_n=0\n cph = ThisLayer.kz*(xx-d_n)\n cph_t = cmath.exp(cph*(0.0-1.0J))\n cph_r = cmath.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t + ThisLayer.E_r*cph_r\n else:\n d_n=FilmThick-ThisLayer.interface\n cph = ThisLayer.kz*(xx-d_n)\n cph_t = cmath.exp(cph*(0.0-1.0J))\n cph_r = cmath.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t + ThisLayer.E_r*cph_r\n EFI = (Etot.real)**2 + (Etot.imag)**2\n if xsw_mode:\n pass\n temp=angle*180.0/math.pi\n out=str(temp)+' '+str(intenR)+' '+str(EFI)+'\\n'\n ListOut.append([temp, intenR, EFI])\n fp.write(out) \n fp.close()\n #for layer in layers:\n # print(layer.tag, layer.composition, layer.thickness, layer.rms, layer.density)\n return ListOut #list of [[th1, refl1], [th2, refl2] ...]\n \n\n\n\nif __name__=='__main__':\n #test\n reload(readf1f2a)\n import time\n a=time.clock()\n reflectivity() \n print(time.clock()-a, 'seconds')\n\n\n\n",
"# 9/20/2010: Y.Choi.\n# Reflectivity calculation using Parratt's recursive formula\n# Calculate reflected intensity as a function of angle or energy\n# Needs accesss to index of refraction data\n# layer0 is vaccum, layer1 is top film layer ...\n\nimport math\nimport numpy as np\nfrom xraydb import xray_delta_beta\n\nclass Layer:\n def __init__(self, tag, composition='Si', density=2.33, thickness=1000.1234, rms=1e-3):\n self.tag=tag # layer name, ex), 'top layer','film1'...\n self.composition=composition # chemical formula ex) SiO2\n self.density=density # nominal density in g/cm^3\n self.relden=1.0 # relative density 1.0=100% of nominal density\n self.thickness=thickness # in Angstroms 1e8 A = 1cm\n if rms==0: rms=1e-9 # cannot handle 0 roughness.\n self.rms=rms # rms interface roughness in Agnstroms\n self.la=1.0 # absoprtion length in cm, for inicident x-ray\n self.laFY=1.0 # absorption length in Angstrom, for emitted fluorescence\n self.trans=0.5 # transmission coefficient\n self.absrp=0.5 # absorption coefficient\n self.delta=0.1 # index of refraction, real part\n self.beta=0.1 # index of refraction, imaginary part\n self.kz=1.0+1.0J # wavenumber, complex [wavenumZ]\n self.rr=0+0J # Fresnel coefficient, [FresnelR]\n self.rf=0+0J # Fresnel coefficient with roughness, refl:[FresnelR]+[RoughGauss]\n self.rrr=0+0J # reflectivity, [Reflect]\n self.tt=0+0J # Fresnel coeffcient, [FresnelT]\n self.tf=0+0J # Fresnel coefficient with roughness, for transmission\n self.ttt=0+0J # transmission, [Transmit]\n self.E_t=0+0J # electric field, transmission\n self.E_r=0+0J # electric field, relfection\n self.interface=0 # interface depth, air/film is 0 for air layer\n self.index=-1 # air=0, film1=1, ...substrate=n\n self.Nat=1 # atomic number density for element of interest\n def set_DenThickRms(self, RelativeDensity, thickness, roughness):\n self.relden=RelativeDensity\n self.thickness=thickness\n self.rms=roughness\n\n def get_index(self, energy=8370.0, indexNat=0): # x-ray energy in eV, relative density\n # MN replace...\n # temp=readf1f2a.get_delta(self.composition, self.density*self.relden, energy, indexNat) # used to be fluo\n #self.delta=temp[0]\n #self.beta=temp[1]\n #self.la=temp[2] # in cm,\n #self.Nat=temp[3]\n delta, beta, la = xray_delta_beta(self.composition,\n self.density*self.relden, energy)\n self.delta, self.beta, self.la = delta, beta, la\n #la attenuation length cm, NumLayer for multiple layers\n self.trans=math.exp(-self.thickness*1e8/la)\n self.absrp=1.0-self.trans\n\n def cal_kz(self, k0, th_rad): # calculate wavenumber in each layer\n temp = np.sqrt((math.sin(th_rad))**2 - 2.0*self.delta - 2.0*self.beta*1.0j)\n self.kz = k0*(temp.real + abs(temp.imag)*1.0J)\n #kz = k0 * sqrt((sin(th_rad))^2 - 2*delta - 2*beta*i)\n def cal_rr(self, kz0, kz1):\n # Fresnel coefficient, [FresnelR] input: kz_(j), kz_(j+1)\n temp = (kz0-kz1)/(kz0+kz1)\n self.rr = temp\n def cal_rf(self, rr, kz0, kz1):\n # add roughness effect to Fresnel coefficient, [RoughGauss], input:kz_(j), kz_(j+1), rr, rms\n temp = rr*np.exp(-2.0*kz0*kz1*self.rms)\n self.rf = temp\n def cal_rrr(self, rf0, rrr1, kz1, d1): # reflectivity, [Reflect]\n v = 2.0*kz1*d1\n u = -v.imag + v.real*1.0J\n z1 = rrr1*np.exp(u) + rf0\n z2 = 1.0 + rf0*rrr1*np.exp(u)\n z=z1/z2\n self.rrr=z\n def cal_tt(self, kz0, kz1):\n #Fresnel coefficient [FresnelT], upto here 0: ThisLayer_(i), 1: BelowLayer_(i+1)\n temp = 2*kz0/(kz0+kz1)\n self.tt=temp\n def cal_ttt(self, tf2, rf2, rrr0, d0, ttt2, kz0):\n #Fresnel coefficient [FresnelT], 0:ThisLayer_(i), 2: AboveLayer_(i-1)\n v1 = -2.0*d0*kz0.imag + (2.0*d0*kz0.real)*1.0J\n v2 = np.exp(v1)\n v3 = -d0*kz0.imag + (d0*kz0.real)*1.0J\n v4 = np.exp(v3)\n v5 = tf2*(ttt2*v4)\n v6 = rf2*(rrr0*v2)\n v7 = v6.real+1.0 + (v6.imag)*1.0J\n z=v5/v7\n self.ttt=z\n\n\ndef reflectivity(eV0=14000.0, th_deg=[], mat=[], thick=[], den=[], rough=[], tag=[], depths=[], xsw_mode=0):\n# --------------------set default values------------------------\n if th_deg==[]: # set default th list\n th_min=0.0 # minimum th\n th_max=1.0 # maximum th\n th_step=0.002 # stepsize th\n th_deg = np.arange(th_min, th_max+th_step, th_step)\n th=[] # theta(incident angle) in radian\n qz=[] # momentum transfer (1/Angstrom)\n if mat==[] or thick==[] or den==[] or rough==[]:\n #set defalut layer material, air, film1, film2, substrate\n tag=['air', 'film', 'underlayer', 'substrate']\n mat=['N1.56O0.48C0.03Ar0.01Kr0.000001Xe0.0000009', 'Pt', 'Cr', 'Si']\n thick=[0., 200., 50., 10000] # air, film1, film2, substrate\n den=[1.e-10, 21.45, 7.19, 2.33]\n rough=[1.0, 1.0, 1.0, 1.0]\n if depths==[]: # set default depth list\n depths=[0.0] # in Angstroms\n depth_num=len(depths)\n layers=[]\n for (ii, d) in enumerate(thick):\n layer0=Layer(tag[ii], mat[ii], den[ii])\n layer0.set_DenThickRms(1.0, thick[ii], rough[ii])\n layers.append(layer0)\n NumLayers=len(layers) # this value is (# of film layer + 2[air, substrate])\n FilmThick=0.0 # film thickness\n for (ix, item) in enumerate(layers):\n item.get_index(eV0) # get index of refraction, delta, beta for eV0\n FilmThick+=item.thickness # get total film thickness\n item.interface=FilmThick # interface location: depth from surface\n item.index=ix # layer index\n WaveLength=12.39842/(eV0/1000.0) # in Angstroms, 1e-8cm = 1 Angstrom\n k0=2.*math.pi/WaveLength\n for (ix, angle) in enumerate(th_deg): # convert th_deg to th(rad) and qz(1/A)\n temp=angle/180.0*math.pi\n th.append(temp) # th in radian\n temp1=4.*math.pi/WaveLength*math.sin(temp) #qz=4pi/lambda*sin(th)*2k0sin(th)\n qz.append(temp1)\n NumTh=len(th)\n out_parratt='SimpleParratt.txt' # output file name\n fp=open(out_parratt, 'w')\n ListOut=[]\n for angle in th:\n # define wavenumber within each layer\n for layer in layers:\n layer.cal_kz(k0, angle)\n # calculate reflection and transmission coefficients\n for ix in range(NumLayers-1):\n layer=layers[ix]\n kz0=layers[ix].kz\n kz1=layers[ix+1].kz\n layer.cal_rr(kz0, kz1) # Fresnel coefficient, rr\n layer.cal_rf( layer.rr, kz0, kz1) # Fresnel coefficient with roughness, rf\n layer.cal_tt(kz0, kz1) # Fresnel coefficient, tt, in e-field intensity\n layer.tf=layer.rf+1.0 # T=1+R\n # calculate reflectivity\n layers[NumLayers-1].rrr=0.0 # nothing reflects back from below the substrate\n layers[NumLayers-2].rrr=layers[NumLayers-2].rf # interface between the substrate and layer above it\n ixs = np.arange(NumLayers-3, -1, -1) # start from second interface from the substrate to 0\n for ix in ixs: # calculate RRR\n BelowLayer=layers[ix+1]\n ThisLayer=layers[ix]\n ThisLayer.cal_rrr(ThisLayer.rf, BelowLayer.rrr, BelowLayer.kz, BelowLayer.thickness)\n intenR = (layers[0].rrr.real)**2 + (layers[0].rrr.imag)**2\n # intenR is reflected intensity\n # calculate transmission\n layers[0].ttt=1.0 + 0J\n ixs=np.arange(1, NumLayers-1, 1) # from 1 to <(NumLayers-1)\n for ix in ixs: # Calculate TTT\n ThisLayer=layers[ix]\n AboveLayer=layers[ix-1]\n ThisLayer.cal_ttt(AboveLayer.tf, AboveLayer.rf, ThisLayer.rrr, \\\n ThisLayer.thickness, AboveLayer.ttt, ThisLayer.kz)\n ixs=np.arange(0, NumLayers-1, 1) # from 1 to <(NumLayers-1)\n for ix in ixs:\n ThisLayer=layers[ix]\n ThisLayer.E_t=ThisLayer.ttt\n ThisLayer.E_r=ThisLayer.ttt*ThisLayer.rrr\n layers[NumLayers-1].E_t = layers[NumLayers-2].tf*layers[NumLayers-2].ttt\n## Next, the current depth within the film structure is searched.\n## depth=0 is air/film, depth>0 film, depth<0 above film\n## xx=0 is film/substrate, xx<0 inside substrate, xx>0 above substrate\n## for reflectivity only, fix depth=0 and skip full xsw calculation\n layer_index=0 # air/layer1\n netFY=0.0; EFIat0=0.0; FY=0.0\n TransFY=1.0; TransFYList=[]\n EFI_atTH=[] # EFI as a function of depth at current th\n EFI = 0\n #print( depth_num)\n for depth in depths:\n # calculate e-field intensity at each depth\n xx=FilmThick-depth\n ThisLayer = layers[layer_index]\n if layer_index==(NumLayers-1): #inside substrate\n cph = -xx*ThisLayer.kz\n cph_t = np.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t\n elif layer_index==(NumLayers-2): # layer above the substrate\n d_n=0\n cph = ThisLayer.kz*(xx-d_n)\n cph_t = np.exp(cph*(0.0-1.0J))\n cph_r = np.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t + ThisLayer.E_r*cph_r\n else:\n d_n=FilmThick-ThisLayer.interface\n cph = ThisLayer.kz*(xx-d_n)\n cph_t = np.exp(cph*(0.0-1.0J))\n cph_r = np.exp(cph*(0.0+1.0J))\n Etot = ThisLayer.E_t*cph_t + ThisLayer.E_r*cph_r\n EFI = (Etot.real)**2 + (Etot.imag)**2\n if xsw_mode:\n pass\n temp=angle*180.0/math.pi\n out=str(temp)+' '+str(intenR)+' '+str(EFI)+'\\n'\n ListOut.append([temp, intenR, EFI])\n fp.write(out)\n fp.close()\n #for layer in layers:\n # print( layer.tag, layer.composition, layer.thickness, layer.rms, layer.density)\n return ListOut #list of [[th1, refl1], [th2, refl2] ...]\n\n\n\n\nif __name__=='__main__':\n #test\n # reload(readf1f2a)\n import time\n a=time.clock()\n reflectivity()\n print(time.clock()-a, 'seconds')\n"
] |
[
[
"numpy.arange"
],
[
"numpy.arange",
"numpy.exp"
]
] |
Jasonnor/deepface
|
[
"1512d0ae58832d7c66f01b24acca1077323ecfbd"
] |
[
"api/api.py"
] |
[
"from flask import Flask, jsonify, request, make_response\n\nimport argparse\nimport uuid\nimport json\nimport time\nfrom tqdm import tqdm\n\nimport tensorflow as tf\n\nfrom deepface import DeepFace\nfrom deepface.basemodels import VGGFace, OpenFace, Facenet, FbDeepFace\nfrom deepface.extendedmodels import Age, Gender, Race, Emotion\n\n#import DeepFace\n#from basemodels import VGGFace, OpenFace, Facenet, FbDeepFace\n#from extendedmodels import Age, Gender, Race, Emotion\n\n#------------------------------\n\napp = Flask(__name__)\n\n#------------------------------\n\ntic = time.time()\n\nprint(\"Loading Face Recognition Models...\")\n\npbar = tqdm(range(0,4), desc='Loading Face Recognition Models...')\n\nfor index in pbar:\n\tif index == 0:\n\t\tpbar.set_description(\"Loading VGG-Face\")\n\t\tvggface_model = VGGFace.loadModel()\n\telif index == 1:\n\t\tpbar.set_description(\"Loading OpenFace\")\n\t\topenface_model = OpenFace.loadModel()\n\telif index == 2:\n\t\tpbar.set_description(\"Loading Google FaceNet\")\n\t\tfacenet_model = Facenet.loadModel()\n\telif index == 3:\n\t\tpbar.set_description(\"Loading Facebook DeepFace\")\n\t\tdeepface_model = FbDeepFace.loadModel()\n\ntoc = time.time()\n\nprint(\"Face recognition models are built in \", toc-tic,\" seconds\")\n\n#------------------------------\n\ntic = time.time()\n\nprint(\"Loading Facial Attribute Analysis Models...\")\n\npbar = tqdm(range(0,4), desc='Loading Facial Attribute Analysis Models...')\n\nfor index in pbar:\n\tif index == 0:\n\t\tpbar.set_description(\"Loading emotion analysis model\")\n\t\temotion_model = Emotion.loadModel()\n\telif index == 1:\n\t\tpbar.set_description(\"Loading age prediction model\")\n\t\tage_model = Age.loadModel()\n\telif index == 2:\n\t\tpbar.set_description(\"Loading gender prediction model\")\n\t\tgender_model = Gender.loadModel()\n\telif index == 3:\n\t\tpbar.set_description(\"Loading race prediction model\")\n\t\trace_model = Race.loadModel()\n\ntoc = time.time()\n\nfacial_attribute_models = {}\nfacial_attribute_models[\"emotion\"] = emotion_model\nfacial_attribute_models[\"age\"] = age_model\nfacial_attribute_models[\"gender\"] = gender_model\nfacial_attribute_models[\"race\"] = race_model\n\nprint(\"Facial attribute analysis models are built in \", toc-tic,\" seconds\")\n\n#------------------------------\n\ngraph = tf.get_default_graph()\n\n#------------------------------\n#Service API Interface\n\n@app.route('/')\ndef index():\n\treturn '<h1>Hello, world!</h1>'\n\n@app.route('/analyze', methods=['POST'])\ndef analyze():\n\t\n\tglobal graph\n\t\n\ttic = time.time()\n\treq = request.get_json()\n\ttrx_id = uuid.uuid4()\n\n\t#---------------------------\n\t\n\tresp_obj = jsonify({'success': False})\n\twith graph.as_default():\n\t\tinstances = []\n\t\tif \"img\" in list(req.keys()):\n\t\t\traw_content = req[\"img\"] #list\n\n\t\t\tfor item in raw_content: #item is in type of dict\n\t\t\t\tinstances.append(item)\n\t\t\n\t\tif len(instances) == 0:\n\t\t\treturn jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205\n\t\t\n\t\tprint(\"Analyzing \", len(instances),\" instances\")\n\n\t\t#---------------------------\n\n\t\tactions= ['emotion', 'age', 'gender', 'race']\n\t\tif \"actions\" in list(req.keys()):\n\t\t\tactions = req[\"actions\"]\n\t\t\n\t\t#---------------------------\n\n\t\t#resp_obj = DeepFace.analyze(instances, actions=actions)\n\t\tresp_obj = DeepFace.analyze(instances, actions=actions, models=facial_attribute_models)\n\t\t\n\t\t#---------------------------\n\n\ttoc = time.time()\n\n\tresp_obj[\"trx_id\"] = trx_id\n\tresp_obj[\"seconds\"] = toc-tic\n\n\treturn resp_obj, 200\n\n\n@app.route('/analysis', methods=['POST'])\ndef analysis():\n\tglobal graph\n\ttic = time.time()\n\treq = request.get_json()\n\ttrx_id = uuid.uuid4()\n\twith graph.as_default():\n\t\tinstances = []\n\t\tif \"img\" in list(req.keys()):\n\t\t\traw_content = req[\"img\"] # list\n\t\t\tfor item in raw_content: # item is in type of dict\n\t\t\t\tinstances.append(item)\n\t\tif len(instances) == 0:\n\t\t\treturn jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205\n\t\tprint(\"Analyzing \", len(instances), \" instances\")\n\t\tresults = DeepFace.analysis(instances, models=facial_attribute_models)\n\ttoc = time.time()\n\ttime_cost = toc - tic\n\tprint(\"Analyze id {} done, time cost: {:.2f}\".format(trx_id, time_cost))\n\tresponse = {\n\t\t'result': results,\n\t\t'trx_id': str(trx_id),\n\t\t'time_cost': time_cost\n\t}\n\treturn response, 200\n\n\n@app.route('/verify', methods=['POST'])\ndef verify():\n\t\n\tglobal graph\n\t\n\ttic = time.time()\n\treq = request.get_json()\n\ttrx_id = uuid.uuid4()\n\t\n\tresp_obj = jsonify({'success': False})\n\t\n\twith graph.as_default():\n\t\t\n\t\tmodel_name = \"VGG-Face\"; distance_metric = \"cosine\"\n\t\tif \"model_name\" in list(req.keys()):\n\t\t\tmodel_name = req[\"model_name\"]\n\t\tif \"distance_metric\" in list(req.keys()):\n\t\t\tdistance_metric = req[\"distance_metric\"]\n\t\t\n\t\t#----------------------\n\t\t\n\t\tinstances = []\n\t\tif \"img\" in list(req.keys()):\n\t\t\traw_content = req[\"img\"] #list\n\n\t\t\tfor item in raw_content: #item is in type of dict\n\t\t\t\tinstance = []\n\t\t\t\timg1 = item[\"img1\"]; img2 = item[\"img2\"]\n\n\t\t\t\tvalidate_img1 = False\n\t\t\t\tif len(img1) > 11 and img1[0:11] == \"data:image/\":\n\t\t\t\t\tvalidate_img1 = True\n\t\t\t\t\n\t\t\t\tvalidate_img2 = False\n\t\t\t\tif len(img2) > 11 and img2[0:11] == \"data:image/\":\n\t\t\t\t\tvalidate_img2 = True\n\n\t\t\t\tif validate_img1 != True or validate_img2 != True:\n\t\t\t\t\treturn jsonify({'success': False, 'error': 'you must pass both img1 and img2 as base64 encoded string'}), 205\n\n\t\t\t\tinstance.append(img1); instance.append(img2)\n\t\t\t\tinstances.append(instance)\n\t\t\t\n\t\t#--------------------------\n\n\t\tif len(instances) == 0:\n\t\t\treturn jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205\n\t\t\n\t\tprint(\"Input request of \", trx_id, \" has \",len(instances),\" pairs to verify\")\n\t\t\n\t\t#--------------------------\n\t\t\n\t\tif model_name == \"VGG-Face\":\n\t\t\tresp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = vggface_model)\n\t\telif model_name == \"Facenet\":\n\t\t\tresp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = facenet_model)\n\t\telif model_name == \"OpenFace\":\n\t\t\tresp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = openface_model)\n\t\telif model_name == \"DeepFace\":\n\t\t\tresp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = deepface_model)\n\t\telse:\n\t\t\treturn jsonify({'success': False, 'error': 'You must pass a valid model name. Available models are VGG-Face, Facenet, OpenFace, DeepFace but you passed %s' % (model_name)}), 205\n\t\t\n\t#--------------------------\n\t\n\ttoc = time.time()\n\t\n\tresp_obj[\"trx_id\"] = trx_id\n\tresp_obj[\"seconds\"] = toc-tic\n\t\n\treturn resp_obj, 200\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\n\t\t'-p', '--port',\n\t\ttype=int,\n\t\tdefault=5000,\n\t\thelp='Port of serving api')\n\targs = parser.parse_args()\n\tapp.run(host='0.0.0.0', port=args.port)\n"
] |
[
[
"tensorflow.get_default_graph"
]
] |
basiralab/ReMI-Net
|
[
"15402fee3afb572480971b11dac23c6da4f30e0c"
] |
[
"plotting.py"
] |
[
"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom matplotlib._color_data import BASE_COLORS\r\nfrom sklearn.manifold import TSNE\r\n\r\ndef plot_cbt(img, fold_num=1, timepoint=0):\r\n img = np.repeat(np.repeat(img, 10, axis=1), 10, axis=0)\r\n plt.imshow(img)\r\n plt.title(f\"CBT at Fold {fold_num} - Time {timepoint}\")\r\n plt.axis('off')\r\n plt.colorbar()\r\n plt.show()"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.title",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.axis",
"numpy.repeat",
"matplotlib.pyplot.show"
]
] |
samvanderpoel/PixelGeom
|
[
"cbe7ae3edd62105d69843f7317c608b16907849f"
] |
[
"tests/testcmap.py"
] |
[
"import functools\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # add parent dir to sys path\n\nfrom grid import rgb_to_cmap\n\nif not os.path.isdir('tests/test-output'):\n os.makedirs('tests/test-output')\n\n# Specify cmap here:\nmycmap = rgb_to_cmap([[255,127,80], [189,183,107], [123,104,238], [0,128,128], [218,112,214]])\n\ndef gradient(x, dim):\n idx, val = x\n temp_val = 1-idx[0]/(dim[0]-1)-idx[1]/(dim[1]-1)\n return [idx, (temp_val+1)/2]\n\ndim = (10, 10)\ncanvas = np.zeros(dim)\nenum = map(functools.partial(gradient, dim=dim), np.ndenumerate(canvas))\nfor idx, val in enum:\n canvas[idx] = val\n\ndpi = 300\nfig, ax = plt.subplots(1, figsize=(3, 3), dpi = dpi)\nax.imshow(canvas, cmap = mycmap, interpolation = 'None', vmin = 0, vmax = 1)\nax.axes.get_xaxis().set_visible(False)\nax.axes.get_yaxis().set_visible(False)\nax.axis('off')\nfig.subplots_adjust(right=1.00, left=0.00, bottom=0.00, top=1.00)\nfig.savefig('tests/test-output/test-cmap.png', dpi = dpi)\nplt.close()\n"
] |
[
[
"numpy.ndenumerate",
"numpy.zeros",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close"
]
] |
kaylai/VESIcal
|
[
"3ea18b0ce30b30fb55786346c37ef8f428ee5034"
] |
[
"VESIcal/models/liu.py"
] |
[
"from VESIcal import activity_models\nfrom VESIcal import calibration_checks\nfrom VESIcal import core\nfrom VESIcal import fugacity_models\nfrom VESIcal import model_classes\nfrom VESIcal import sample_class\n\nimport numpy as np\nimport warnings as w\nimport sympy\nfrom scipy.optimize import root_scalar\n\n\nclass water(model_classes.Model):\n \"\"\"\n Implementation of the Liu et al. (2005) H2O solubility model for metaluminous high-silica\n rhyolitic melts.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the model.\n \"\"\"\n self.set_volatile_species(['H2O'])\n self.set_fugacity_model(fugacity_models.fugacity_idealgas())\n self.set_activity_model(activity_models.activity_idealsolution())\n self.set_solubility_dependence(False)\n\n # Generate calibration range objects for each oxide\n cr_oxide_list = []\n for ox in watercomprange.keys():\n cr_oxide_list.append(\n calibration_checks.CalibrationRange(\n ox, watercomprange[ox], calibration_checks.crf_Between, 'wt%',\n 'Liu et al. (2005) water',\n fail_msg=calibration_checks.crmsg_BC_fail,\n pass_msg=calibration_checks.crmsg_BC_pass,\n description_msg=calibration_checks.crmsg_Between_description))\n\n self.set_calibration_ranges([\n calibration_checks.CalibrationRange(\n 'pressure', [0, 5000.0], calibration_checks.crf_Between, 'bar',\n 'Liu et al. (2005) water',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'temperature', [700.0, 1200], calibration_checks.crf_Between, 'oC',\n 'Liu et al. (2005) water',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'sample', None, crf_WaterComp, None, None,\n fail_msg=crmsg_WaterComp_fail,\n pass_msg=crmsg_Comp_pass,\n description_msg=crmsg_Comp_description)] + cr_oxide_list)\n\n def calculate_dissolved_volatiles(self, sample, pressure, temperature, X_fluid=1.0, **kwargs):\n \"\"\"\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n pressure float\n Pressure in bars.\n\n temperature float\n Temperature in degrees C.\n\n X_fluid float\n OPTIONAL. Default is 1.0. Mole fraction of H2O in the H2O-CO2 fluid.\n\n Returns\n -------\n float\n Calculated dissolved H2O concentration in wt%.\n \"\"\"\n pressureMPa = pressure / 10.0\n Pw = pressureMPa * X_fluid\n PCO2 = pressureMPa * (1 - X_fluid)\n\n temperatureK = temperature + 273.15\n\n H2Ot = ((354.94*Pw**(0.5) + 9.623*Pw - 1.5223*Pw**(1.5)) / temperatureK +\n 0.0012439*Pw**(1.5) + PCO2*(-1.084*10**(-4)*Pw**(0.5) - 1.362*10**(-5)*Pw))\n\n return H2Ot\n\n def calculate_equilibrium_fluid_comp(self, sample, pressure, temperature, **kwargs):\n \"\"\"\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n pressure float\n Pressure in bars.\n\n temperature float\n Temperature in degrees C.\n\n Returns\n -------\n float\n Calculated equilibrium fluid concentration in XH2Ofluid mole fraction.\n \"\"\"\n temperatureK = temperature + 273.15\n pressureMPa = pressure / 10.0\n\n H2Ot = sample.get_composition(\"H2O\")\n\n # calculate saturation pressure and assert that input P <= SatP\n satP = self.calculate_saturation_pressure(temperature, sample)\n is_saturated = satP - pressure\n if is_saturated >= 0:\n pass\n else:\n w.warn(\"{:.1f} bars is above the saturation pressure ({:.1f} bars) for this sample. \"\n \"Results from this calculation may be nonsensical.\".format(pressure, satP))\n\n # Use sympy to solve solubility equation for XH2Ofluid\n XH2Ofluid = sympy.symbols('XH2Ofluid') # XH2Ofluid is the variable to solve for\n\n equation = ((354.94*(XH2Ofluid*pressureMPa)**(0.5) + 9.623*(XH2Ofluid*pressureMPa)\n - 1.5223*(XH2Ofluid*pressureMPa)**(1.5)) / temperatureK\n + 0.0012439*(XH2Ofluid*pressureMPa)**(1.5)\n + pressureMPa*(1-XH2Ofluid)*(-1.084*10**(-4)*(XH2Ofluid*pressureMPa)**(0.5)\n - 1.362*10**(-5)*(XH2Ofluid*pressureMPa)) - H2Ot)\n\n XH2Ofluid = sympy.solve(equation, XH2Ofluid)[0]\n if XH2Ofluid > 1:\n XH2Ofluid = 1\n if XH2Ofluid < 0:\n XH2Ofluid = 0\n\n return XH2Ofluid\n\n def calculate_saturation_pressure(self, temperature, sample, X_fluid=1.0, **kwargs):\n \"\"\"\n Calculates the pressure at which a an H2O-bearing fluid is saturated. Calls the\n scipy.root_scalar routine, which makes repeated called to the\n calculate_dissolved_volatiles method.\n\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n temperature float\n Temperature in degrees C.\n\n X_fluid float\n OPTIONAL. Default is 1.0. Mole fraction of H2O in the H2O-CO2 fluid.\n\n Returns\n -------\n float\n Calculated saturation pressure in bars.\n \"\"\"\n\n temperatureK = temperature + 273.15\n if temperatureK <= 0.0:\n raise core.InputError(\"Temperature must be greater than 0K.\")\n if X_fluid < 0 or X_fluid > 1:\n raise core.InputError(\"X_fluid must have a value between 0 and 1.\")\n if isinstance(sample, sample_class.Sample) is False:\n raise core.InputError(\"Sample must be an instance of the Sample class.\")\n if sample.check_oxide('H2O') is False:\n raise core.InputError(\"sample must contain H2O.\")\n if sample.get_composition('H2O') < 0.0:\n raise core.InputError(\"Dissolved H2O concentration must be greater than 0 wt%.\")\n\n try:\n satP = root_scalar(self.root_saturation_pressure,\n args=(temperature, sample, X_fluid, kwargs),\n x0=1.0, x1=2.0).root\n except Exception:\n w.warn(\"Saturation pressure not found.\", RuntimeWarning, stacklevel=2)\n satP = np.nan\n return np.real(satP)\n\n def root_saturation_pressure(self, pressure, temperature, sample, X_fluid, kwargs):\n \"\"\" Function called by scipy.root_scalar when finding the saturation pressure using\n calculate_saturation_pressure.\n\n Parameters\n ----------\n pressure float\n Pressure guess in bars\n temperature float\n The temperature of the system in C.\n sample: Sample class\n Magma major element composition, including H2O.\n kwargs dictionary\n Additional keyword arguments supplied to calculate_saturation_pressure. Might be\n required for the fugacity or activity models.\n\n Returns\n -------\n float\n The differece between the dissolved H2O at the pressure guessed, and the H2O\n concentration passed in the sample variable.\n \"\"\"\n return (self.calculate_dissolved_volatiles(pressure=pressure, temperature=temperature,\n sample=sample, X_fluid=X_fluid, **kwargs) -\n sample.get_composition('H2O'))\n\n\nclass carbon(model_classes.Model):\n \"\"\"\n Implementation of the Liu et al. (2005) H2O-CO2 solubility model for metaluminous high-silica\n rhyolitic melts.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the model.\n \"\"\"\n self.set_volatile_species(['CO2'])\n self.set_fugacity_model(fugacity_models.fugacity_idealgas())\n self.set_activity_model(activity_models.activity_idealsolution())\n self.set_solubility_dependence(False)\n\n # Generate calibration range objects for each oxide\n cr_oxide_list = []\n for ox in carboncomprange.keys():\n cr_oxide_list.append(\n calibration_checks.CalibrationRange(\n ox, carboncomprange[ox], calibration_checks.crf_Between, 'wt%',\n 'Liu et al. (2005) carbon',\n fail_msg=calibration_checks.crmsg_BC_fail,\n pass_msg=calibration_checks.crmsg_BC_pass,\n description_msg=calibration_checks.crmsg_Between_description))\n\n self.set_calibration_ranges([\n calibration_checks.CalibrationRange(\n 'pressure', [0, 5000.0], calibration_checks.crf_Between, 'bar',\n 'Liu et al. (2005) Carbon',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'temperature', [700.0, 1200], calibration_checks.crf_Between, 'oC',\n 'Liu et al. (2005) Carbon',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'sample', None, crf_CarbonComp, None, None,\n fail_msg=crmsg_CarbonComp_fail,\n pass_msg=crmsg_Comp_pass,\n description_msg=crmsg_Comp_description)] + cr_oxide_list)\n\n def calculate_dissolved_volatiles(self, sample, pressure, temperature, X_fluid=1, **kwargs):\n \"\"\"\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n pressure float\n Pressure in bars.\n\n temperature float\n Temperature in degrees C.\n\n X_fluid float\n OPTIONAL. Default is 1. Mole fraction of CO2 in the H2O-CO2 fluid.\n\n Returns\n -------\n float\n Calculated dissolved CO2 concentration in wt%.\n \"\"\"\n pressureMPa = pressure / 10.0\n Pw = pressureMPa * (1 - X_fluid)\n PCO2 = pressureMPa * X_fluid\n\n temperatureK = temperature + 273.15\n\n CO2melt_ppm = (PCO2*(5668 - 55.99*Pw)/temperatureK\n + PCO2*(0.4133*Pw**(0.5) + 2.041*10**(-3)*Pw**(1.5)))\n\n CO2melt = CO2melt_ppm / 10000\n\n return CO2melt\n\n def calculate_equilibrium_fluid_comp(self, sample, pressure, temperature, **kwargs):\n \"\"\"\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n pressure float\n Pressure in bars.\n\n temperature float\n Temperature in degrees C.\n\n Returns\n -------\n float\n Calculated equilibrium fluid concentration in XCO2fluid mole fraction.\n \"\"\"\n temperatureK = temperature + 273.15\n pressureMPa = pressure / 10.0\n\n if temperatureK <= 0.0:\n raise core.InputError(\"Temperature must be greater than 0K.\")\n if isinstance(sample, sample_class.Sample) is False:\n raise core.InputError(\"Sample must be an instance of the Sample class.\")\n if sample.check_oxide('CO2') is False:\n raise core.InputError(\"sample must contain CO2.\")\n if sample.get_composition('CO2') < 0.0:\n raise core.InputError(\"Dissolved CO2 concentration must be greater than 0 wt%.\")\n\n CO2melt_wt = sample.get_composition(\"CO2\")\n CO2melt_ppm = CO2melt_wt * 10000\n\n # calculate saturation pressure and assert that input P <= SatP\n satP = self.calculate_saturation_pressure(temperature, sample)\n is_saturated = satP - pressure\n if is_saturated >= 0:\n pass\n else:\n w.warn(str(pressure) + \" bars is above the saturation pressure (\" + str(satP) +\n \" bars) for this sample. Results from this calculation may be nonsensical.\")\n\n # Use sympy to solve solubility equation for XH2Ofluid\n XCO2fluid = sympy.symbols('XCO2fluid') # XCO2fluid is the variable to solve for\n\n equation = ((XCO2fluid*pressureMPa*(5668 - 55.99*(pressureMPa*(1-XCO2fluid)))/temperatureK\n + (XCO2fluid*pressureMPa)*(0.4133*(pressureMPa*(1-XCO2fluid))**(0.5)\n + 2.041*10**(-3)*(pressureMPa*(1-XCO2fluid))**(1.5))) - CO2melt_ppm)\n\n XCO2fluid = sympy.solve(equation, XCO2fluid, real=True)[0]\n\n if type(XCO2fluid) != float:\n w.warn(\"Could not find equilibrium fluid composition.\")\n return 0\n else:\n if XCO2fluid > 1:\n XCO2fluid = 1\n if XCO2fluid < 0:\n XCO2fluid = 0\n\n return XCO2fluid\n\n def calculate_saturation_pressure(self, temperature, sample, X_fluid=1.0, **kwargs):\n \"\"\"\n Calculates the pressure at which a an CO2-bearing fluid is saturated. Calls the\n scipy.root_scalar routine, which makes repeated called to the\n calculate_dissolved_volatiles method.\n\n Parameters\n ----------\n sample: Sample class\n Magma major element composition.\n\n temperature float\n Temperature in degrees C.\n\n X_fluid float\n OPTIONAL. Default is 0. Mole fraction of CO2 in the H2O-CO2 fluid.\n\n Returns\n -------\n float\n Calculated saturation pressure in bars.\n \"\"\"\n\n temperatureK = temperature + 273.15\n if temperatureK <= 0.0:\n raise core.InputError(\"Temperature must be greater than 0K.\")\n if X_fluid < 0 or X_fluid > 1:\n raise core.InputError(\"X_fluid must have a value between 0 and 1.\")\n if isinstance(sample, sample_class.Sample) is False:\n raise core.InputError(\"Sample must be an instance of the Sample class.\")\n if sample.check_oxide('CO2') is False:\n raise core.InputError(\"sample must contain CO2.\")\n if sample.get_composition('CO2') < 0.0:\n raise core.InputError(\"Dissolved CO2 concentration must be greater than 0 wt%.\")\n\n try:\n satP = root_scalar(self.root_saturation_pressure,\n args=(temperature, sample, X_fluid, kwargs),\n x0=10.0, x1=2000.0).root\n except Exception:\n w.warn(\"Saturation pressure not found.\", RuntimeWarning, stacklevel=2)\n satP = np.nan\n return np.real(satP)\n\n def root_saturation_pressure(self, pressure, temperature, sample, X_fluid, kwargs):\n \"\"\" Function called by scipy.root_scalar when finding the saturation pressure using\n calculate_saturation_pressure.\n\n Parameters\n ----------\n pressure float\n Pressure guess in bars\n temperature float\n The temperature of the system in C.\n sample: Sample class\n Magma major element composition, including H2O.\n kwargs dictionary\n Additional keyword arguments supplied to calculate_saturation_pressure. Might be\n required for the fugacity or activity models.\n\n Returns\n -------\n float\n The differece between the dissolved H2O at the pressure guessed, and the H2O\n concentration passed in the sample variable.\n \"\"\"\n return (self.calculate_dissolved_volatiles(pressure=pressure, temperature=temperature,\n sample=sample, X_fluid=X_fluid, **kwargs) -\n sample.get_composition('CO2'))\n\n\n# Defining compositional ranges for Liu - based on the Max value of the calibration dataset +-5%\n# of that value\nwatercomprange = {'SiO2': [71, 82],\n 'TiO2': [0, 0.21],\n 'FeO': [0, 1.5],\n 'Al2O3': [11.5, 14.2],\n 'MgO': [0, 0.18],\n 'CaO': [0, 1.2],\n 'Na2O': [3.2, 4.9],\n 'K2O': [3.4, 6.0]\n }\n\ncarboncomprange = {'SiO2': [73, 82],\n 'TiO2': [0.07, 0.12],\n 'FeO': [0.36, 1.1],\n 'Al2O3': [11.9, 13.7],\n 'MgO': [0.05, 0.08],\n 'CaO': [0.23, 0.6],\n 'Na2O': [3.9, 4.4],\n 'K2O': [4.0, 5.0]\n }\n\n\ndef crf_WaterComp(calibval=None, sample=sample_class.Sample({})):\n comp = sample.get_composition(units='wtpt_oxides')\n\n test_results = []\n for ox in watercomprange.keys():\n test_results.append(comp[ox] >= watercomprange[ox][0] and\n comp[ox] <= watercomprange[ox][1])\n\n return all(test_results)\n\n\ndef crf_CarbonComp(calibval=None, sample=sample_class.Sample({})):\n comp = sample.get_composition(units='wtpt_oxides')\n\n test_results = []\n for ox in carboncomprange.keys():\n test_results.append(comp[ox] >= carboncomprange[ox][0] and\n comp[ox] <= carboncomprange[ox][1])\n\n return all(test_results)\n\n\ndef crf_MixedComp(calibval=None, sample=sample_class.Sample({})):\n comp = sample.get_composition(units='wtpt_oxides')\n\n test_results = []\n for ox in carboncomprange.keys():\n test_results.append(comp[ox] >= np.min([watercomprange[ox][0], carboncomprange[ox][0]]))\n test_results.append(comp[ox] <= np.max([watercomprange[ox][1], carboncomprange[ox][1]]))\n\n return all(test_results)\n\n\ncrmsg_Comp_pass = (\"The sample appears to be similar in composition to the rhyolites and \"\n \"haplogranites used to calibrate the Liu et al. model.\")\ncrmsg_WaterComp_fail = (\" These calibration limits were selected based on the minimum and \"\n \"maximum values of these oxides (+-5%) in the Water calibration dataset. \"\n \"As the Liu et al. model incorperates no term for compositional \"\n \"dependence, users must take extreme care when extrapolating this model \"\n \"to compositions which differ significantly from the haplogranites and \"\n \"rhyolites in the calibration dataset. These warnings are simply a guide;\"\n \" we suggest that users carefully compare their major element data to the \"\n \"calibration dataset to check for suitability \")\ncrmsg_CarbonComp_fail = (\" These calibration limits were selected based on the minimum and \"\n \"maximum values of these oxides (+-5%) in the Carbon calibration dataset.\"\n \" As the Liu et al. model incorperates no term for compositional \"\n \"dependence, users must take extreme care when extrapolating this model \"\n \"to compositions which differ significantly from the haplogranites and \"\n \"rhyolites in the calibration dataset. These warnings are simply a guide;\"\n \" we suggest that users carefully compare their major element data to the\"\n \" calibration dataset to check for suitability \")\ncrmsg_Comp_fail = (\" These calibration limits were selected based on the minimum and maximum \"\n \"values of these oxides (+-5%) in the combined Water and Carbon calibration\"\n \" dataset. As the Liu et al. model incorperates no term for compositional \"\n \"dependence, users must take extreme care when extrapolating this model to \"\n \"compositions which differ significantly from the haplogranites and rhyolites \"\n \"in the calibration dataset. These warnings are simply a guide; we suggest that\"\n \" users carefully compare their major element data to the calibration dataset \"\n \"to check for suitability \")\ncrmsg_Comp_description = \"The Liu et al. model is suitable for haplogranites and rhyolites.\"\n\n\nmixed = model_classes.MixedFluid({'H2O': water(), 'CO2': carbon()})\n\n# Prevent the same error being returned for both H2O and CO2 when using the mixed model.\nmixed.models[1].set_calibration_ranges([])\n_crs_to_update = mixed.models[0].calibration_ranges\nfor _cr in _crs_to_update:\n _cr.model_name = 'Liu et al. (2005)'\n\ncr_oxide_list = []\nfor ox in carboncomprange.keys():\n lo = np.min([watercomprange[ox][0], carboncomprange[ox][0]])\n hi = np.max([watercomprange[ox][1], carboncomprange[ox][1]])\n cr_oxide_list.append(\n calibration_checks.CalibrationRange(\n ox, [lo, hi], calibration_checks.crf_Between, 'wt%', 'Liu et al. (2005)',\n fail_msg=calibration_checks.crmsg_BC_fail,\n pass_msg=calibration_checks.crmsg_BC_pass,\n description_msg=calibration_checks.crmsg_Between_description))\n\nmixed.models[0].set_calibration_ranges([\n calibration_checks.CalibrationRange(\n 'pressure', [0, 5000.0], calibration_checks.crf_Between, 'bar', 'Liu et al. (2005)',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'temperature', [700.0, 1200], calibration_checks.crf_Between, 'oC', 'Liu et al. (2005)',\n fail_msg=calibration_checks.crmsg_Between_fail,\n pass_msg=calibration_checks.crmsg_Between_pass,\n description_msg=calibration_checks.crmsg_Between_description),\n calibration_checks.CalibrationRange(\n 'sample', None, crf_MixedComp, None, None,\n fail_msg=crmsg_Comp_fail,\n pass_msg=crmsg_Comp_pass,\n description_msg=crmsg_Comp_description)] + cr_oxide_list)\n"
] |
[
[
"scipy.optimize.root_scalar",
"numpy.max",
"numpy.real",
"numpy.min"
]
] |
everdoubling/Korean-math-word-problems-solver
|
[
"55faec42462f9b99e8952ab900389b0621f21935"
] |
[
"legacy/template-jit.py"
] |
[
"# %%\nfrom numba import jit\n\nimport time\nimport re\nimport wordsim\nimport utils\nimport dataset\n\nimport numpy as np\n\n# pos tagging된 두 단어를 비교한 score를 계산, w1 = template tag, w2 = question tag\n# w = (str, POS, start, end)의 형식, start, end는 문장에서의 span 시작과 끝 index\n# 이상적으로는 str과 POS값을 모두 고려하여 score를 계산하여야 하지만 일단 POS값을 중요시하여 계산\n# POS값에 따른 score matrix를 생각할 수 있고, 이것을 자동학습 할 수 있으면 좋을듯\n# @jit(nopython=True)\ndef match_word_tags(w1, w2): \n if w1[1] == w2[1]: # POS가 같으면 페널티 없음\n return 0.0\n if w1[1] == 'NONE' or w2[1] == 'NONE': # 매칭되는 단어가 없어서 스킵할 경우\n return 0.6\n if w1[1] == 'WILDCARD':\n if w2[1][0] == 'N' or w2[1] == 'SL': # WILDCARD는 단어 또는 숫자에 매칭 가능\n return 0.0\n else:\n return 1000000.0#float('inf')\n if w1[1] == 'SF' or w2[1] == 'SF': # 마침표\n return 0.1\n # POS가 다른 단어끼리 매칭\n return 1.0\n\n# score_table = 1000000.0 * np.ones([100, 100])\n# # scores = np.zeros([100, 100])\n# scores = np.random.random([100, 100])\n# tracks1 = -1000000.0 * np.ones([100, 100])\n# tracks2 = -1000000.0 * np.ones([100, 100])\n\n# @jit(nopython=True)\n# 문장 비교, 비슷할 수록 낮은 값 리턴\ndef match_to_template_tags_jit(len_t, len_q, score_table, scores, tracks1, tracks2):\n # # score_table = [[1000000.0 for i in range(len(question_tags)+1)] for j in range(len(template_tags)+1)]\n # # assign_table = [['' for i in range(len(question_tags)+1)] for j in range(len(template_tags)+1)]\n # for repeat in range(10):\n # for i1 in range(0, len(template_tags)+1):\n # for i2 in range(0, len(question_tags)+1):\n # # score_table[i1][i2] = match_word_tags(\n # # template_tags[i1-1] if i1>0 else ('', 'NONE', None, None),\n # # question_tags[i2-1] if i2>0 else ('', 'NONE', None, None))\n # t_tag = template_tags[i1-1] if i1>0 else ('', 'NONE', -1, -1)\n # q_tag = question_tags[i2-1] if i2>0 else ('', 'NONE', -1, -1)\n # if t_tag[1] == q_tag[1]: # POS가 같으면 페널티 없음\n # s = 0.0\n # elif t_tag[1] == 'NONE' or q_tag[1] == 'NONE': # 매칭되는 단어가 없어서 스킵할 경우\n # s = 0.6\n # elif t_tag[1] == 'WILDCARD':\n # if q_tag[1][0] == 'N' or q_tag[1] == 'SL': # WILDCARD는 단어 또는 숫자에 매칭 가능\n # s = 0.0\n # else:\n # s = 1000000.0\n # elif t_tag[1] == 'SF' or q_tag[1] == 'SF': # 마침표\n # s = 0.1\n # # POS가 다른 단어끼리 매칭\n # else:\n # s = 1.0\n # score_table[i1][i2] = s\n # # scores[i1, i2] = 0.0\n\n # scores: question_tags[0:i1]과 template_tags[0:i2]를 매칭한 최적 스코어\n\n # return 1, 1\n # scores = [[1000000.0 for i in range(len(question_tags)+1)] for j in range(len(template_tags)+1)]\n # tracks1 = [[-1000000 for i in range(len(question_tags)+1)] for j in range(len(template_tags)+1)]\n # tracks2 = [[-1000000 for i in range(len(question_tags)+1)] for j in range(len(template_tags)+1)]\n for i1 in range(0, len_t+1):\n for i2 in range(0, len_q+1):\n scores[i1,i2], tracks1[i1][i2], tracks2[i1][i2] = 1000000.0, -1000000, -1000000\n if i1>0 and i2>0 and scores[i1,i2] > scores[i1-1,i2-1] + score_table[i1][i2]:\n scores[i1,i2] = scores[i1-1,i2-1] + score_table[i1][i2]\n tracks1[i1][i2] = i1-1\n tracks2[i1][i2] = i2-1\n if i2>0 and scores[i1,i2] > scores[i1,i2-1] + score_table[0][i2]:\n scores[i1,i2] = scores[i1,i2-1] + score_table[0][i2]\n tracks1[i1][i2] = i1\n tracks2[i1][i2] = i2-1\n if i1>0 and scores[i1,i2] > scores[i1-1,i2] + score_table[i1][0]:\n scores[i1,i2] = scores[i1-1,i2] + score_table[i1][0]\n tracks1[i1][i2] = i1-1\n tracks2[i1][i2] = i2\n if i1==0 and i2==0:\n scores[i1,i2], tracks1[i1][i2], tracks2[i1][i2] = 0.0, -1000000, -1000000\n\n return scores, tracks1, tracks2\n return scores[-1][-1], 1\n correspondence = []\n assignments = dict()\n i1, i2 = len(template_tags), len(question_tags)\n while True:\n if i1 == -1000000 or i2 == -1000000:\n break\n if tracks1[i1][i2] == i1 - 1 and tracks2[i1][i2] == i2 - 1: # 실제 tags사이에 매칭이 일어난 경우 (None과 매칭되지 않고) WILDCARD에 대응되는 값을 assignments에 추가\n if template_tags[i1-1][1] == 'WILDCARD':\n name = template_tags[i1-1][0][1:]\n # if name not in assignments:\n # assignments[name] = set()\n # assignments[name].add(question_tags[i2-1])\n assignments[name] = question_tags[i2-1]\n correspondence.append((i1, i2, scores[i1,i2]))\n i1, i2 = tracks1[i1][i2], tracks2[i1][i2]\n # def backtrack(i1, i2):\n # if i1 == -1000000 or i2 == -1000000:\n # return\n # if tracks1[i1][i2] == i1 - 1 and tracks2[i1][i2] == i2 - 1: # 실제 tags사이에 매칭이 일어난 경우 (None과 매칭되지 않고) WILDCARD에 대응되는 값을 assignments에 추가\n # if template_tags[i1-1][1] == 'WILDCARD':\n # name = template_tags[i1-1][0][1:]\n # # if name not in assignments:\n # # assignments[name] = set()\n # # assignments[name].add(question_tags[i2-1])\n # correspondence.append((i1, i2, scores[i1][i2]))\n # backtrack(tracks1[i1][i2], tracks2[i1][i2])\n # backtrack(len(template_tags), len(question_tags))\n # return scores[-1][-1], assignments\n # return scores[-1][-1], assignments\n\n if visualize:\n last = (0, 0, 0.0)\n for i in range(len(correspondence), 0, -1):\n match = correspondence[i-1]\n left = template_tags[match[0]-1] if match[0] > last[0] else (' ', 'NONE', -1, -1)\n right = question_tags[match[1]-1] if match[1] > last[1] else (' ', 'NONE', -1, -1)\n print((' (' + left[0] + ' ' + left[1] + ') --- (' + right[0] + ' ' + right[1] + ')', match[2] - last[2]))\n last = match\n print(('matching score = ', scores[-1,-1]))\n\n return scores[-1,-1], assignments\n\n# match_to_template_tags(utils.pos_tagging('상자 안에 5개의 감이 있습니다.'), utils.pos_tagging('상자 안에 5개의 감이 있습니다.'))\n# match_to_template_tags(utils.pos_tagging('상자 안에 @0개의 감이 있습니다.'), utils.pos_tagging('박스 안에 5개의 과일이 있다.'))\n\n# @jit(nopython=True)\n# def test_func(score_table, scores, tracks1, tracks2, visualize=False):\n \n# return 1, 1\n\ndef match_to_template_tags(template_tags, question_tags, visualize=False):\n len_t, len_q = len(template_tags)+1, len(question_tags)+1\n score_table = 1000000.0 * np.ones([len_t+1, len_q+1])\n for i1 in range(0, len(template_tags)+1):\n for i2 in range(0, len(question_tags)+1):\n # score_table[i1][i2] = match_word_tags(\n # template_tags[i1-1] if i1>0 else ('', 'NONE', None, None),\n # question_tags[i2-1] if i2>0 else ('', 'NONE', None, None))\n t_tag = template_tags[i1-1] if i1>0 else ('', 'NONE', -1, -1)\n q_tag = question_tags[i2-1] if i2>0 else ('', 'NONE', -1, -1)\n if t_tag[1] == q_tag[1]: # POS가 같으면 페널티 없음\n s = 0.0\n elif t_tag[1] == 'NONE' or q_tag[1] == 'NONE': # 매칭되는 단어가 없어서 스킵할 경우\n s = 0.6\n elif t_tag[1] == 'WILDCARD':\n if q_tag[1][0] == 'N' or q_tag[1] == 'SL': # WILDCARD는 단어 또는 숫자에 매칭 가능\n s = 0.0\n else:\n s = 1000000.0\n elif t_tag[1] == 'SF' or q_tag[1] == 'SF': # 마침표\n s = 0.1\n # POS가 다른 단어끼리 매칭\n else:\n s = 1.0\n score_table[i1][i2] = s\n # scores[i1, i2] = 0.0\n\n scores = np.zeros([len_t+1, len_q+1])\n tracks1 = -1000000.0 * np.ones([len_t+1, len_q+1])\n tracks2 = -1000000.0 * np.ones([len_t+1, len_q+1])\n scores, tracks1, tracks2 = match_to_template_tags_jit(len_t, len_q, score_table, scores, tracks1, tracks2)\n\n correspondence = []\n assignments = dict()\n i1, i2 = len_t, len_q\n while True:\n if i1 == -1000000 or i2 == -1000000:\n break\n if tracks1[i1][i2] == i1 - 1 and tracks2[i1][i2] == i2 - 1: # 실제 tags사이에 매칭이 일어난 경우 (None과 매칭되지 않고) WILDCARD에 대응되는 값을 assignments에 추가\n if template_tags[i1-1][1] == 'WILDCARD':\n name = template_tags[i1-1][0][1:]\n if name not in assignments:\n assignments[name] = set()\n assignments[name].add(question_tags[i2-1])\n # assignments[name] = question_tags[i2-1]\n correspondence.append((i1, i2, scores[i1,i2]))\n i1, i2 = tracks1[i1][i2], tracks2[i1][i2]\n\n if visualize:\n last = (0, 0, 0.0)\n for i in range(len(correspondence), 0, -1):\n match = correspondence[i-1]\n left = template_tags[match[0]-1] if match[0] > last[0] else (' ', 'NONE', -1, -1)\n right = question_tags[match[1]-1] if match[1] > last[1] else (' ', 'NONE', -1, -1)\n print((' (' + left[0] + ' ' + left[1] + ') --- (' + right[0] + ' ' + right[1] + ')', match[2] - last[2]))\n last = match\n print(('matching score = ', scores[-1,-1]))\n\n return scores[-1,-1], assignments\n\ndef find_closest(problem):\n closest_distance, best_pattern, best_assignments = float('inf'), None, None\n datasets = [dataset.dataset_csv, dataset.dataset_csv_qanda] # 사용할 데이터셋\n dists = []\n for dset in datasets:\n for template in dset:\n if utils.is_pruning(template['question_pruning'], problem['pruning_vector']):\n continue\n if template['extracted_lists'].keys() != problem['extracted_lists'].keys():\n continue\n if (len(template['extracted_equations']) > 0) != (len(problem['extracted_equations']) > 0):\n continue\n # distance, assignments = match_to_template(problem['question_preprocessed'], template)\n distance, assignments = match_to_template_tags(template['template_tags'], problem['question_tags'])\n if distance < closest_distance:\n closest_distance, best_pattern, best_assignments = distance, template, assignments\n\n dists.append([distance, template, assignments])\n # if distance < 10:\n # template = template['template']\n # print(f' matching distance = {distance}')\n # print(f' matching template = {template}')\n # print(f' matching assignments = {assignments}')\n\n problem['closest_k'] = sorted(dists, key=lambda x: x[0])[:10]\n\n return closest_distance, best_pattern, best_assignments\n\ndef find_template(problem):\n problem['pruning_vector'] = utils.pruning_vector(problem['question_preprocessed'])\n # 문제에서 숫자열이나 문자열 패턴이 발견되면 추출해내고, 추출한 부분을 제외한 문장으로 매칭을 시도한다.\n problem['extracted_lists'], problem['question_preprocessed'] = utils.extract_lists(problem['question_preprocessed'])\n problem['extracted_equations'], problem['question_preprocessed'] = utils.extract_equations(problem['question_preprocessed'])\n\n problem['question_tags'] = utils.pos_tagging(problem['question_preprocessed'])\n\n # question = problem['question_preprocessed']\n distance, matched, assignments = find_closest(problem)\n\n print(f'best match distance = {distance}')\n print(f'best match template = {matched}')\n print(f'best match template candidate assigments = {assignments}')\n values = [x for x in matched['template_values']]\n # for idx, valueset in enumerate(assignments):\n # if len(valueset) > 0:\n # values[idx] = list(valueset)[0]\n for key in assignments:\n assignments[key] = list(assignments[key])[0][0]\n print(f'best match template final assigments = {values}')\n print('extracted question lists = ' + str(problem['extracted_lists']))\n print('extracted question equations = ' + str(problem['extracted_equations']))\n\n # problem['extracted_lists'] = extracted_lists\n # problem['extracted_equations'] = extracted_equations\n problem['best_template_distance'] = distance\n problem['best_template'] = matched\n problem['best_template_assignment'] = assignments\n\n # 매칭된 템플릿을 이용하여 statements(lists, equation, code, objective) 구성\n # statements는 풀이과정과 답안을 구하기 위한 충분정보가 포함되어야 한다.\n statements = dict()\n field_names = ['equation', 'code', 'objective']\n for fn in field_names:\n statements[fn] = []\n if problem['extracted_lists']:\n if 'numbers' in problem['extracted_lists']:\n statements['code'].append('numbers=' + str(problem['extracted_lists']['numbers']))\n if 'strings' in problem['extracted_lists']:\n statements['code'].append('strings=' + str(problem['extracted_lists']['strings']))\n if problem['extracted_equations']:\n for eq in problem['extracted_equations']:\n statements['equation'].append(eq)\n for fn in field_names:\n if 'template_'+fn not in matched:\n continue\n for line in matched['template_'+fn]:\n for key in assignments:\n line = re.sub(f'(@{key})($|\\D)', assignments[key] + '\\\\g<2>', line)\n # line = re.sub(f'\\\\b@{idx}\\\\b', v, line)\n statements[fn].append(line)\n\n print(f'statements = {statements}')\n problem['statements'] = statements\n\n return distance, statements\n\n# %%\n# score, assignments = match_to_template_tags(\n# utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n# utils.pos_tagging('버스에 22명이 타고 있습니다. 그 중 118명이 내렸을 때, 버스에 남아있는 있는 사람은 얼마입니까?'),\n# visualize=True)\n# score, assignments = match_to_template_tags(\n# utils.pos_tagging('비행기에 351명이 타고 있습니다. 그 중 158명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n# utils.pos_tagging('달력에서 31일까지 있는 연속 된 2달 중, 더 나중에 있는 달은 언제 입니까?'),\n# visualize=True)\n# score, assignments = match_to_template_tags(utils.pos_tagging('상자 안에 @0개의 감이 있습니다.'), utils.pos_tagging('박스 안에 5개의 과일이 있다.'), visualize=True)\n# score, assignments = match_to_template_tags(\n# utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 @1개를 택하여 1개의 접시에 담으려고 합니다. @2과 @0을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n# utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 포도와 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n# visualize=True)\n# score, assignments = match_to_template_tags(\n# utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 @1개를 택하여 $1개의 접시에 담으려고 합니다. @3과 @0을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n# utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 감과 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n# visualize=True)\n\nscore, assignments = match_to_template_tags(\n utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 감과 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n visualize=True)\n\nstart_time = time.time()\nfor i in range(1000):\n # utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?')\n # utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 감과 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?')\n # score, assignments = match_to_template_tags(\n # utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n # utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 감과 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?'))\n score, assignments = match_to_template_tags(\n utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n utils.pos_tagging('버스에 22명이 타고 있습니다. 그 중 118명이 내렸을 때, 버스에 남아있는 있는 사람은 얼마입니까?'))\nprint(time.time() - start_time)\n# score, assignments = match_to_template_tags(\n# utils.pos_tagging('비행기에 @0명이 타고 있습니다. 그 중 @1명이 내렸습니다. 비행기에 타고 있는 인원은 얼마입니까?'),\n# utils.pos_tagging('@strings 각각 1개씩 있습니다. 이 중 3개를 택하여 한 개의 접시에 담으려고 합니다. 감과 귤을 함께 담지 않는 방법은 모두 몇 가지입니까?'),\n# visualize=True)\n# print(score)\n# print(assignments)\n"
] |
[
[
"numpy.zeros",
"numpy.ones"
]
] |
AmarSaini/Cost-Based-Optimization
|
[
"c6a2fcd930ac915a3d09585ff285b5bea0653a32"
] |
[
"Cost Based Optimization.py"
] |
[
"import math\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras import optimizers\nfrom keras import callbacks\n\n# ----- Global Variables -----\n\n# Feature Size\nfeatureSize = 0\n\n\ndef fit(x, a, b):\n return a/(x**b)\n\ndef loadData(fileName, dataSize, featureSize):\n\n myFile = open(fileName)\n\n # 57514 negatives, 1731 positives\n examples = np.zeros((dataSize, featureSize), float)\n labels = np.zeros(dataSize, int)\n\n index = 0\n\n for myLine in myFile:\n #print(lineNum)\n myPairs = myLine.split(\" \")\n\n if(myPairs[0] == \"+1\"):\n labels[index] = 1\n\n else:\n labels[index] = -1\n\n myPairs.pop(0)\n myPairs.pop()\n for onePair in myPairs:\n splitPair = onePair.split(\":\");\n examples[index][int(splitPair[0])-1] = float(splitPair[1])\n index += 1\n\n myFile.close()\n\n return [examples, labels]\n\ndef fitGD(deltaLosses, timePerIter, desiredError):\n\n # Fit the error to our curve. \n # Our curve is a function that takes in an error, and outputs the number of iterations needed to achieve that error.\n \n # popt holds the optimal fitted parameter values\n iterations = np.arange(len(deltaLosses))\n iterations += 1\n\n popt, pcov = curve_fit(fit, deltaLosses, iterations)\n\n # Get the estimated number of iterations for the desired error\n estimatedIter = int(fit(desiredError, *popt))\n estimatedTotalTime = estimatedIter*timePerIter\n\n # Plot the error points, and the fitted curve\n plt.plot(deltaLosses, iterations, 'ro')\n plt.plot(deltaLosses, fit(deltaLosses, *popt), 'b', label='Speculated Change In Loss: %.5f \\nEstimated Iter: %d \\nTime Per Iter: %.4f \\nEstimated Total Time: %.2f \\nfit: a=%.4f b=%.4f' % (desiredError, estimatedIter, timePerIter, estimatedTotalTime, popt[0], popt[1]))\n\n plt.ylabel('Iterations')\n plt.xlabel('Change in Loss')\n plt.legend()\n\n print('Speculated Change In Loss: {0}, Estimated Iter: {1}, Time per Iter: {2}, ETA for Convergence {3}'.format(desiredError, estimatedIter, timePerIter, estimatedTotalTime))\n\n return estimatedIter, estimatedTotalTime\n\ndef testKeras(examples, labels, subsetPercent = 0.2, desiredError = 0.001, timeLimit = 30):\n\n # Test each algorithm on a smaller dataset.\n\n exampleSubset = examples[0:int(len(examples)*subsetPercent)]\n labelSubset = labels[0:int(len(labels)*subsetPercent)]\n\n max_iterations = 10000\n estimatedIters = []\n\n allResults = []\n\n for i in range(7):\n\n plt.figure(i+1)\n\n # Create Model for Keras\n model = Sequential()\n model.add(Dense(units=1, activation='linear', input_dim=featureSize))\n\n # Choose GD Algorithm for Keras\n if (i == 0):\n myOpt = optimizers.SGD(lr=0.01, momentum=0., decay=0., nesterov=False)\n plt.title(\"SGD\")\n elif (i == 1):\n myOpt = optimizers.SGD(lr=0.01, momentum=0.9, decay=0., nesterov=False)\n plt.title(\"Momentum\")\n elif (i == 2):\n myOpt = optimizers.SGD(lr=0.01, momentum=0.9, decay=0., nesterov=True)\n plt.title(\"Nesterov-Momentum\")\n elif (i == 3):\n myOpt = optimizers.Adagrad(lr=0.01, epsilon=1e-6)\n plt.title(\"Adagrad\")\n elif (i == 4):\n myOpt = optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-6)\n plt.title(\"Adadelta\")\n elif (i == 5):\n myOpt = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-6)\n plt.title(\"RMSprop\")\n elif (i == 6):\n myOpt = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)\n plt.title(\"Adam\")\n\n model.compile(optimizer=myOpt, loss=logloss)\n\n # Create Custom Callback. Run GD. History saved in output. Use it to find the changes in loss per iteration\n customCallback = EarlyStoppingByDeltaLossOrTime(desiredError, timeLimit)\n myCallbacks = [customCallback]\n output = model.fit(exampleSubset, labelSubset, epochs=max_iterations, batch_size=int(len(exampleSubset)/50), callbacks=myCallbacks)\n losses = np.array(output.history['loss'])\n deltaLosses = -np.diff(losses)\n\n # Run again on the full dataset, for a few iterations. Use this to find the average time per iteration.\n # Reset callback to reset time elapsed and history of losses.\n model = Sequential()\n model.add(Dense(units=1, activation='linear', input_dim=featureSize))\n model.compile(optimizer=myOpt, loss=logloss)\n customCallback = EarlyStoppingByDeltaLossOrTime(desiredError, timeLimit)\n myCallbacks = [customCallback]\n output = model.fit(examples, labels, epochs=5, batch_size=int(len(examples)/50), callbacks=myCallbacks)\n losses = np.array(output.history['loss'])\n timePerIter = myCallbacks[0].timeElapsed/len(losses)\n\n # Pass in the following:\n # 1. Array of DeltaLosses, iterations is length of array.\n # 2. Average Time per Iteration on the full dataset.\n results = fitGD(deltaLosses, timePerIter, desiredError)\n estimatedIters.append(results[0])\n print(\"ETI: \", results[0])\n print(\"ETA: \", results[1])\n\n allResults.append(results)\n\n for i in range(len(allResults)):\n print(\"Algo\", i, \"Iterations:\", allResults[i][0], \"ETA:\", allResults[i][1])\n\n plt.show()\n\n return estimatedIters\n\ndef logloss(y_true, y_pred): # define a custom tensorflow loss function\n return tf.log(1 + tf.exp(-y_true * y_pred))\n\nclass EarlyStoppingByDeltaLossOrTime(callbacks.Callback):\n def __init__(self, deltaLoss, timeLimit, logs={}):\n\n self.deltaLoss = deltaLoss\n self.timeLimit = timeLimit\n\n self.losses = [1.0]\n self.startTime = time.time()\n self.timeElapsed = 0\n\n def on_epoch_end(self, batch, logs={}):\n\n self.losses.append(logs.get('loss'))\n lossesSize = len(self.losses)\n\n changeinLoss = self.losses[lossesSize-2] - self.losses[lossesSize-1]\n self.timeElapsed = time.time() - self.startTime\n print(\"Change in Loss: \", changeinLoss)\n print(\"Total Time: \", self.timeElapsed)\n\n if (changeinLoss <= self.deltaLoss or self.timeElapsed >= self.timeLimit):\n self.model.stop_training = True\n\nclass PrintDeltaLossAndTime(callbacks.Callback):\n def __init__(self, logs={}):\n\n self.losses = [1.0]\n self.startTime = time.time()\n self.timeElapsed = 0\n\n def on_epoch_end(self, batch, logs={}):\n\n self.losses.append(logs.get('loss'))\n lossesSize = len(self.losses)\n\n changeinLoss = self.losses[lossesSize-2] - self.losses[lossesSize-1]\n self.timeElapsed = time.time() - self.startTime\n print(\"Change in Loss: \", changeinLoss)\n print(\"Total Time: \", self.timeElapsed)\n\n\ndef main():\n\n global svrg;\n global adaGrad;\n\n # Set up data\n\n # -------- Make sure you change the featureSize variable below to the correct dimension --------\n\n #result = loadData('a1a.t', 30956, 123)\n result = loadData('w8a.txt', 59245, 300)\n #result = loadData('covtype.libsvm.binary.scale', 581012, 54)\n \n examples = result[0]\n labels = result[1]\n\n #np.save(\"examples.npy\", examples)\n #np.save(\"labels.npy\", labels)\n\n #examples = np.load('examples.npy')\n #labels = np.load('labels.npy')\n\n\n global featureSize\n featureSize = 300\n\n # Test Keras\n estimatedIters = testKeras(examples, labels)\n\n print(\"Choosing GD Plan...\")\n\n while(1):\n\n print(\"0 - SGD\")\n print(\"1 - Momentum\")\n print(\"2 - Nesterov-Momentum\")\n print(\"3 - Adagrad\")\n print(\"4 - Adadelta\")\n print(\"5 - RMSprop\")\n print(\"6 - Adam\")\n\n algoChoice = int(input(\"Choose Algo: \"))\n\n # Create Model for Keras\n model = Sequential()\n model.add(Dense(units=1, activation='linear', input_dim=featureSize))\n\n # Choose GD Algorithm for Keras\n if (algoChoice == 0):\n myOpt = optimizers.SGD(lr=0.01, momentum=0., decay=0., nesterov=False)\n elif (algoChoice == 1):\n myOpt = optimizers.SGD(lr=0.01, momentum=0.9, decay=0., nesterov=False)\n elif (algoChoice == 2):\n myOpt = optimizers.SGD(lr=0.01, momentum=0.9, decay=0., nesterov=True)\n elif (algoChoice == 3):\n myOpt = optimizers.Adagrad(lr=0.01, epsilon=1e-6)\n elif (algoChoice == 4):\n myOpt = optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-6)\n elif (algoChoice == 5):\n myOpt = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-6)\n elif (algoChoice == 6):\n myOpt = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)\n\n model.compile(optimizer=myOpt, loss=logloss)\n\n # To get results, use early stop, double iter.\n customCallback = PrintDeltaLossAndTime()\n myCallbacks = [customCallback]\n output = model.fit(examples, labels, epochs=estimatedIters[algoChoice], batch_size=int(len(examples)/50), callbacks=myCallbacks)\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"tensorflow.exp",
"matplotlib.pyplot.plot",
"numpy.diff",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"scipy.optimize.curve_fit",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
] |
dem123456789/Speech-Emotion-Recognition-with-Dual-Sequence-LSTM-Architecture
|
[
"a072cb940201bbcdb2d0f4d0dfa1dde478fa4464"
] |
[
"src/speech/model_joint.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pdb\nimport numpy as np\nfrom torch.nn.utils.rnn import pad_packed_sequence, pad_sequence, pack_padded_sequence\n\noutput = []\n\nclass LSTM_Audio(nn.Module):\n def __init__(self, hidden_dim, num_layers, device,dropout_rate=0 ,bidirectional=False):\n super(LSTM_Audio, self).__init__()\n self.device = device\n self.num_features = 39\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n self.dropout_rate = dropout_rate\n self.bidirectional = bidirectional\n self.lstm = nn.LSTM(self.num_features, self.hidden_dim, self.num_layers, batch_first=True,\n dropout=self.dropout_rate, bidirectional=self.bidirectional).to(self.device)\n\n def forward(self, input):\n input = input.to(self.device)\n out, hn = self.lstm(input)\n return out\n\nclass ConvLSTMCell(nn.Module):\n def __init__(self, input_channels, hidden_channels, kernel_size, kernel_size_pool, kernel_stride_pool,device, dropout=0.1):\n super(ConvLSTMCell, self).__init__()\n\n self.input_channels = input_channels\n self.hidden_channels = hidden_channels\n self.kernel_size = kernel_size\n self.stride=1\n self.padding = (int((kernel_size[0]-1) / 2),int((kernel_size[1]-1) / 2))\n self.kernel_size_pool=kernel_size_pool\n self.kernel_stride_pool=kernel_stride_pool\n self.padding_pool=(int((kernel_size_pool[0]-1)/2),int((kernel_size_pool[1]-1)/2))\n\n\n self.Wxi = nn.Conv2d(self.input_channels, self.hidden_channels, self.kernel_size, self.stride,self.padding, bias=True)\n self.Whi = nn.Conv2d(self.hidden_channels, self.hidden_channels, self.kernel_size, self.stride, self.padding, bias=False)\n\n self.Wxf = nn.Conv2d(self.input_channels, self.hidden_channels, self.kernel_size, self.stride,self.padding, bias=True)\n self.Whf = nn.Conv2d(self.hidden_channels, self.hidden_channels, self.kernel_size, self.stride,self.padding, bias=False)\n\n self.Wxc = nn.Conv2d(self.input_channels, self.hidden_channels, self.kernel_size, self.stride, self.padding, bias=True)\n self.Whc = nn.Conv2d(self.hidden_channels, self.hidden_channels, self.kernel_size, self.stride, self.padding, bias=False)\n\n self.Wxo = nn.Conv2d(self.input_channels, self.hidden_channels, self.kernel_size, self.stride,self.padding, bias=True)\n self.Who = nn.Conv2d(self.hidden_channels, self.hidden_channels, self.kernel_size, self.stride, self.padding, bias=False)\n\n self.max_pool = nn.MaxPool2d(self.kernel_size_pool, stride=self.kernel_stride_pool, padding=self.padding_pool)\n self.batch = nn.BatchNorm2d(self.hidden_channels)\n\n self.dropout=nn.Dropout(p=dropout, inplace=False)\n\n self.Wci = None\n self.Wcf = None\n self.Wco = None\n self.device=device\n\n\n def forward(self, x, h, c):\n ci = torch.sigmoid(self.Wxi(x) + self.Whi(h) + c * self.Wci)\n cf = torch.sigmoid(self.Wxf(x) + self.Whf(h) + c * self.Wcf)\n cc = cf * c + ci * torch.tanh(self.Wxc(x) + self.Whc(h))\n co = torch.sigmoid(self.Wxo(x) + self.Who(h) + cc * self.Wco)\n ch = co * torch.tanh(cc)\n ch_pool=self.batch(self.max_pool(ch))\n #ch_pool=self.dropout(ch_pool)\n return ch_pool, ch, cc\n\n def init_hidden(self, batch_size, hidden, shape):\n\n if self.Wci is None:\n self.Wci = nn.Parameter(torch.zeros(1, hidden, shape[0],shape[1])).to(self.device)\n self.Wcf = nn.Parameter(torch.zeros(1, hidden, shape[0],shape[1])).to(self.device)\n self.Wco = nn.Parameter(torch.zeros(1, hidden, shape[0],shape[1])).to(self.device)\n\n return (nn.Parameter(torch.zeros(batch_size, hidden, shape[0],shape[1])).to(self.device),\n nn.Parameter(torch.zeros(batch_size, hidden, shape[0],shape[1])).to(self.device))\n\n\nclass ConvLSTM(nn.Module):\n # input_channels corresponds to the first input feature map\n # hidden state is a list of succeeding lstm layers.\n # kernel size is also a list, same length as hidden_channels\n def __init__(self, input_channels, hidden_channels, kernel_size, kernel_size_pool,kernel_stride_pool,step,device,num_devices,hidden_dim_lstm,num_layers_lstm,attention_flag=False):\n super(ConvLSTM, self).__init__()\n self.device= device\n self.num_devices=num_devices\n self.input_channels = [input_channels] + hidden_channels\n self.hidden_channels = hidden_channels\n self.kernel_size = kernel_size\n self.num_layers = len(hidden_channels)\n self.step = step\n self._all_layers = []\n self.num_labels=4\n self.hidden_dim_lstm = hidden_dim_lstm\n self.num_layers_lstm = num_layers_lstm\n self.kernel_size_pool=kernel_size_pool\n self.kernel_stride_pool=kernel_stride_pool\n strideF=1\n strideT=1\n for i in range(self.num_layers+1):\n if i<self.num_layers:\n name = 'cell{}'.format(i)\n cell = ConvLSTMCell(self.input_channels[i], self.hidden_channels[i], self.kernel_size[i],self.kernel_size_pool[i],self.kernel_stride_pool[i],self.device)\n setattr(self, name, cell)\n self._all_layers.append(cell)\n strideF*=self.kernel_stride_pool[i][0]\n strideT*=self.kernel_stride_pool[i][1]\n else:\n name=\"lstm\"\n cell=LSTM_Audio(self.hidden_dim_lstm,self.num_layers_lstm,device=self.device,bidirectional=True)\n setattr(self,name,cell)\n self._all_layers.append(cell)\n\n\n\n self.linear_dim=int(self.hidden_channels[-1]*(48/strideF)*(64/strideT))\n self.classification_convlstm = nn.Linear(self.linear_dim, self.num_labels)\n self.classification_lstm=nn.Linear(self.hidden_dim_lstm*2,self.num_labels)\n\n self.attention=nn.Parameter(torch.zeros(self.linear_dim))\n self.attention_flag=attention_flag\n\n self.weight= nn.Parameter(torch.tensor(-0.1).float(),requires_grad=True)\n\n\n\n def forward(self, input_lstm,input,target,seq_length, train=True):\n # input should be a list of inputs, like a time stamp, maybe 1280 for 100 times.\n ##data process here\n internal_state = []\n outputs = []\n for step in range(self.step):\n x=input[:,:,:,:,step]\n for i in range(self.num_layers):\n name = 'cell{}'.format(i)\n if step == 0:\n bsize, _, shapeF,shapeT = x.size()\n shape=(shapeF,shapeT)\n (h, c) = getattr(self, name).init_hidden(batch_size=bsize, hidden=self.hidden_channels[i],\n shape=shape)\n internal_state.append((h, c))\n\n # do forward\n (h, c) = internal_state[i]\n x, new_h, new_c = getattr(self, name)(x, h, c)\n internal_state[i] = (new_h, new_c)\n outputs.append(x)\n out=[torch.unsqueeze(o, dim=4) for o in outputs]\n out=torch.flatten(torch.cat(out,dim=4),start_dim=1,end_dim=3)\n\n input_lstm=input_lstm.to(self.device)\n seq_length=seq_length.to(self.device)\n out_lstm=getattr(self,\"lstm\")(input_lstm)\n out_lstm=out_lstm.permute(0,2,1)\n # out.shape batch*kf1f2*T\n\n if self.attention_flag:\n alpha=torch.unsqueeze(F.softmax(torch.matmul(self.attention,out),dim=1),dim=2)\n out=torch.squeeze(torch.bmm(out,alpha),dim=2)\n else:\n out=torch.mean(out,dim=2)\n temp=[torch.unsqueeze(torch.mean(out_lstm[k,:,:s],dim=1),dim=0) for k,s in enumerate(seq_length)]\n out_lstm=torch.cat(temp,dim=0)\n p=torch.exp(10*self.weight)/(1+torch.exp(10*self.weight))\n #out=torch.cat([p*out,(1-p)*out_lstm],dim=1)\n out=self.classification_convlstm(out)\n out_lstm=self.classification_lstm(out_lstm)\n out_final=p*out_lstm+(1-p)*out\n target_index = torch.argmax(target, dim=1).to(self.device)\n pred_index = torch.argmax(out_final, dim=1)\n correct_batch=torch.sum(target_index==pred_index)\n losses_batch=F.cross_entropy(out_final,torch.max(target,1)[1])\n\n correct_batch=torch.unsqueeze(correct_batch,dim=0)\n losses_batch=torch.unsqueeze(losses_batch, dim=0)\n\n if train:\n return losses_batch,correct_batch\n return losses_batch,correct_batch, (target_index, pred_index)\n"
] |
[
[
"torch.mean",
"torch.nn.Dropout",
"torch.max",
"torch.zeros",
"torch.cat",
"torch.nn.LSTM",
"torch.nn.Conv2d",
"torch.sum",
"torch.unsqueeze",
"torch.tensor",
"torch.tanh",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.exp",
"torch.matmul",
"torch.bmm",
"torch.nn.BatchNorm2d",
"torch.argmax"
]
] |
mwang87/NPAtlasGNPSproxy
|
[
"f3fa873cbf1d346f4cb8bd24739ee3c33d0e575f"
] |
[
"workflow/bin/convert_mibig.py"
] |
[
"import requests\nimport sys\nimport json\nimport pandas as pd\nimport glob\nimport requests_cache\nfrom tqdm import tqdm\nimport urllib.parse\nrequests_cache.install_cache('demo_cache')\n\n\ndef get_inchikey(smiles):\n url = \"https://gnps-structure.ucsd.edu/inchikey?smiles={}\".format(urllib.parse.quote(smiles))\n r = requests.get(url)\n return r.text\n\n\noutput_filename = sys.argv[1]\n\nall_json = glob.glob(\"**/*.json\", recursive=True)\n\noutput_list = []\nfor json_filename in tqdm(all_json):\n mibig_entry = json.loads(open(json_filename).read())\n #print(json.dumps(mibig_entry[\"cluster\"], indent=4))\n\n mibig_accession = mibig_entry[\"cluster\"].get(\"mibig_accession\", \"\")\n organism_name = mibig_entry[\"cluster\"].get(\"organism_name\", \"\")\n ncbi_tax_id = mibig_entry[\"cluster\"].get(\"ncbi_tax_id\", \"\")\n\n for compound in mibig_entry[\"cluster\"].get(\"compounds\", []):\n if not \"chem_struct\" in compound:\n continue\n\n smiles = compound[\"chem_struct\"]\n compound_name = compound[\"compound\"]\n molecular_formula = compound[\"molecular_formula\"]\n inchikey = get_inchikey(smiles)\n no_stereo_inchikey = inchikey.split(\"-\")[0]\n\n output_dict = {}\n output_dict[\"mibig_accession\"] = mibig_accession\n output_dict[\"organism_name\"] = organism_name\n output_dict[\"ncbi_tax_id\"] = ncbi_tax_id\n\n output_dict[\"smiles\"] = smiles\n output_dict[\"inchikey\"] = inchikey\n output_dict[\"no_stereo_inchikey\"] = no_stereo_inchikey\n output_dict[\"compound_name\"] = compound_name\n output_dict[\"molecular_formula\"] = molecular_formula\n\n\n output_list.append(output_dict)\n\npd.DataFrame(output_list).to_csv(output_filename, sep=\"\\t\", index=False)"
] |
[
[
"pandas.DataFrame"
]
] |
ahmed-shariff/lighttrack
|
[
"28ff1aea5273ead4013d0c733ca15328d7563245"
] |
[
"detector/detector_utils.py"
] |
[
"# Source: https://github.com/eriklindernoren/PyTorch-YOLOv3/blob/a68d786f6c9cb65d944c2f48eb7d219c914de11f/utils/utils.py\n\nfrom __future__ import division\nimport math\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\nimport cv2\n\ndef preprocess_img_for_yolo(img, img_size=416):\n input_img, _ = pad_to_square(img, 127.5)\n # Resize\n input_img = cv2.resize(\n input_img, (img_size, img_size), interpolation=cv2.INTER_AREA\n )\n # Channels-first\n input_img = np.transpose(input_img, (2, 0, 1))\n\n # extend one dimension\n input_img = np.expand_dims(input_img, axis=0)\n\n # As pytorch tensor\n input_img = torch.from_numpy(input_img).float() / 255.0\n return input_img\n\n\ndef pad_to_square(img, pad_value):\n h, w, _ = img.shape\n dim_diff = np.abs(h - w)\n # Upper (left) and lower (right) padding\n pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2\n # Determine padding\n pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0))\n # Add padding\n img = np.pad(img, pad, \"constant\", constant_values=pad_value)\n return img, pad\n\n\ndef load_classes(path):\n \"\"\"\n Loads class labels at 'path'\n \"\"\"\n fp = open(path, \"r\")\n names = fp.read().split(\"\\n\")[:-1]\n return names\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm2d\") != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n\n\ndef xywh2xyxy(x):\n y = x.new(x.shape)\n y[..., 0] = x[..., 0] - x[..., 2] / 2\n y[..., 1] = x[..., 1] - x[..., 3] / 2\n y[..., 2] = x[..., 0] + x[..., 2] / 2\n y[..., 3] = x[..., 1] + x[..., 3] / 2\n return y\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.\n # Arguments\n tp: True positives (list).\n conf: Objectness value from 0-1 (list).\n pred_cls: Predicted object classes (list).\n target_cls: True object classes (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n # Find unique classes\n unique_classes = np.unique(target_cls)\n\n # Create Precision-Recall curve and compute AP for each class\n ap, p, r = [], [], []\n for c in unique_classes:\n i = pred_cls == c\n n_gt = (target_cls == c).sum() # Number of ground truth objects\n n_p = i.sum() # Number of predicted objects\n\n if n_p == 0 and n_gt == 0:\n continue\n elif n_p == 0 or n_gt == 0:\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n # Accumulate FPs and TPs\n fpc = (1 - tp[i]).cumsum()\n tpc = (tp[i]).cumsum()\n\n # Recall\n recall_curve = tpc / (n_gt + 1e-16)\n r.append(recall_curve[-1])\n\n # Precision\n precision_curve = tpc / (tpc + fpc)\n p.append(precision_curve[-1])\n\n # AP from recall-precision curve\n ap.append(compute_ap(recall_curve, precision_curve))\n\n # Compute F1 score (harmonic mean of precision and recall)\n p, r, ap = np.array(p), np.array(r), np.array(ap)\n f1 = 2 * p * r / (p + r + 1e-16)\n\n return p, r, ap, f1, unique_classes.astype(\"int32\")\n\n\ndef compute_ap(recall, precision):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n\n # Arguments\n recall: The recall curve (list).\n precision: The precision curve (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.0], recall, [1.0]))\n mpre = np.concatenate(([0.0], precision, [0.0]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef get_batch_statistics(outputs, targets, iou_threshold):\n \"\"\" Compute true positives, predicted scores and predicted labels per sample \"\"\"\n batch_metrics = []\n for sample_i in range(len(outputs)):\n annotations = targets[sample_i][targets[sample_i][:, -1] > 0].detach().cpu().numpy()\n target_labels = annotations[:, 0] if len(annotations) else []\n\n if outputs[sample_i] is None:\n continue\n\n output = outputs[sample_i].detach().cpu().numpy()\n pred_boxes = output[:, :4]\n pred_scores = output[:, 4]\n pred_labels = output[:, -1]\n\n true_positives = np.zeros(pred_boxes.shape[0])\n if len(annotations):\n detected_boxes = []\n target_boxes = annotations[:, 1:]\n\n for pred_i, (pred_box, pred_label) in enumerate(zip(pred_boxes, pred_labels)):\n\n # If targets are found break\n if len(detected_boxes) == len(annotations):\n break\n\n # Ignore if label is not one of the target labels\n if pred_label not in target_labels:\n continue\n\n ious = bbox_iou_numpy(np.expand_dims(pred_box, 0), target_boxes)\n iou, box_index = ious.max(1), ious.argmax(1)\n if iou >= iou_threshold and box_index not in detected_boxes:\n true_positives[pred_i] = 1\n detected_boxes += [box_index]\n batch_metrics.append([true_positives, pred_scores, pred_labels])\n return batch_metrics\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n \"\"\"\n Returns the IoU of two bounding boxes\n \"\"\"\n if not x1y1x2y2:\n # Transform from center and width to exact coordinates\n b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n else:\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n\n # get the corrdinates of the intersection rectangle\n inter_rect_x1 = torch.max(b1_x1, b2_x1)\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n # Intersection area\n inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(\n inter_rect_y2 - inter_rect_y1 + 1, min=0\n )\n # Union Area\n b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n return iou\n\n\ndef bbox_iou_numpy(box1, box2):\n \"\"\"Computes IoU between bounding boxes.\n Parameters\n ----------\n box1 : ndarray\n (N, 4) shaped array with bboxes\n box2 : ndarray\n (M, 4) shaped array with bboxes\n Returns\n -------\n : ndarray\n (N, M) shaped array with IoUs\n \"\"\"\n area = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])\n\n iw = np.minimum(np.expand_dims(box1[:, 2], axis=1), box2[:, 2]) - np.maximum(\n np.expand_dims(box1[:, 0], 1), box2[:, 0]\n )\n ih = np.minimum(np.expand_dims(box1[:, 3], axis=1), box2[:, 3]) - np.maximum(\n np.expand_dims(box1[:, 1], 1), box2[:, 1]\n )\n iw = np.maximum(iw, 0)\n ih = np.maximum(ih, 0)\n ua = np.expand_dims((box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1]), axis=1) + area - iw * ih\n ua = np.maximum(ua, np.finfo(float).eps)\n intersection = iw * ih\n\n return intersection / ua\n\n\ndef non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4):\n \"\"\"\n Removes detections with lower object confidence score than 'conf_thres' and performs\n Non-Maximum Suppression to further filter detections.\n Returns detections with shape:\n (x1, y1, x2, y2, object_conf, class_score, class_pred)\n \"\"\"\n\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n prediction[..., :4] = xywh2xyxy(prediction[..., :4])\n output = [None for _ in range(len(prediction))]\n for image_i, image_pred in enumerate(prediction):\n # Filter out confidence scores below threshold\n image_pred = image_pred[image_pred[:, 4] >= conf_thres]\n # If none are remaining => process next image\n if not image_pred.size(0):\n continue\n # Object confidence times class confidence\n score = image_pred[:, 4] * image_pred[:, 5:].max(1)[0]\n # Sort by it\n image_pred = image_pred[(-score).argsort()]\n class_preds = image_pred[:, 5:].max(1, keepdim=True)[1].float()\n detections = torch.cat((image_pred[:, :5], class_preds), 1)\n # Perform non-maximum suppression\n keep_boxes = []\n while detections.size(0):\n large_overlap = bbox_iou(detections[0, :4].unsqueeze(0), detections[:, :4]) > nms_thres\n label_match = detections[0, -1] == detections[:, -1]\n # Indices of boxes with lower confidence scores, large IOUs and matching labels\n invalid = large_overlap & label_match\n weights = detections[invalid, 4:5]\n # Merge overlapping bboxes by order of confidence\n detections[0, :4] = (weights * detections[invalid, :4]).sum(0) / weights.sum()\n keep_boxes += [detections[0]]\n detections = detections[~invalid]\n if keep_boxes:\n output[image_i] = torch.stack(keep_boxes)\n\n return output\n\n\ndef build_targets(\n pred_boxes, pred_conf, pred_cls, target, anchors, num_anchors, num_classes, grid_size, ignore_thres, img_dim\n):\n nB = target.size(0)\n nA = num_anchors\n nC = num_classes\n nG = grid_size\n obj_mask = torch.zeros(nB, nA, nG, nG)\n noobj_mask = torch.ones(nB, nA, nG, nG)\n tx = torch.zeros(nB, nA, nG, nG)\n ty = torch.zeros(nB, nA, nG, nG)\n tw = torch.zeros(nB, nA, nG, nG)\n th = torch.zeros(nB, nA, nG, nG)\n tconf = torch.ByteTensor(nB, nA, nG, nG).fill_(0)\n tcls = torch.ByteTensor(nB, nA, nG, nG, nC).fill_(0)\n\n num_targets = 0\n num_correct = 0\n for b in range(nB):\n for t in range(target.shape[1]):\n if target[b, t].sum() == 0:\n continue\n num_targets += 1\n # Convert to position relative to box\n gx = target[b, t, 1] * nG\n gy = target[b, t, 2] * nG\n gw = target[b, t, 3] * nG\n gh = target[b, t, 4] * nG\n # Get grid box indices\n gi = int(gx)\n gj = int(gy)\n # Get shape of gt box\n gt_box = torch.FloatTensor(np.array([0, 0, gw, gh])).unsqueeze(0)\n # Get shape of anchor box\n anchor_shapes = torch.FloatTensor(np.zeros((len(anchors), 4)))\n anchor_shapes[:, 2:] = torch.FloatTensor(anchors)\n # Calculate iou between gt and anchor shapes\n anch_ious = bbox_iou(gt_box, anchor_shapes)\n # Where the overlap is larger than threshold set mask to zero (ignore)\n noobj_mask[b, anch_ious > ignore_thres, gj, gi] = 0\n # Find the best matching anchor box\n best_n = np.argmax(anch_ious)\n # Get ground truth box\n gt_box = torch.FloatTensor(np.array([gx, gy, gw, gh])).unsqueeze(0)\n # Get the prediction at best matching anchor box\n pred_box = pred_boxes[b, best_n, gj, gi].unsqueeze(0)\n # Masks\n obj_mask[b, best_n, gj, gi] = 1\n noobj_mask[b, best_n, gj, gi] = 0\n # Coordinates\n tx[b, best_n, gj, gi] = gx - gi\n ty[b, best_n, gj, gi] = gy - gj\n # Width and height\n tw[b, best_n, gj, gi] = math.log(gw / anchors[best_n][0] + 1e-16)\n th[b, best_n, gj, gi] = math.log(gh / anchors[best_n][1] + 1e-16)\n # One-hot encoding of label\n target_label = int(target[b, t, 0])\n tcls[b, best_n, gj, gi, target_label] = 1\n tconf[b, best_n, gj, gi] = 1\n # Calculate iou between ground truth and best matching prediction\n iou = bbox_iou(gt_box, pred_box, x1y1x2y2=False)\n pred_label = torch.argmax(pred_cls[b, best_n, gj, gi])\n score = pred_conf[b, best_n, gj, gi]\n if iou > 0.5 and pred_label == target_label and score > 0.5:\n num_correct += 1\n\n return num_targets, num_correct, obj_mask, noobj_mask, tx, ty, tw, th, tconf, tcls\n\n\ndef to_categorical(y, num_classes):\n \"\"\" 1-hot encodes a tensor \"\"\"\n return torch.from_numpy(np.eye(num_classes, dtype=\"uint8\")[y])\n"
] |
[
[
"numpy.expand_dims",
"torch.max",
"torch.zeros",
"torch.cat",
"numpy.concatenate",
"torch.FloatTensor",
"numpy.where",
"torch.ones",
"numpy.pad",
"numpy.unique",
"numpy.eye",
"torch.from_numpy",
"numpy.finfo",
"numpy.argmax",
"numpy.zeros",
"torch.nn.init.constant_",
"torch.min",
"torch.nn.init.normal_",
"numpy.transpose",
"torch.stack",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"torch.ByteTensor",
"numpy.maximum",
"numpy.abs",
"torch.clamp",
"torch.argmax"
]
] |
PrashantDandriyal/tensorflow
|
[
"cc6d91a334802a0a4a1c66e539c2b08602fa588b"
] |
[
"tensorflow/lite/tools/pip_package/setup.py"
] |
[
"# Copyright 2018 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\"\"\"TensorFlow Lite is for mobile and embedded devices.\n\nTensorFlow Lite is the official solution for running machine learning models on\nmobile and embedded devices. It enables on-device machine learning inference\nwith low latency and a small binary size on Android, iOS, and other operating\nsystems.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport multiprocessing\nimport os\nimport subprocess\nimport sys\n\nfrom distutils.command.build_ext import build_ext\nimport numpy\n\nfrom setuptools import Extension\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.command.build_py import build_py\nPACKAGE_NAME = 'tflite_runtime'\nPACKAGE_VERSION = os.environ['PACKAGE_VERSION']\nDOCLINES = __doc__.split('\\n')\nTENSORFLOW_DIR = os.environ['TENSORFLOW_DIR']\nRELATIVE_MAKE_DIR = os.path.join('tensorflow', 'lite', 'tools', 'make')\nMAKE_DIR = os.path.join(TENSORFLOW_DIR, RELATIVE_MAKE_DIR)\nDOWNLOADS_DIR = os.path.join(MAKE_DIR, 'downloads')\nRELATIVE_MAKEFILE_PATH = os.path.join(RELATIVE_MAKE_DIR, 'Makefile')\nDOWNLOAD_SCRIPT_PATH = os.path.join(MAKE_DIR, 'download_dependencies.sh')\n\n# Setup cross compiling\nTARGET = os.environ.get('TENSORFLOW_TARGET')\nif TARGET == 'rpi':\n os.environ['CXX'] = 'arm-linux-gnueabihf-g++'\n os.environ['CC'] = 'arm-linux-gnueabihf-gcc'\nelif TARGET == 'aarch64':\n os.environ['CXX'] = 'aarch64-linux-gnu-g++'\n os.environ['CC'] = 'aarch64-linux-gnu-gcc'\n\nMAKE_CROSS_OPTIONS = []\nfor name in ['TARGET', 'TARGET_ARCH', 'CC_PREFIX', 'EXTRA_CXXFLAGS']:\n value = os.environ.get('TENSORFLOW_%s' % name)\n if value:\n MAKE_CROSS_OPTIONS.append('%s=%s' % (name, value))\n\n\n# Check physical memory and if we are on a reasonable non small SOC machine\n# with more than 4GB, use all the CPUs, otherwise only 1.\ndef get_build_cpus():\n physical_bytes = os.sysconf('SC_PAGESIZE') * os.sysconf('SC_PHYS_PAGES')\n if physical_bytes < (1 << 30) * 4:\n return 1\n else:\n return multiprocessing.cpu_count()\n\n\ndef make_args(target='', quiet=True):\n \"\"\"Construct make command line.\"\"\"\n args = ([\n 'make', 'SHELL=/bin/bash', 'BUILD_WITH_NNAPI=false', '-C', TENSORFLOW_DIR\n ] + MAKE_CROSS_OPTIONS +\n ['-f', RELATIVE_MAKEFILE_PATH, '-j',\n str(get_build_cpus())])\n if quiet:\n args.append('--quiet')\n if target:\n args.append(target)\n return args\n\n\ndef make_output(target):\n \"\"\"Invoke make on the target and return output.\"\"\"\n return subprocess.check_output(make_args(target)).decode('utf-8').strip()\n\n\ndef make():\n \"\"\"Invoke make to build tflite C++ sources.\n\n Build dependencies:\n apt-get install swig libjpeg-dev zlib1g-dev python3-dev python3-nump\n \"\"\"\n subprocess.check_call(make_args(quiet=False))\n\n\ndef download_dependencies():\n \"\"\"Download build dependencies if haven't done yet.\"\"\"\n if not os.path.isdir(DOWNLOADS_DIR) or not os.listdir(DOWNLOADS_DIR):\n subprocess.check_call(DOWNLOAD_SCRIPT_PATH)\n\n\nclass CustomBuildExt(build_ext, object):\n \"\"\"Customized build extension.\"\"\"\n\n def get_ext_filename(self, ext_name):\n if TARGET:\n ext_path = ext_name.split('.')\n return os.path.join(*ext_path) + '.so'\n return super(CustomBuildExt, self).get_ext_filename(ext_name)\n\n def run(self):\n download_dependencies()\n make()\n\n return super(CustomBuildExt, self).run()\n\n\nclass CustomBuildPy(build_py, object):\n\n def run(self):\n self.run_command('build_ext')\n return super(CustomBuildPy, self).run()\n\n\ndef get_pybind_include():\n \"\"\"pybind11 include directory is not correctly resolved.\n\n This fixes include directory to /usr/local/pythonX.X\n\n Returns:\n include directories to find pybind11\n \"\"\"\n if sys.version_info[0] == 3:\n include_dirs = glob.glob('/usr/local/include/python3*')\n else:\n include_dirs = glob.glob('/usr/local/include/python2*')\n tmp_include_dirs = []\n pip_dir = os.path.join(TENSORFLOW_DIR, 'tensorflow', 'lite', 'tools',\n 'pip_package', 'gen')\n for include_dir in include_dirs:\n tmp_include_dir = os.path.join(pip_dir, include_dir[1:])\n tmp_include_dirs.append(tmp_include_dir)\n try:\n os.makedirs(tmp_include_dir)\n os.symlink(include_dir, os.path.join(tmp_include_dir, 'include'))\n except IOError: # file already exists.\n pass\n return tmp_include_dirs\n\n\nLIB_TFLITE = 'tensorflow-lite'\nLIB_TFLITE_DIR = make_output('libdir')\n\next = Extension(\n name='%s._interpreter_wrapper' % PACKAGE_NAME,\n language='c++',\n sources=[\n 'interpreter_wrapper/interpreter_wrapper.cc',\n 'interpreter_wrapper/interpreter_wrapper_pybind11.cc',\n 'interpreter_wrapper/numpy.cc',\n 'interpreter_wrapper/python_error_reporter.cc',\n 'interpreter_wrapper/python_utils.cc'\n ],\n extra_compile_args=['--std=c++11'],\n include_dirs=[\n TENSORFLOW_DIR,\n os.path.join(TENSORFLOW_DIR, 'tensorflow', 'lite', 'tools',\n 'pip_package'),\n numpy.get_include(),\n os.path.join(DOWNLOADS_DIR, 'flatbuffers', 'include'),\n os.path.join(DOWNLOADS_DIR, 'absl')\n ] + get_pybind_include(),\n libraries=[LIB_TFLITE],\n library_dirs=[LIB_TFLITE_DIR])\n\nsetup(\n name=PACKAGE_NAME.replace('_', '-'),\n version=PACKAGE_VERSION,\n description=DOCLINES[0],\n long_description='\\n'.join(DOCLINES[2:]),\n url='https://www.tensorflow.org/lite/',\n author='Google, LLC',\n author_email='packages@tensorflow.org',\n license='Apache 2.0',\n include_package_data=True,\n keywords='tflite tensorflow tensor machine learning',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Mathematics',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Software Development',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n packages=find_packages(exclude=[]),\n ext_modules=[ext],\n install_requires=[\n 'numpy >= 1.16.0',\n 'pybind11 >= 2.4.3',\n ],\n cmdclass={\n 'build_ext': CustomBuildExt,\n 'build_py': CustomBuildPy,\n })\n"
] |
[
[
"numpy.get_include"
]
] |
s-vidal/style_transfer
|
[
"a7f02b1ee0a69c49ff59f8b36e8d6c4500cc665a"
] |
[
".history/server_2/algo_20200930102133.py"
] |
[
"import matplotlib.pylab as plt\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\n\ndef style_transfer(content_image_path, style_image_path):\n try:\n content_image_path = \"images/rnd_imgs/trump.jpg\"\n style_image_path = \"images/style_imgs/wave.jpg\"\n\n content_image = plt.imread(content_image_path)\n style_image = plt.imread(style_image_path)\n content_image = content_image.astype(np.float32)[np.newaxis, ...] / 255.\n style_image = style_image.astype(np.float32)[np.newaxis, ...] / 255.\n # Optionally resize the images. It is recommended that the style image is about\n # 256 pixels (this size was used when training the style transfer network).\n # The content image can be any size.\n style_image = tf.image.resize(style_image, (256, 256))\n\n hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')\n # hub_module = hub.load(\"./hub_module\")\n outputs = hub_module(tf.constant(content_image), tf.constant(style_image))\n stylized_image = outputs[0]\n save_tensor_as_image(stylized_image)\n return True\n except Exception as e:\n raise e\n\n\ndef save_tensor_as_image(stylized_image):\n try:\n numpy_array = (stylized_image.numpy())\n shape = numpy_array.shape\n list_shape = list(shape)\n list_shape.pop(0)\n img = numpy_array.reshape(tuple(list_shape))\n plt.imshow(img, interpolation='nearest')\n plt.axis('off')\n print(\"start saving file\")\n plt.savefig('stylized_imgs/test_3.png', transparent=True, pad_inches=0)\n print(\"finished saving file\")\n except Exception as e:\n raise e\n"
] |
[
[
"tensorflow.constant",
"matplotlib.pylab.axis",
"matplotlib.pylab.imread",
"tensorflow.image.resize",
"matplotlib.pylab.imshow",
"matplotlib.pylab.savefig"
]
] |
sgs-weather-and-environmental-systems/rstt
|
[
"bd7855001e65f4802f4a2556fc5d7d2fa1f85619"
] |
[
"gr-rstt/python/nle_integral.py"
] |
[
"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n\nclass Src:\n def __init__(self, fname, block_size, navg = 1):\n self.offs = 0\n self.navg = navg\n self.block_size = block_size\n self.data = np.fromfile(fname, dtype=np.float32)\n l = divmod(len(self.data), block_size)[0]\n self.data = self.data[0:l*block_size]\n self.data = self.data.reshape(l, block_size)\n\n def read(self):\n navg = self.navg\n # do frame averaging\"\n data = np.zeros(self.block_size)\n while navg > 0 and self.offs < len(self.data):\n data += self.data[self.offs]\n self.offs += 1\n navg -= 1\n if navg:\n return None\n return data / self.navg\n\n\nclass Extreme:\n def __init__(self, data, mean_rel):\n \"\"\"Data should be integral of signal power value,\n mean_rel should be relative mean value, see Split.set_mean for details.\"\"\"\n idx = self.idx = 0\n self.val = 0\n while idx < len(data):\n val = data[idx] - data[0] - mean_rel * idx\n if val > self.val:\n self.val = val\n self.idx = idx\n# why \"+ 1\", because this point is last one with value above mean_rel on the\n# descenting side of peak, so we need firt point which does not belogn to peak\n elif -val > self.val:\n self.val = -val\n self.idx = idx\n idx += 1\n\n\n\nclass Split:\n def __init__(self, start, _len):\n self.start = start\n self.len = _len\n\n def __str__(self):\n return \"start = %f; len = %f; mean_rel = %f;\" % (self.start, self.len, self.mean_rel, )\n\n def get_mean(self, data):\n return (self.mean_rel * (self.len - 1) + data[self.start]) / self.len\n\n def set_mean(self, data):\n \"\"\"Set relative mean value for data in range defined by Split.\n Data should be integrated power value of signal.\"\"\"\n if self.len > 1:\n l = self.len - 1\n self.mean_rel = (data[self.start + l] - data[self.start]) / l\n else:\n self.mean_rel = 0.\n\n def set_extreme(self, data):\n \"\"\"Find new extreme.\"\"\"\n self.extreme = Extreme(self.data(data), self.mean_rel)\n\n def data(self, data):\n return data[self.start:self.start+self.len]\n\n\nclass Show:\n \"\"\"Noise level estimation. Input is vector of FFT(1024) series.\"\"\"\n\n def __init__(self, src):\n self.src = src\n\n def run(self, noise_pct = 0.2, nsplits = 60, threshold = 2):\n d = self.src.read()\n while len(d):\n # plot: original signal\n offs = int(len(d) / 2)\n x = range(0 - offs, len(d) - offs)\n plt.plot(x, d)\n\n # plot: log(original signal)\n d_log = [np.log(d_) for d_ in d]\n min_ = max(d_log)\n for d_ in d_log:\n if d_ < min_ and np.isfinite(d_):\n min_ = d_\n d_log = [d_ if np.isfinite(d_) else min_ for d_ in d_log ]\n #plt.plot(x, d_log)\n\n self.write_signal('out', d_log)\n\n # get splits\n d_ilog = [d_log[0], ]\n for idx in range(1, len(d_log)):\n d_ilog.append(d_ilog[idx - 1] + d_log[idx])\n split = Split(0, len(d_log))\n splits = [split, ]\n split.set_mean(d_ilog)\n split.set_extreme(d_ilog)\n for sn in range(0, nsplits):\n smax = max(splits, key=lambda s: s.extreme.val)\n snew = Split(smax.start + smax.extreme.idx + 1, smax.len - smax.extreme.idx - 1)\n splits.append(snew)\n snew.set_mean(d_ilog)\n snew.set_extreme(d_ilog)\n smax.len = smax.extreme.idx + 1\n smax.set_mean(d_ilog)\n smax.set_extreme(d_ilog)\n\n # get mean and sigma for noise\n splits.sort(key=lambda v: v.get_mean(d_log))\n l = 0\n mean = 0\n sigma = 0\n for split in splits:\n #print(split)\n for v in split.data(d_log):\n mean += v\n sigma += v**2\n l += split.len\n if l > len(d) * noise_pct:\n break\n mean /= l\n sigma = np.sqrt(sigma/l - mean**2) * threshold\n\n print(\"%.4f %.4f %.4f\" % (mean - sigma, mean, mean + sigma, ))\n n_lo, mean, n_hi = np.exp(mean - sigma), np.exp(mean), np.exp(mean + sigma)\n plt.plot(x, [n_lo for a in x])\n plt.plot(x, [mean for a in x])\n plt.plot(x, [n_hi for a in x])\n\n plt.show()\n plt.close()\n\n\n def write_signal(self, fname, data):\n with open('out', 'w') as f:\n i = 0\n while i < len(data):\n f.write(\"%.4f, \" % data[i])\n i += 1\n if i % 8 == 0 and i != 0:\n f.write(\"\\n\")\n\n\nif __name__ == '__main__':\n s = Show(Src(sys.argv[1], 1024, 100))\n s.run()\n"
] |
[
[
"numpy.log",
"numpy.fromfile",
"numpy.sqrt",
"numpy.isfinite",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
andy920262/pytorch-a2c-ppo-acktr
|
[
"2e7e85219dfe737cb4036de3cf0c8b00706d640e"
] |
[
"storage.py"
] |
[
"import torch\nfrom torch.utils.data.sampler import BatchSampler, SubsetRandomSampler\n\n\nclass RolloutStorage(object):\n def __init__(self, num_steps, num_processes, obs_shape, action_space, state_size):\n self.observations = torch.zeros(num_steps + 1, num_processes, *obs_shape)\n self.states = torch.zeros(num_steps + 1, num_processes, state_size)\n self.rewards = torch.zeros(num_steps, num_processes, 1)\n self.value_preds = torch.zeros(num_steps + 1, num_processes, 1)\n self.returns = torch.zeros(num_steps + 1, num_processes, 1)\n self.action_log_probs = torch.zeros(num_steps, num_processes, 1)\n if action_space.__class__.__name__ == 'Discrete':\n action_shape = 1\n else:\n action_shape = action_space.shape[0]\n self.actions = torch.zeros(num_steps, num_processes, action_shape)\n if action_space.__class__.__name__ == 'Discrete':\n self.actions = self.actions.long()\n self.masks = torch.ones(num_steps + 1, num_processes, 1)\n\n self.num_steps = num_steps\n self.step = 0\n\n def cuda(self):\n self.observations = self.observations.cuda()\n self.states = self.states.cuda()\n self.rewards = self.rewards.cuda()\n self.value_preds = self.value_preds.cuda()\n self.returns = self.returns.cuda()\n self.action_log_probs = self.action_log_probs.cuda()\n self.actions = self.actions.cuda()\n self.masks = self.masks.cuda()\n\n def insert(self, current_obs, state, action, action_log_prob, value_pred, reward, mask):\n self.observations[self.step + 1].copy_(current_obs)\n self.states[self.step + 1].copy_(state)\n self.actions[self.step].copy_(action)\n self.action_log_probs[self.step].copy_(action_log_prob)\n self.value_preds[self.step].copy_(value_pred)\n self.rewards[self.step].copy_(reward)\n self.masks[self.step + 1].copy_(mask)\n \n self.step = (self.step + 1) % self.num_steps\n\n def after_update(self):\n self.observations[0].copy_(self.observations[-1])\n self.states[0].copy_(self.states[-1])\n self.masks[0].copy_(self.masks[-1])\n\n def compute_returns(self, next_value, use_gae, gamma, tau):\n if use_gae:\n self.value_preds[-1] = next_value\n gae = 0\n for step in reversed(range(self.rewards.size(0))):\n delta = self.rewards[step] + gamma * self.value_preds[step + 1] * self.masks[step + 1] - self.value_preds[step]\n gae = delta + gamma * tau * self.masks[step + 1] * gae\n self.returns[step] = gae + self.value_preds[step]\n else:\n self.returns[-1] = next_value\n for step in reversed(range(self.rewards.size(0))):\n self.returns[step] = self.returns[step + 1] * \\\n gamma * self.masks[step + 1] + self.rewards[step]\n\n\n def feed_forward_generator(self, advantages, num_mini_batch):\n num_steps, num_processes = self.rewards.size()[0:2]\n batch_size = num_processes * num_steps\n mini_batch_size = batch_size // num_mini_batch\n sampler = BatchSampler(SubsetRandomSampler(range(batch_size)), mini_batch_size, drop_last=False)\n for indices in sampler:\n indices = torch.LongTensor(indices)\n\n if advantages.is_cuda:\n indices = indices.cuda()\n\n observations_batch = self.observations[:-1].view(-1,\n *self.observations.size()[2:])[indices]\n states_batch = self.states[:-1].view(-1, self.states.size(-1))[indices]\n actions_batch = self.actions.view(-1, self.actions.size(-1))[indices]\n return_batch = self.returns[:-1].view(-1, 1)[indices]\n masks_batch = self.masks[:-1].view(-1, 1)[indices]\n old_action_log_probs_batch = self.action_log_probs.view(-1, 1)[indices]\n adv_targ = advantages.view(-1, 1)[indices]\n\n yield observations_batch, states_batch, actions_batch, \\\n return_batch, masks_batch, old_action_log_probs_batch, adv_targ\n\n def recurrent_generator(self, advantages, num_mini_batch):\n num_processes = self.rewards.size(1)\n num_envs_per_batch = num_processes // num_mini_batch\n perm = torch.randperm(num_processes)\n for start_ind in range(0, num_processes, num_envs_per_batch):\n observations_batch = []\n states_batch = []\n actions_batch = []\n return_batch = []\n masks_batch = []\n old_action_log_probs_batch = []\n adv_targ = []\n\n for offset in range(num_envs_per_batch):\n ind = perm[start_ind + offset]\n observations_batch.append(self.observations[:-1, ind])\n states_batch.append(self.states[0:1, ind])\n actions_batch.append(self.actions[:, ind])\n return_batch.append(self.returns[:-1, ind])\n masks_batch.append(self.masks[:-1, ind])\n old_action_log_probs_batch.append(self.action_log_probs[:, ind])\n adv_targ.append(advantages[:, ind])\n\n observations_batch = torch.cat(observations_batch, 0)\n states_batch = torch.cat(states_batch, 0)\n actions_batch = torch.cat(actions_batch, 0)\n return_batch = torch.cat(return_batch, 0)\n masks_batch = torch.cat(masks_batch, 0)\n old_action_log_probs_batch = torch.cat(old_action_log_probs_batch, 0)\n adv_targ = torch.cat(adv_targ, 0)\n\n yield observations_batch, states_batch, actions_batch, \\\n return_batch, masks_batch, old_action_log_probs_batch, adv_targ\n"
] |
[
[
"torch.LongTensor",
"torch.ones",
"torch.cat",
"torch.randperm",
"torch.zeros"
]
] |
andrijaster/GCRF-GCRFC
|
[
"1a308bd563838719cb6afe826d1852e00aafb514"
] |
[
"src/preprocess/Distr_gener.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 24 10:42:49 2018\n\n@author: Andrija Master\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom scipy.io import arff\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n\ndf = pd.read_csv(\"df_slobodno.csv\", header = 0, index_col = 0)\n\natribute = df.iloc[:,:-36]\noutput = df.iloc[:,-36:]\n\nbrzina_NIS = output.loc[:,\"('brlabels', '0')\"]\nbrzina_NIS.index = pd.to_datetime(brzina_NIS.index,dayfirst=True)\n#brzina_NIS = brzina_NIS[brzina_NIS!=0]\nfigure = plt.figure(figsize=(13, 6))\nax1 = plt.subplot(211)\nax1.hist(brzina_NIS, bins = 15)\nax1.grid()\nax1.set_xlabel('Prosečna brzina [m/s]')\n#ax1.set_xlim(brzina_NIS.index[0],brzina_NIS.index[-1])\n#ax1.set_ylim(50,150)\n#ax1.set_ylabel('$\\mathbf{\\lambda}$ [1/min]')\nax2 = plt.subplot(212)\nsb.kdeplot(brzina_NIS)\nax2.grid()\nax2.set_xlabel('Prosečna brzina [m/s]')\nax2.get_legend().remove()\n\nbrzina_mod = 125.1\nkilometraza = pd.read_csv('kilometraza_nis.csv',sep=';')\nbg_vreme = kilometraza.iloc[:,0] / brzina_mod\nY_test = np.load('Y_test_reg.npy')\nY_test = Y_test[:,0]\nno_test = np.where(Y_test>0)\nY_test = Y_test[no_test]\nY_GCRF = np.load('Y_GCRF.npy')\nY_GCRF = Y_GCRF[:,0]\nY_GCRF = Y_GCRF[no_test]\nvreme_test_nis = np.zeros([Y_GCRF.shape[0],bg_vreme.shape[0]])\nvreme_razlika = np.zeros([Y_GCRF.shape[0],bg_vreme.shape[0]])\nvreme_GCRF_nis = np.zeros([Y_GCRF.shape[0],bg_vreme.shape[0]])\nvreme_GCRF_razlika = np.zeros([Y_GCRF.shape[0],bg_vreme.shape[0]])\nroot_mean_squared = np.zeros([kilometraza.shape[0]])\n\nfor i in range(kilometraza.shape[0]):\n vreme_test_nis[:,i] = kilometraza.iloc[i,0]/ Y_test\n vreme_razlika[:,i] = (vreme_test_nis[:,i] - bg_vreme[i])\n vreme_GCRF_nis[:,i] = kilometraza.iloc[i,0]/ Y_GCRF\n vreme_GCRF_razlika[:,i] = (vreme_GCRF_nis[:,i] - bg_vreme[i])\n root_mean_squared[i] = np.sqrt(mean_squared_error(vreme_razlika[:,i], vreme_GCRF_razlika[:,i]))\n\nvreme_test_nis = vreme_test_nis*60\nvreme_GCRF_nis = vreme_GCRF_nis*60\nvreme_razlika = vreme_razlika*60\nvreme_GCRF_razlika = vreme_GCRF_razlika*60\nroot_mean_squared = root_mean_squared*60"
] |
[
[
"pandas.read_csv",
"pandas.to_datetime",
"sklearn.metrics.mean_squared_error",
"matplotlib.pyplot.subplot",
"numpy.load",
"numpy.where",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
cmaureir/TurnipBot5000
|
[
"6f65ea2618d194c8c7e410cec3810ceeab670505"
] |
[
"lib/spreadsheet.py"
] |
[
"import re\nimport pandas as pd\nimport numpy as np\nimport gspread\nfrom google.oauth2.service_account import Credentials\n\ndef get_data(credentials):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = Credentials.from_service_account_file(credentials, scopes=scope)\n gc = gspread.authorize(credentials)\n\n # This uses the filename on Google Drive,\n # and by default we use the 'sheet1', if any of those\n # things changes names, we need to update this\n wks = gc.open(\"Turnip price tracker\").sheet1\n\n l = wks.get_all_values()\n column_names = [\"day\"] + [re.sub(\"\\ week\\ \\d+\", \"\", i) for i in l[0][1:]]\n df = pd.DataFrame.from_records(l, columns=column_names)[:-2]\n\n # Removing the lines without a day\n df = df[df.day != \"\"]\n\n # Selecting only the rows where at least one person added a price\n df = df[(df[list(df.columns)[1:]] != \"\").any(axis=1)]\n\n return df\n\ndef format_message(d):\n # Get day cell content, and removing it for the sorting\n day = list(d[\"day\"].values())[0]\n del d[\"day\"]\n\n # Adding NaN for empty values\n d_parsed = {}\n for k, v in d.items():\n try:\n d_parsed[k] = int(list(v.values())[0])\n except ValueError:\n d_parsed[k] = np.nan\n\n # Order prices\n d_sorted = {k: v for k, v in sorted(d_parsed.items(),\n key=lambda i: -1 if i[1] is np.nan else i[1], reverse=True)}\n\n # Format in Markdown\n s = \"```\\n\"\n s += f\"Day: {day}\\n\"\n for key, value in d_sorted.items():\n if value is np.nan:\n s += f\"{key:12} ?\\n\"\n else:\n s += f\"{key:12} {value:4}\\n\"\n s += \"```\\n\"\n return s\n\n\ndef get_last(credentials):\n df = get_data(credentials)\n d = df.tail(1).to_dict()\n return format_message(d)\n\ndef get_prev(credentials):\n df = get_data(credentials)\n d = df.tail(2).head(1).to_dict()\n return format_message(d)\n\ndef get_fossils(credentials):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = Credentials.from_service_account_file(credentials, scopes=scope)\n gc = gspread.authorize(credentials)\n\n wks = gc.open(\"Turnip price tracker\").worksheet(\"Fossils\")\n\n l = wks.get_all_values()\n column_names = [\"name1\", \"name2\"] + [re.sub(\"\\ week\\ \\d+\", \"\", i).lower().replace(\"á\", \"a\") for i in l[0][2:]]\n df = pd.DataFrame.from_records(l, columns=column_names)[1:-2]\n\n empty_columns = [i for i, name in enumerate(df.columns) if name == \"\"]\n\n df = df.drop(df.columns[empty_columns], axis=1)\n df[\"name\"] = df[\"name1\"] + \" \" + df[\"name2\"]\n df[\"name\"] = df[\"name\"].str.strip()\n df = df.drop([\"name1\", \"name2\"], axis=1)\n\n d_missing = {i: None for i in df.columns if i != \"name\"}\n d_repeated = {i: None for i in df.columns if i != \"name\"}\n for key, value in d_missing.items():\n d_missing[key] = list(df[\"name\"][~df[key].str.lower().str.contains(\"x\")])\n d_repeated[key] = list(df[\"name\"][df[key].str.lower().str.contains(\"e\")])\n d_missing[key] = [i for i in d_missing[key] if i not in d_repeated[key]]\n\n return d_missing, d_repeated, [i for i in df.columns if i != \"name\"]\n\n\ndef get_songs(credentials):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = Credentials.from_service_account_file(credentials, scopes=scope)\n gc = gspread.authorize(credentials)\n\n wks = gc.open(\"Turnip price tracker\").worksheet(\"Songs\")\n\n l = wks.get_all_values()\n\n column_names = [\"song\"] + [re.sub(\"\\ week\\ \\d+\", \"\", i).lower().replace(\"á\", \"a\") for i in l[0][1:]]\n df = pd.DataFrame.from_records(l, columns=column_names).iloc[1:96, 0:11]\n\n d_missing = {i: None for i in df.columns if i != \"song\"}\n d_repeated = {i: None for i in df.columns if i != \"song\"}\n\n print([i for i in df.columns if i != \"song\"])\n\n for key, value in d_missing.items():\n d_missing[key] = list(df[\"song\"][df[key] == \"\"])\n d_repeated[key] = list(df[\"song\"][df[key] != \"\"])\n\n return d_missing, d_repeated, [i for i in df.columns if i != \"song\"]\n"
] |
[
[
"pandas.DataFrame.from_records"
]
] |
liziyun/SparseConvNet
|
[
"0053b2a4eef3d0b9d4b79ede3ede664c2f0a3910"
] |
[
"examples/cifar10/data.py"
] |
[
"\n# Copyright 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch\nimport torchnet\nimport torchvision\nimport torchvision.transforms as transforms\nimport sparseconvnet as scn\nimport pickle\nimport math\nimport random\nimport numpy as np\nimport os\n\n#if not os.path.exists('pickle/'):\n# #print('Downloading and preprocessing data ...')\n# #os.system(\n# # 'wget http://www.nlpr.ia.ac.cn/databases/download/feature_data/OLHWDB1.1trn_pot.zip')\n# #os.system(\n# # 'wget http://www.nlpr.ia.ac.cn/databases/download/feature_data/OLHWDB1.1tst_pot.zip')\n# os.system('mkdir -p POT/ pickle/')\n# os.system('unzip OLHWDB1.1trn_pot.zip -d POT/')\n# os.system('unzip OLHWDB1.1tst_pot.zip -d POT/')\n# os.system('python readPotFiles.py')\n\n#def interp(sample,x,y):\n# return torch.from_numpy(np.hstack([np.interp(sample.numpy(),x.numpy(),y[:,i].numpy())[:,None] for i in range(y.shape[1])])).float()\n\n#class Data(torch.utils.data.Dataset):\n# def __init__(self,file,scale=63):\n# print('Loading', file, 'and balancing points for scale', scale)\n# torch.utils.data.Dataset.__init__(self)\n# self.data = pickle.load(open(file, 'rb'))\n# for j in range(len(self.data)):\n# strokes=[]\n# features=[]\n# for k,stroke in enumerate(self.data[j]['input']):\n# #print(\"original\\n\")\n# #print(stroke.shape)\n# #print(stroke)\n# if len(stroke)>1:\n# stroke=stroke.float()/255-0.5\n# stroke*=scale-1e-3\n# #print(\"scaled\\n\")\n# #print(stroke)\n# delta=stroke[1:]-stroke[:-1]\n# #print(\"delta\\n\")\n# #print(delta)\n# mag=(delta**2).sum(1)**0.5\n# #print(\"mag\\n\")\n# #print(mag)\n# l=mag.cumsum(0)\n# #print(\"l\\n\")\n# #print(l)\n# zl=torch.cat([torch.zeros(1),l])\n# #print(\"zl\\n\")\n# #print(zl)\n# #print(\"arange\\n\")\n# #print(torch.arange(0,zl[-1]))\n# strokes.append(interp(torch.arange(0,zl[-1]),zl,stroke))\n# #print(\"strokes new\\n\")\n# #print(strokes)\n# delta/=mag[:,None]\n# delta=torch.Tensor(delta[[i//2 for i in range(2*len(l))]])\n# zl_=zl[[i//2 for i in range(1,2*len(l)+1)]]\n# features.append(interp(torch.arange(0,zl[-1]),zl_,delta))\n# #print(\"coords\\n\")\n# #print(strokes)\n# #print(\"features\\n\")\n# #print(features)\n# self.data[j]['coords'] = torch.cat(strokes,0)\n# self.data[j]['features'] = torch.cat(features,0)\n# for i, x in enumerate(self.data):\n# x['idx'] = i\n# print('Loaded', len(self.data), 'points')\n# def __getitem__(self,n):\n# return self.data[n]\n# def __len__(self):\n# return len(self.data)\n\ndef MergeFn(density=0.5):\n\n def merge(tbl):\n #targets=[x['target'] for x in tbl]\n locations=[]\n features=[]\n targets=[]\n\n mask = torch.FloatTensor(32, 32).uniform_() <= density \n #print(mask)\n\n for idx, item in enumerate(tbl):\n l = []\n f = []\n for r in range(0, item[0].shape[1]):\n for c in range(0, item[0].shape[2]):\n if mask[r,c] == True:\n #print(str(r) + \" \" + str(c))\n l.append([r, c])\n f.append(item[0][:,r,c].tolist())\n\n l = torch.LongTensor(l)\n #print(\"l raw\")\n #print(l)\n l = torch.cat([l,torch.LongTensor([idx]).expand([l.size(0),1])],1)\n #print(\"l padded\")\n #print(l)\n locations.append(l)\n #print(\"f raw\")\n #print(f)\n f = torch.FloatTensor(f)\n #print(\"f padded\")\n #print(f)\n features.append(f)\n targets.append(item[1])\n\n return {'input': scn.InputLayerInput(torch.cat(locations,0), torch.cat(features,0)), 'target': torch.LongTensor(targets)}\n return merge\n\n\ndef get_iterators(*args):\n\n normalize = transforms.Normalize(mean=[0.491, 0.482, 0.447], std=[0.247, 0.243, 0.262])\n\n train_dataset = torchvision.datasets.CIFAR10(\n root='./data', \n train=True, \n download=True,\n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n\n test_dataset = torchvision.datasets.CIFAR10(\n root='./data',\n train=False,\n download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ]))\n\n return {'train': torch.utils.data.DataLoader(train_dataset, collate_fn=MergeFn(), batch_size=128, shuffle=True, num_workers=10),\n 'val': torch.utils.data.DataLoader(test_dataset, collate_fn=MergeFn(), batch_size=100, shuffle=True, num_workers=10)}\n"
] |
[
[
"torch.LongTensor",
"torch.FloatTensor",
"torch.cat"
]
] |
HanKun66/haker_ner
|
[
"7c05a10987d82394c9b1a471ca7fdc302cf4e646"
] |
[
"train.py"
] |
[
"\"\"\"Train and evaluate the model\"\"\"\nimport os\nimport torch\nimport utils\nimport random\nimport logging\nimport argparse\nimport torch.nn as nn\nfrom tqdm import trange\nfrom evaluate import evaluate\nfrom data_loader import DataLoader\nfrom SequenceTagger import BertForSequenceTagging\nfrom transformers.optimization import get_linear_schedule_with_warmup, AdamW\n\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', default='conll', help=\"Directory containing the dataset\")\nparser.add_argument('--seed', type=int, default=2019, help=\"random seed for initialization\")\nparser.add_argument('--restore_dir', default=None,\n help=\"Optional, name of the directory containing weights to reload before training, e.g., 'experiments/conll/'\")\n\n\ndef train_epoch(model, data_iterator, optimizer, scheduler, params):\n \"\"\"Train the model on `steps` batches\"\"\"\n # set model to training mode\n model.train()\n\n # a running average object for loss\n loss_avg = utils.RunningAverage()\n \n # Use tqdm for progress bar\n one_epoch = trange(params.train_steps)\n for batch in one_epoch:\n # fetch the next training batch\n batch_data, batch_token_starts, batch_tags = next(data_iterator)\n batch_masks = batch_data.gt(0) # get padding mask\n\n # compute model output and loss\n loss = model((batch_data, batch_token_starts), token_type_ids=None, attention_mask=batch_masks, labels=batch_tags)[0]\n\n # clear previous gradients, compute gradients of all variables wrt loss\n model.zero_grad()\n loss.backward()\n\n # gradient clipping\n nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=params.clip_grad)\n\n # performs updates using calculated gradients\n optimizer.step()\n scheduler.step()\n\n # update the average loss\n loss_avg.update(loss.item())\n one_epoch.set_postfix(loss='{:05.3f}'.format(loss_avg()))\n \n\ndef train_and_evaluate(model, train_data, val_data, optimizer, scheduler, params, model_dir, restore_dir=None):\n \"\"\"Train the model and evaluate every epoch.\"\"\"\n # reload weights from restore_dir if specified\n if restore_dir is not None:\n model = BertForSequenceTagging.from_pretrained(tagger_model_dir)\n \n best_val_f1 = 0.0\n patience_counter = 0\n\n for epoch in range(1, params.epoch_num + 1):\n # Run one epoch\n logging.info(\"Epoch {}/{}\".format(epoch, params.epoch_num))\n\n # Compute number of batches in one epoch\n params.train_steps = params.train_size // params.batch_size\n params.val_steps = params.val_size // params.batch_size\n\n # data iterator for training\n train_data_iterator = data_loader.data_iterator(train_data, shuffle=True)\n\n # Train for one epoch on training set\n train_epoch(model, train_data_iterator, optimizer, scheduler, params)\n\n # data iterator for evaluation\n # train_data_iterator = data_loader.data_iterator(train_data, shuffle=False)\n val_data_iterator = data_loader.data_iterator(val_data, shuffle=False)\n\n # Evaluate for one epoch on training set and validation set\n # params.eval_steps = params.train_steps\n # train_metrics = evaluate(model, train_data_iterator, params, mark='Train') # callback train f1\n params.eval_steps = params.val_steps\n val_metrics = evaluate(model, val_data_iterator, params, mark='Val')\n \n val_f1 = val_metrics['f1']\n improve_f1 = val_f1 - best_val_f1\n if improve_f1 > 1e-5: \n logging.info(\"- Found new best F1\")\n best_val_f1 = val_f1\n model.save_pretrained(model_dir)\n if improve_f1 < params.patience:\n patience_counter += 1\n else:\n patience_counter = 0\n else:\n patience_counter += 1\n\n # Early stopping and logging best f1\n if (patience_counter >= params.patience_num and epoch > params.min_epoch_num) or epoch == params.epoch_num:\n logging.info(\"Best val f1: {:05.2f}\".format(best_val_f1))\n break\n \n\nif __name__ == '__main__':\n args = parser.parse_args()\n tagger_model_dir = 'experiments/' + args.dataset\n\n # Load the parameters from json file\n json_path = os.path.join(tagger_model_dir, 'params.json')\n assert os.path.isfile(json_path), \"No json configuration file found at {}\".format(json_path)\n params = utils.Params(json_path)\n\n # Use GPUs if available\n params.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # Set the random seed for reproducible experiments\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n params.seed = args.seed\n \n # Set the logger\n utils.set_logger(os.path.join(tagger_model_dir, 'train.log'))\n logging.info(\"device: {}\".format(params.device))\n\n # Create the input data pipeline\n \n # Initialize the DataLoader\n data_dir = 'data/' + args.dataset\n\n #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n #这里设置模型位置\n #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n if args.dataset in [\"conll\"]:\n bert_class = 'bert-base-cased' # auto\n # bert_class = 'pretrained_bert_models/bert-base-cased/' # manual\n elif args.dataset in [\"msra\"]:\n bert_class = 'bert-base-chinese' # auto\n # bert_class = 'pretrained_bert_models/bert-base-chinese/' # manual\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n # 理解下token_pad_idx,tag_pad_idx\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n data_loader = DataLoader(data_dir, bert_class, params, token_pad_idx=0, tag_pad_idx=-1)\n \n logging.info(\"Loading the datasets...\")\n\n # Load training data and test data\n train_data = data_loader.load_data('train')\n val_data = data_loader.load_data('val')\n\n # Specify the training and validation dataset sizes\n params.train_size = train_data['size']\n params.val_size = val_data['size']\n \n logging.info(\"Loading BERT model...\")\n\n # Prepare model\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n # 这里设置label数量为len(params.tag2idx))\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n model = BertForSequenceTagging.from_pretrained(bert_class, num_labels=len(params.tag2idx))\n model.to(params.device)\n\n # Prepare optimizer\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n # 加载预训练模型的数据\n # *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**#*\n if params.full_finetuning:\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], \n 'weight_decay': params.weight_decay},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], \n 'weight_decay': 0.0}\n ]\n else: # only finetune the head classifier\n param_optimizer = list(model.classifier.named_parameters()) \n optimizer_grouped_parameters = [{'params': [p for n, p in param_optimizer]}]\n \n\n optimizer = AdamW(optimizer_grouped_parameters, lr=params.learning_rate, correct_bias=False)\n train_steps_per_epoch = params.train_size // params.batch_size\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=train_steps_per_epoch, num_training_steps=params.epoch_num * train_steps_per_epoch)\n\n # Train and evaluate the model\n logging.info(\"Starting training for {} epoch(s)\".format(params.epoch_num))\n train_and_evaluate(model, train_data, val_data, optimizer, scheduler, params, tagger_model_dir, args.restore_dir)"
] |
[
[
"torch.manual_seed",
"torch.cuda.is_available"
]
] |
determinant-io/aboleth
|
[
"53a3de23dce4d607ffec92be936e83d2dd7ebb3c"
] |
[
"tests/test_utils.py"
] |
[
"\"\"\"Test the aboleth utilities.\"\"\"\n\nfrom types import GeneratorType\n\nimport numpy as np\nimport tensorflow as tf\n\nimport aboleth as ab\n\n\ndef test_batch():\n \"\"\"Test the batch feed dict generator.\"\"\"\n X = np.arange(100)\n fd = {'X': X}\n\n data = ab.batch(fd, batch_size=10, n_iter=10)\n\n # Make sure this is a generator\n assert isinstance(data, GeneratorType)\n\n # Make sure we get a dict back of a length we expect\n d = next(data)\n assert isinstance(d, dict)\n assert 'X' in d\n assert len(d['X']) == 10\n\n # Test we get all of X back in one sweep of the data\n accum = list(d['X'])\n for ds in data:\n assert len(ds['X']) == 10\n accum.extend(list(ds['X']))\n\n assert len(accum) == len(X)\n assert set(X) == set(accum)\n\n\ndef test_batch_predict():\n \"\"\"Test the batch prediction feed dict generator.\"\"\"\n X = np.arange(100)\n fd = {'X': X}\n\n data = ab.batch_prediction(fd, batch_size=10)\n\n # Make sure this is a generator\n assert isinstance(data, GeneratorType)\n\n # Make sure we get a dict back of a length we expect with correct indices\n for ind, d in data:\n assert isinstance(d, dict)\n assert 'X' in d\n assert len(d['X']) == 10\n assert all(X[ind] == d['X'])\n"
] |
[
[
"numpy.arange"
]
] |
linthieda/ynn
|
[
"8c3334c57fc461e4883027dbc0559b961a206922",
"8c3334c57fc461e4883027dbc0559b961a206922",
"8c3334c57fc461e4883027dbc0559b961a206922"
] |
[
"script/script_2_1_naive.py",
"script/script_3_1_preprocessing.py",
"script/script_4_0_pbp.py"
] |
[
"# required python version: 3.6+\n\nimport os\nimport sys\nimport src.load_data as load_data\nfrom src import layer\nimport src.rbm as rbm\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\n\n# format of data\n# disitstrain.txt contains 3000 lines, each line 785 numbers, comma delimited\n\nfull_path = os.path.realpath(__file__)\npath, filename = os.path.split(full_path)\ndata_filepath = '../data'\ndata_train_filename = 'digitstrain.txt'\ndata_valid_filename = 'digitsvalid.txt'\ndata_test_filename = 'digitstest.txt'\n\ndata_train_filepath = os.path.join(path, data_filepath, data_train_filename)\ndata_valid_filepath = os.path.join(path, data_filepath, data_valid_filename)\ndata_test_filepath = os.path.join(path, data_filepath, data_test_filename)\n\nprint('start initializing...')\n#rbm.init_rbm(random_seed=1099)\n#numpy.random.RandomState(seed=1099)\nnumpy.random.seed(1099)\n\nx_train, y_train = load_data.load_from_path(data_train_filepath)\nx_valid, y_valid = load_data.load_from_path(data_valid_filepath)\n\nmyRBM = rbm.RBM(28*28, hidden_units=100)\nmyRBM.set_visualize(28,28)\nmyRBM.set_autostop(window=40, stride=20)\nmyRBM.train(x_train, x_valid, k=1, epoch=3000, learning_rate=0.1, batch_size=128, plotfile='script-2-1-naive')\n",
"# required python version: 3.6+\n\nimport os\nimport sys\nimport src.load_data as load_data\nfrom src import layer\nimport src.rbm as rbm\nimport src.autoencoder as autoencoder\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\nimport pickle\n\n# Phase 0: Read File\nfull_path = os.path.realpath(__file__)\npath, filename = os.path.split(full_path)\ndata_filepath = '../data'\nsave_filepath = '../output/n-gram'\ndump_filepath = '../output/dump'\ngram_name = '4-gram.png'\ndictionary_name = 'dictionary.dump'\ninv_dictionary_name = 'inv-dictionary.dump'\ndata_train_filename = 'train.txt'\ndata_valid_filename = 'val.txt'\ndata_train_dump_filename = 'train.dump'\ndata_valid_dump_filename = 'valid.dump'\n\ndata_train_filepath = os.path.join(path, data_filepath, data_train_filename)\ndata_valid_filepath = os.path.join(path, data_filepath, data_valid_filename)\ngram_savepath = os.path.join(path, save_filepath, gram_name)\ndictionary_dumppath = os.path.join(path, dump_filepath, dictionary_name)\ninv_dictionary_dumppath = os.path.join(path, dump_filepath, inv_dictionary_name)\ndata_train_dump_filepath = os.path.join(path, dump_filepath, data_train_dump_filename)\ndata_valid_dump_filepath = os.path.join(path, dump_filepath, data_valid_dump_filename)\n\n# load text data from path\ndef load_from_path(data_filepath):\n # data_train: numpy.ndarray\n data_input = numpy.loadtxt(data_filepath, dtype=str, delimiter='\\n')\n # x_train: numpy.ndarray\n return data_input\ndata_train = load_from_path(data_train_filepath)\ndata_valid = load_from_path(data_valid_filepath)\n\n\n# Phase 1: split\n\n# Create a vocabulary dictionary you are required to create an entry for every word in the training set\n# also, make the data lower-cased\ndef split_lins(data_input):\n all_lines: list = []\n train_size = data_input.size\n # will serve as a lookup table for the words and their corresponding id.\n for i in range(train_size):\n tmp_list = data_input[i].lower().split()\n tmp_list.insert(0, 'START')\n tmp_list.append('END')\n all_lines.insert(i, tmp_list)\n return all_lines\n\nall_lines_train = split_lins(data_train)\nall_lines_valid = split_lins(data_valid)\n\n\n# build the dictionary\ndef build_vocabulary(all_lines: list):\n vocabulary: dict = {}\n train_size = len(all_lines)\n for i in range(train_size):\n for word in all_lines[i]:\n try:\n vocabulary[word] += 1\n except KeyError:\n vocabulary[word] = 1\n return vocabulary\n\n\nvocabulary = build_vocabulary(all_lines_train)\n\n\n# truncate the dictionary\ndef truncate_dictionary(dictionary: dict, size: int):\n sorted_list = sorted(vocabulary.items(), key=lambda x:x[1])\n sorted_list.reverse()\n dictionary_size = size\n truncated_vocabulary: dict = {}\n for i in range(dictionary_size - 1):\n word, freq = sorted_list[i]\n truncated_vocabulary[word] = freq\n truncated_vocabulary['UNK'] = 0\n for i in range(dictionary_size - 1, vocabulary.__len__()):\n _, freq = sorted_list[i]\n truncated_vocabulary['UNK'] += freq\n\n # re-sort the dictionary\n sorted_list = sorted(truncated_vocabulary.items(), key=lambda x:x[1])\n sorted_list.reverse()\n dictionary_size = 8000\n truncated_vocabulary: dict = {}\n for i in range(dictionary_size - 1):\n word, freq = sorted_list[i]\n truncated_vocabulary[word] = freq\n return truncated_vocabulary\n\ntruncated_vocabulary = truncate_dictionary(vocabulary, 8000)\n\n\n# generate a dictionary map string to IDs\ndef gen_word_to_id_dict(vocabulary):\n dictionary: dict = {}\n idn = 0\n for word in truncated_vocabulary:\n dictionary[word] = idn\n idn += 1\n return dictionary\n\ndict_word_to_id = gen_word_to_id_dict(truncated_vocabulary)\n\n\n# replace less frequent words in all_lines with 'UNK'\ndef replace_with_unk(all_lines, dict_word_to_id):\n tokenized_lines = []\n train_size = len(all_lines)\n for i in range(train_size):\n tokenized_lines.append([])\n for j in range(len(all_lines[i])):\n if not all_lines[i][j] in truncated_vocabulary:\n tokenized_lines[i].append(dict_word_to_id['UNK'])\n else:\n tokenized_lines[i].append(dict_word_to_id[all_lines[i][j]])\n return tokenized_lines\n\ntokenized_lines_train = replace_with_unk(all_lines_train, dict_word_to_id)\ntokenized_lines_valid = replace_with_unk(all_lines_valid, dict_word_to_id)\n\n\n# build a 4-gram\ndef build_four_gram(tokenized_lines):\n four_gram: dict = {}\n for i in range(len(tokenized_lines)):\n cur_line = tokenized_lines[i]\n cur_len = len(cur_line)\n if (cur_len < 4):\n continue\n for j in range(cur_len-3):\n cur_tuple = (cur_line[j], cur_line[j+1], cur_line[j+2], cur_line[j+3])\n try:\n four_gram[cur_tuple] += 1\n except KeyError:\n four_gram[cur_tuple] = 1\n\n # sort the 4-gram\n sorted_list = sorted(four_gram.items(), key=lambda x:x[1])\n sorted_list.reverse()\n return sorted_list\n\nfour_gram_train = build_four_gram(tokenized_lines_train)\nfour_gram_valid = build_four_gram(tokenized_lines_valid)\n\n\n# plot the 4-gram\ndef plot_four_gram(four_gram: list):\n x_axis = numpy.arange(four_gram.__len__())\n y_axis = numpy.zeros(four_gram.__len__())\n for i in range(four_gram.__len__()):\n y_axis[i] = four_gram[i][1]\n\n plt.figure(1)\n line_1, = plt.plot(y_axis, label='4-gram')\n plt.xlabel('the ids sorted by the frequency')\n plt.ylabel('frequency')\n plt.title('4-gram')\n plt.savefig(gram_savepath)\n plt.close(1)\n return\n\nflag_plot_four_gram = True\nif flag_plot_four_gram:\n plot_four_gram(four_gram_train)\n\n# invert the key-value pair of dictionary\ninv_dictionary = {v: k for k, v in dict_word_to_id.items()}\n\n\ndef print_top_four_gram(four_gram: list, top_num: int):\n for i in range(top_num):\n gram_tuple = four_gram[i][0]\n print(inv_dictionary[gram_tuple[0]],\n inv_dictionary[gram_tuple[1]],\n inv_dictionary[gram_tuple[2]],\n inv_dictionary[gram_tuple[3]],\n sep=' ')\n return\n\nflag_print_most_frequent_grams: bool = True\nif flag_print_most_frequent_grams:\n print_top_four_gram(four_gram_train, 50)\n\n# dump the dictionary for later use\nwith open(dictionary_dumppath, 'wb+') as f:\n pickle.dump(dict_word_to_id, f)\nwith open(inv_dictionary_dumppath, 'wb+') as f:\n pickle.dump(inv_dictionary, f)\n\n# generate the one-hot representation of inputs\n# get the number of the inputs\ndef process_four_gram(four_gram):\n num_input: int = len(four_gram)\n X: numpy.ndarray\n for i in range(num_input):\n tup = four_gram[i]\n w1 = tup[0][0]\n w2 = tup[0][1]\n w3 = tup[0][2]\n w4 = tup[0][3]\n\n for j in range(tup[1]):\n array = numpy.array([w1, w2, w3, w4]).reshape(1, 4)\n try:\n X = numpy.concatenate((X, array), axis=0)\n except NameError:\n X = array\n return X\n\nX_train = process_four_gram(four_gram_train)\nX_valid = process_four_gram(four_gram_valid)\n\n# dump the one-hot representation of input\nwith open(data_train_dump_filepath, 'wb+') as f:\n pickle.dump(X_train, f)\nwith open(data_valid_dump_filepath, 'wb+') as f:\n pickle.dump(X_valid, f)\n\nprint(truncated_vocabulary['UNK'])\n\n\n\n# Phase 3: Compute the number of trainable parameters in the network\nflag_print_num_trainable: bool = True\nif flag_print_num_trainable:\n print(8000 * 16 + 128 * 16 * 3 + 128 + 8000 * 128 + 8000)",
"# required python version: 3.6+\n\nif __name__ == \"__main__\" and __package__ is None:\n from sys import path\n from os.path import dirname as dir\n\n path.append(dir(path[0]))\n # __package__ = \"src\"\n\n\nimport numpy\n\n\nimport src.callback as cb\nimport src.train as utf\n\nfrom src.util.status import DataStore\nfrom src.util.status import TrainSettings\nfrom src import network\nfrom src import layer\n\nimport tensorflow as tf\n\n\n\n\n\n# set the random seed\nnumpy.random.seed(1099)\n\n\nmnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\nx_train = mnist.train.images # 55000 x 784\nx_valid = mnist.validation.images # 5000 x 784\n\ny_train = mnist.train.labels\ny_valid = mnist.validation.labels\n\ndata_store_train = DataStore(x_train, y_train)\ndata_store_valid = DataStore(x_valid, y_valid)\n\n#############################\n\nprint('Settings 1')\ntrain_settings = TrainSettings(learning_rate=0.001, batch_size=16, momentum=0.0, plot_callback=cb.plot_callback,\n loss_callback=cb.loss_callback, filename='script-4-0-1', epoch=200, prefix='e16')\n\nlayers = [layer.ProbabilisticGaussianLinear(784, 100),\n #layer.BN(100, 100),\n layer.Sigmoid(100),\n layer.ProbabilisticGaussianLinear(100, 10),\n layer.Softmax(10)]\n\nmynn = network.MLP(layers)\n\nutf.cross_train(mynn, data_store_train, data_store_valid, train_settings)\n\n#########################\n\nprint('Settings 2')\ntrain_settings = TrainSettings(learning_rate=0.002, batch_size=16, momentum=0.0, plot_callback=cb.plot_callback,\n loss_callback=cb.loss_callback, filename='script-4-0-2', epoch=200, prefix='e16')\n\nlayers = [layer.ProbabilisticGaussianLinear(784, 100),\n #layer.BN(100, 100),\n layer.Sigmoid(100),\n layer.ProbabilisticGaussianLinear(100, 10),\n layer.Softmax(10)]\n\nmynn = network.MLP(layers)\n\nutf.cross_train(mynn, data_store_train, data_store_valid, train_settings)\n\n#############################\nprint('Settings 3')\ntrain_settings = TrainSettings(learning_rate=0.005, batch_size=16, momentum=0.0, plot_callback=cb.plot_callback,\n loss_callback=cb.loss_callback, filename='script-4-0-3', epoch=200, prefix='e16')\n\nlayers = [layer.ProbabilisticGaussianLinear(784, 100),\n #layer.BN(100, 100),\n layer.Sigmoid(100),\n layer.ProbabilisticGaussianLinear(100, 10),\n layer.Softmax(10)]\n\nmynn = network.MLP(layers)\n\nutf.cross_train(mynn, data_store_train, data_store_valid, train_settings)\n\n\n\nprint('Settings 4')\ntrain_settings = TrainSettings(learning_rate=0.01, batch_size=16, momentum=0.0, plot_callback=cb.plot_callback,\n loss_callback=cb.loss_callback, filename='script-4-0-4', epoch=300, prefix='e16')\n\nlayers = [layer.ProbabilisticGaussianLinear(784, 100),\n #layer.BN(100, 100),\n layer.Sigmoid(100),\n layer.ProbabilisticGaussianLinear(100, 10),\n layer.Softmax(10)]\n\nmynn = network.MLP(layers)\n\nutf.cross_train(mynn, data_store_train, data_store_valid, train_settings)\n"
] |
[
[
"numpy.random.seed"
],
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"numpy.concatenate",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"numpy.array",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
],
[
"tensorflow.contrib.learn.datasets.load_dataset",
"numpy.random.seed"
]
] |
xmyhhh/DBPN-Pytorch
|
[
"7e6852658605ec59347661f88251e6c92ff5e56e"
] |
[
"base_networks.py"
] |
[
"import torch\nimport math\n\nclass DenseBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, bias=True, activation='relu', norm='batch'):\n super(DenseBlock, self).__init__()\n self.fc = torch.nn.Linear(input_size, output_size, bias=bias)\n\n self.norm = norm\n if self.norm =='batch':\n self.bn = torch.nn.BatchNorm1d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm1d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.fc(x))\n else:\n out = self.fc(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass ConvBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu', norm=None):\n super(ConvBlock, self).__init__()\n self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm =='batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.conv(x))\n else:\n out = self.conv(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass DeconvBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu', norm=None):\n super(DeconvBlock, self).__init__()\n self.deconv = torch.nn.ConvTranspose2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif self.norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.deconv(x))\n else:\n out = self.deconv(x)\n\n if self.activation is not None:\n return self.act(out)\n else:\n return out\n\n\nclass ResnetBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu', norm='batch'):\n super(ResnetBlock, self).__init__()\n self.conv1 = torch.nn.Conv2d(num_filter, num_filter, kernel_size, stride, padding, bias=bias)\n self.conv2 = torch.nn.Conv2d(num_filter, num_filter, kernel_size, stride, padding, bias=bias)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(num_filter)\n elif norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(num_filter)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n\n def forward(self, x):\n residual = x\n if self.norm is not None:\n out = self.bn(self.conv1(x))\n else:\n out = self.conv1(x)\n\n if self.activation is not None:\n out = self.act(out)\n\n if self.norm is not None:\n out = self.bn(self.conv2(out))\n else:\n out = self.conv2(out)\n\n out = torch.add(out, residual)\n return out\n\nclass UpBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, bias=True, activation='prelu', norm=None):\n super(UpBlock, self).__init__()\n self.up_conv1 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv3 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None) \n\n def forward(self, x):\n \th0 = self.up_conv1(x)\n \tl0 = self.up_conv2(h0)\n \th1 = self.up_conv3(l0 - x)\n \treturn h1 + h0\n\nclass UpBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, scale=4, bias=True, activation='prelu', norm=None):\n super(UpBlockPix, self).__init__()\n self.up_conv1 = Upsampler(scale,num_filter)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv3 = Upsampler(scale,num_filter) \n\n def forward(self, x):\n \th0 = self.up_conv1(x)\n \tl0 = self.up_conv2(h0)\n \th1 = self.up_conv3(l0 - x)\n \treturn h1 + h0\n \nclass D_UpBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, bias=True, activation='prelu', norm=None):\n super(D_UpBlock, self).__init__()\n self.conv = ConvBlock(num_filter*num_stages, num_filter, 1, 1, 0, activation, norm=None)\n self.up_conv1 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv3 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None) \n\n def forward(self, x):\n \tx = self.conv(x)\n \th0 = self.up_conv1(x)\n \tl0 = self.up_conv2(h0)\n \th1 = self.up_conv3(l0 - x)\n \treturn h1 + h0\n\nclass D_UpBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, scale=4, bias=True, activation='prelu', norm=None):\n super(D_UpBlockPix, self).__init__()\n self.conv = ConvBlock(num_filter*num_stages, num_filter, 1, 1, 0, activation, norm=None)\n self.up_conv1 = Upsampler(scale,num_filter)\n self.up_conv2 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.up_conv3 = Upsampler(scale,num_filter)\n\n def forward(self, x):\n \tx = self.conv(x)\n \th0 = self.up_conv1(x)\n \tl0 = self.up_conv2(h0)\n \th1 = self.up_conv3(l0 - x)\n \treturn h1 + h0\n\nclass DownBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, bias=True, activation='prelu', norm=None):\n super(DownBlock, self).__init__()\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv2 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n\n def forward(self, x):\n \tl0 = self.down_conv1(x)\n \th0 = self.down_conv2(l0)\n \tl1 = self.down_conv3(h0 - x)\n \treturn l1 + l0\n\nclass DownBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, scale=4,bias=True, activation='prelu', norm=None):\n super(DownBlockPix, self).__init__()\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv2 = Upsampler(scale,num_filter)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n\n def forward(self, x):\n \tl0 = self.down_conv1(x)\n \th0 = self.down_conv2(l0)\n \tl1 = self.down_conv3(h0 - x)\n \treturn l1 + l0\n\nclass D_DownBlock(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, bias=True, activation='prelu', norm=None):\n super(D_DownBlock, self).__init__()\n self.conv = ConvBlock(num_filter*num_stages, num_filter, 1, 1, 0, activation, norm=None)\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv2 = DeconvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n\n def forward(self, x):\n \tx = self.conv(x)\n \tl0 = self.down_conv1(x)\n \th0 = self.down_conv2(l0)\n \tl1 = self.down_conv3(h0 - x)\n \treturn l1 + l0\n\nclass D_DownBlockPix(torch.nn.Module):\n def __init__(self, num_filter, kernel_size=8, stride=4, padding=2, num_stages=1, scale=4, bias=True, activation='prelu', norm=None):\n super(D_DownBlockPix, self).__init__()\n self.conv = ConvBlock(num_filter*num_stages, num_filter, 1, 1, 0, activation, norm=None)\n self.down_conv1 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n self.down_conv2 = Upsampler(scale,num_filter)\n self.down_conv3 = ConvBlock(num_filter, num_filter, kernel_size, stride, padding, activation, norm=None)\n\n def forward(self, x):\n \tx = self.conv(x)\n \tl0 = self.down_conv1(x)\n \th0 = self.down_conv2(l0)\n \tl1 = self.down_conv3(h0 - x)\n \treturn l1 + l0\n\nclass PSBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, scale_factor, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu', norm='batch'):\n super(PSBlock, self).__init__()\n self.conv = torch.nn.Conv2d(input_size, output_size * scale_factor**2, kernel_size, stride, padding, bias=bias)\n self.ps = torch.nn.PixelShuffle(scale_factor)\n\n self.norm = norm\n if self.norm == 'batch':\n self.bn = torch.nn.BatchNorm2d(output_size)\n elif norm == 'instance':\n self.bn = torch.nn.InstanceNorm2d(output_size)\n\n self.activation = activation\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n if self.norm is not None:\n out = self.bn(self.ps(self.conv(x)))\n else:\n out = self.ps(self.conv(x))\n\n if self.activation is not None:\n out = self.act(out)\n return out\n\n\nclass Upsampler(torch.nn.Module):\n def __init__(self, scale, n_feat, bn=False, act='prelu', bias=True):\n super(Upsampler, self).__init__()\n modules = []\n for _ in range(int(math.log(scale, 2))):\n modules.append(ConvBlock(n_feat, 4 * n_feat, 3, 1, 1, bias, activation=None, norm=None))\n modules.append(torch.nn.PixelShuffle(2))\n if bn: modules.append(torch.nn.BatchNorm2d(n_feat))\n #modules.append(torch.nn.PReLU())\n self.up = torch.nn.Sequential(*modules)\n \n self.activation = act\n if self.activation == 'relu':\n self.act = torch.nn.ReLU(True)\n elif self.activation == 'prelu':\n self.act = torch.nn.PReLU()\n elif self.activation == 'lrelu':\n self.act = torch.nn.LeakyReLU(0.2, True)\n elif self.activation == 'tanh':\n self.act = torch.nn.Tanh()\n elif self.activation == 'sigmoid':\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n out = self.up(x)\n if self.activation is not None:\n out = self.act(out)\n return out\n \n\nclass Upsample2xBlock(torch.nn.Module):\n def __init__(self, input_size, output_size, bias=True, upsample='deconv', activation='relu', norm='batch'):\n super(Upsample2xBlock, self).__init__()\n scale_factor = 2\n # 1. Deconvolution (Transposed convolution)\n if upsample == 'deconv':\n self.upsample = DeconvBlock(input_size, output_size,\n kernel_size=4, stride=2, padding=1,\n bias=bias, activation=activation, norm=norm)\n\n # 2. Sub-pixel convolution (Pixel shuffler)\n elif upsample == 'ps':\n self.upsample = PSBlock(input_size, output_size, scale_factor=scale_factor,\n bias=bias, activation=activation, norm=norm)\n\n # 3. Resize and Convolution\n elif upsample == 'rnc':\n self.upsample = torch.nn.Sequential(\n torch.nn.Upsample(scale_factor=scale_factor, mode='nearest'),\n ConvBlock(input_size, output_size,\n kernel_size=3, stride=1, padding=1,\n bias=bias, activation=activation, norm=norm)\n )\n\n def forward(self, x):\n out = self.upsample(x)\n return out\n\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.add",
"torch.nn.ConvTranspose2d",
"torch.nn.InstanceNorm1d",
"torch.nn.PReLU",
"torch.nn.Conv2d",
"torch.nn.PixelShuffle",
"torch.nn.Tanh",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.InstanceNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.Upsample",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
jjakimoto/BBoptimizer
|
[
"fcc58393905ee72184ad3759ea444bc52b9a3a2d"
] |
[
"bboptimizer/samplers/utils.py"
] |
[
"from collections import defaultdict\nimport numpy as np\nimport random\nfrom scipy.stats import norm\n\n\nSAMPLERS_MAP = dict()\n\n\ndef register(cls):\n SAMPLERS_MAP[cls.sampler_name] = cls\n\n\ndef _random_sample(params_conf):\n \"\"\"Sample parameters at random with dictionary format\n\n Parameters\n ----------\n params_conf: list(dict) or dict\n\n Returns\n -------\n params_dict : dict\n key is a name of each parameter\n \"\"\"\n if len(params_conf) == 0 or not isinstance(params_conf[0], list):\n params_conf = [params_conf]\n params_conf = random.sample(params_conf, k=1)[0]\n params_dict = {}\n for conf in params_conf:\n name = conf[\"name\"]\n domain = conf[\"domain\"]\n type_ = conf[\"type\"]\n scale = conf.get('scale', None)\n if type_ == \"continuous\":\n if scale == 'log':\n param = np.random.uniform(np.log10(domain[0]),\n np.log10(domain[1]))\n param = 10 ** param\n else:\n param = np.random.uniform(domain[0], domain[1])\n elif type_ == \"integer\":\n if scale == 'log':\n param = np.random.uniform(np.log10(domain[0]),\n np.log10(domain[1]))\n param = round(10 ** param)\n else:\n param = np.random.randint(domain[0], domain[1] + 1)\n elif type_ in [\"categorical\", \"discrete\"]:\n param = random.sample(domain, k=1)[0]\n elif type_ == \"fixed\":\n param = domain\n params_dict[name] = param\n return params_dict\n\n\ndef random_sample(params_conf, x=None):\n if x is None:\n x = defaultdict(lambda: None)\n if isinstance(params_conf, dict):\n for key, conf in params_conf.items():\n x[key] = random_sample(conf, x[key])\n else:\n x = _random_sample(params_conf)\n return x\n\n\ndef expected_improvement(x, model, evaluated_loss, jitter=0.01, mode=\"gpy\"):\n \"\"\"Expected improvement acquisition function.\n\n Note\n ----\n This implementation aims for minimization\n\n Parameters:\n ----------\n x: array-like, shape = (n_hyperparams,)\n model: GaussianProcessRegressor object.\n Gaussian process trained on previously evaluated hyperparameters.\n evaluated_loss: array-like(float), shape = (# historical results,).\n the values of the loss function for the previously evaluated\n hyperparameters.\n jitter: float\n positive value to make the acquisition more explorative.\n \"\"\"\n\n x = np.atleast_2d(x)\n if mode == \"gpy\":\n mu, var = model.predict(x)\n # Consider 1d case\n sigma = np.sqrt(var)[0, 0]\n mu = mu[0, 0]\n elif mode == \"sklearn\":\n mu, sig = model.predict(x, return_std=True)\n mu = mu[0]\n sigma = sig[0]\n else:\n raise ValueError()\n # Avoid too small sigma\n if sigma == 0.:\n return 0.\n else:\n loss_optimum = np.min(evaluated_loss)\n gamma = (loss_optimum - mu - jitter) / sigma\n ei_val = sigma * (gamma * norm.cdf(gamma) + norm.pdf(gamma))\n return ei_val\n"
] |
[
[
"numpy.sqrt",
"scipy.stats.norm.pdf",
"numpy.min",
"scipy.stats.norm.cdf",
"numpy.atleast_2d",
"numpy.log10",
"numpy.random.uniform",
"numpy.random.randint"
]
] |
conghaowoooong/Project-Erina
|
[
"e4e645a348d5df6d571d5334a0e2d5ecba8466bb"
] |
[
"helpmethods.py"
] |
[
"'''\n@Author: ConghaoWong\n@Date: 2019-12-20 09:39:11\nLastEditors: Conghao Wong\nLastEditTime: 2020-08-16 00:06:03\n@Description: helpmethods\n'''\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\ndef list2array(x):\n return np.array(x)\n\n\ndef dir_check(target_dir):\n \"\"\"\n Used for check if the `target_dir` exists.\n \"\"\"\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n\n return target_dir\n\n\ndef reduce_dim(x, out_dim, pca=True):\n if not pca:\n tsne = TSNE(n_components=out_dim)\n result = tsne.fit_transform(x)\n return result\n\n else:\n x = tf.constant(x)\n s, u, v = tf.linalg.svd(x)\n return tf.matmul(u[:, :out_dim], tf.linalg.diag(s[:out_dim])).numpy()\n\n\ndef calculate_feature_lower_dim(feature, reduction_dimension=2, pca=True, regulation=True):\n current_dimension = feature.shape[1]\n if reduction_dimension < current_dimension:\n feature_vector_low_dim = reduce_dim(\n feature,\n out_dim=reduction_dimension,\n pca=pca,\n )\n else:\n feature_vector_low_dim = feature\n \n if regulation:\n feature_vector_low_dim = (feature_vector_low_dim - np.min(feature_vector_low_dim))/(np.max(feature_vector_low_dim) - np.min(feature_vector_low_dim))\n \n return feature_vector_low_dim\n\n# help methods for linear predict\ndef softmax(x):\n return np.exp(x)/np.sum(np.exp(x),axis=0)\n\n\ndef __predict_linear(x, y, x_p, diff_weights=0):\n if diff_weights == 0:\n P = np.diag(np.ones(shape=[x.shape[0]]))\n else:\n P = np.diag(softmax([(i+1)**diff_weights for i in range(x.shape[0])]))\n\n A = np.stack([np.ones_like(x), x]).T\n A_p = np.stack([np.ones_like(x_p), x_p]).T\n Y = y.T\n B = np.matmul(np.matmul(np.matmul(np.linalg.inv(np.matmul(np.matmul(A.T, P), A)), A.T), P), Y)\n Y_p = np.matmul(A_p, B)\n return Y_p, B\n\n\ndef predict_linear_for_person(position, time_pred, different_weights=0.95):\n \"\"\"\n 对二维坐标的最小二乘拟合\n 注意:`time_pred`中应当包含现有的长度,如`len(position)=8`, `time_pred=20`时,输出长度为20\n \"\"\"\n time_obv = position.shape[0]\n t = np.arange(time_obv)\n t_p = np.arange(time_pred)\n x = position.T[0]\n y = position.T[1]\n\n x_p, _ = __predict_linear(t, x, t_p, diff_weights=different_weights)\n y_p, _ = __predict_linear(t, y, t_p, diff_weights=different_weights)\n\n return np.stack([x_p, y_p]).T\n\n\ndef calculate_ADE_FDE_numpy(pred, GT):\n all_loss = np.linalg.norm(pred - GT, ord=2, axis=1)\n ade = np.mean(all_loss)\n fde = all_loss[-1]\n return ade, fde\n\n\ndef draw_results(feature, result, all_traj='null', detail_save_path='null', whole_save_path='null', only_features=False):\n \"\"\"\n 根据分类结果画图\n\n `feature`: 需要画图的2维特征, \n `result`: 分类结果标签,值为0,1,2,...,n-1, \n `all_traj`: 可选,输入所有特征对应的轨迹,有输入则画出, \n `detail_save_path`: 特征点与所有类轨迹的存储位置,有输入则保存, \n `whole_save_path`: 整体轨迹分布存储位置,有输入则保存, \n `only_features`: 选择图中是否仅画出特征分布\n\n \"\"\"\n cluster_number = (np.max(result) + 1).astype(np.int)\n line_number = max(int(cluster_number//5), 1)\n color = [\n plt.cm.Greys, plt.cm.BuGn, plt.cm.BuPu,\n plt.cm.Oranges, plt.cm.PuBu, plt.cm.PuRd,\n plt.cm.Reds, plt.cm.YlGn, plt.cm.YlGnBu,\n plt.cm.YlOrBr, plt.cm.YlOrRd,\n plt.cm.Greys, plt.cm.BuGn, plt.cm.BuPu,\n plt.cm.Oranges, plt.cm.PuBu, plt.cm.PuRd,\n plt.cm.Reds, plt.cm.YlGn, plt.cm.YlGnBu,\n plt.cm.YlOrBr, plt.cm.YlOrRd,\n plt.cm.Greys, plt.cm.BuGn, plt.cm.BuPu,\n plt.cm.Oranges, plt.cm.PuBu, plt.cm.PuRd,\n plt.cm.Reds, plt.cm.YlGn, plt.cm.YlGnBu,\n plt.cm.YlOrBr, plt.cm.YlOrRd,\n plt.cm.Greys, plt.cm.BuGn, plt.cm.BuPu,\n plt.cm.Oranges, plt.cm.PuBu, plt.cm.PuRd,\n plt.cm.Reds, plt.cm.YlGn, plt.cm.YlGnBu,\n plt.cm.YlOrBr, plt.cm.YlOrRd,\n ]\n\n if not all_traj == 'null':\n mean_traj = []\n for i in range(cluster_number):\n person_index = np.where(result == i)[0].astype(np.int)\n traj_current = np.array([all_traj[person]\n for person in person_index])\n mean = np.mean(traj_current, axis=0)\n mean_traj.append(mean)\n\n if not detail_save_path == 'null':\n plt.figure(figsize=(16, 9))\n for i in range(cluster_number):\n person_index = np.where(result == i)[0].astype(np.int)\n if not only_features:\n plt.subplot(line_number, (cluster_number+1) //\n line_number + 1, 1)\n plt.scatter(\n feature[person_index, 0],\n feature[person_index, 1],\n c=color[i](200),\n )\n plt.axis('scaled')\n\n if (not only_features) and (not all_traj == 'null'):\n for i in range(cluster_number):\n person_index = np.where(result == i)[0].astype(np.int)\n plt.subplot(line_number, (cluster_number+1) //\n line_number + 1, i+2)\n for person in person_index:\n traj = all_traj[person]\n plt.scatter(\n traj[:, 0],\n traj[:, 1],\n c=0.5 + 0.5 *\n (np.arange(0, traj.shape[0])/(traj.shape[0]-1)),\n cmap=color[i],\n alpha=0.5\n )\n\n plt.plot(\n mean_traj[i][:, 0],\n mean_traj[i][:, 1],\n '-*',\n c='black',\n )\n plt.axis('scaled')\n\n plt.savefig(detail_save_path)\n plt.close()\n\n if (not whole_save_path == 'null') and (not all_traj == 'null'):\n plt.figure(figsize=(9, 9))\n plt.subplot(1, 2, 1)\n for i in range(1, cluster_number):\n #person_index = np.where(result==i)[0].astype(np.int)\n # for person in person_index:\n traj = mean_traj[i]\n plt.scatter(\n traj[:, 0],\n traj[:, 1],\n c=0.5 + 0.5*(np.arange(0, traj.shape[0])/(traj.shape[0]-1)),\n cmap=color[i],\n alpha=0.5\n )\n\n plt.subplot(1, 2, 2)\n for i in range(1, cluster_number):\n person_index = np.where(result == i)[0].astype(np.int)\n line_number = all_traj[0].shape[0]\n line_index = np.arange(0, line_number, step=4)\n for person in person_index:\n traj = all_traj[person]\n plt.scatter(\n traj[line_index, 0],\n traj[line_index, 1],\n c=color[i](200),\n alpha=0.1,\n s=50,\n marker='o',\n linewidths=0,\n )\n\n plt.axis('scaled')\n plt.savefig(whole_save_path)\n plt.close()\n\n\ndef draw_test_results(agents_test, log_dir, loss_function, save=True, train_base='agent'):\n if save:\n save_base_dir = dir_check(os.path.join(log_dir, 'test_figs/'))\n save_format = os.path.join(save_base_dir, '{}-pic{}.png')\n \n loss_static = []\n loss_move = []\n\n for index, agent in enumerate(tqdm(agents_test)):\n obs = agent.get_train_traj()\n gt = agent.get_gt_traj()\n pred = agent.get_pred_traj()\n\n # if len(pred.shape) == 3:\n # pred_mean = np.mean(agent.pred, axis=0)\n # else:\n # pred_mean = pred\n\n # loss = loss_function(pred_mean, gt)\n # if np.linalg.norm(obs[0] - gt[-1]) <= 1.0:\n # state = 's'\n # loss_static.append(loss)\n # else:\n # state = 'n'\n # loss_move.append(loss)\n \n if save:\n # print('Saving fig {}...'.format(i), end='\\r')\n # plt.figure(figsize=(20, 20))\n for i in range(len(obs)):\n plt.plot(pred[i].T[0], pred[i].T[1], '-*')\n plt.plot(gt[i].T[0], gt[i].T[1], '-o')\n plt.plot(obs[i].T[0], obs[i].T[1], '-o')\n \n plt.axis('scaled')\n\n if train_base == 'agent':\n ade = loss_function(pred[0], gt[0])\n elif train_base == 'frame':\n ade = loss_function(pred, gt)\n\n plt.title('ADE={}, frame=[{}, {}]'.format(\n ade,\n agent.start_frame,\n agent.end_frame,\n ))\n plt.savefig(save_format.format('f', index))\n plt.close()\n \n # loss_static = np.mean(np.stack(loss_static))\n # loss_move = np.mean(np.stack(loss_move))\n \n # if save:\n # print('\\nSaving done.')\n # print('loss_s = {}, loss_n = {}'.format(loss_static, loss_move))\n "
] |
[
[
"matplotlib.pyplot.plot",
"sklearn.manifold.TSNE",
"numpy.max",
"numpy.mean",
"numpy.exp",
"numpy.where",
"numpy.ones_like",
"tensorflow.linalg.svd",
"numpy.arange",
"numpy.matmul",
"numpy.stack",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"numpy.min",
"tensorflow.linalg.diag",
"matplotlib.pyplot.savefig",
"numpy.array",
"tensorflow.constant",
"numpy.linalg.norm",
"numpy.ones"
]
] |
ashish2020kashyap/cessini
|
[
"9713fd76d2e31a95266ec69da2abc98424a46e52"
] |
[
"anees/views.py"
] |
[
"import csv, io\nfrom django.shortcuts import render,redirect\nfrom django.contrib import messages\nfrom .models import *\nfrom .forms import CampaignForm,CreateUserForm,CustomerForm,EmailForm,EmailUpdateForm,CampUpdateForm\nfrom django.contrib.auth.models import Group,User\nfrom django.contrib.auth import authenticate,login,logout\nfrom .models import Profile,Invalidmail\nfrom django.core.mail import send_mail,EmailMultiAlternatives,send_mass_mail\nfrom django.core.mail import BadHeaderError,send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core import mail\nfrom django.conf import settings\nfrom django.core.mail.message import EmailMessage\nfrom django.contrib.auth.decorators import login_required\nimport re\nfrom django.core.files.storage import default_storage\nfrom django.core.mail import send_mail\nimport pandas as pd\nfrom rest_framework import viewsets\nfrom rest_framework import permissions\nfrom .serializers import UserSerializer, GroupSerializer, CustomerSerializer,EmailSerializer,CampaignSerializer\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n# # Create your views here.\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\n\nclass CustomerViewSet(viewsets.ModelViewSet):\n\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\n\nclass EmailViewSet(viewsets.ModelViewSet):\n\n queryset = Email.objects.all()\n serializer_class = EmailSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\n\nclass CampaignViewSet(viewsets.ModelViewSet):\n\n queryset = Campaign.objects.all()\n serializer_class = CampaignSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef basic(request):\n return render(request,'basic.html')\n\ndef index(request):\n template = \"index.html\"\n data = Profile.objects.all()\n invalid=Invalidmail.objects.all()\n if request.method == \"GET\":\n\n return render(request, template)\n\n csv_file = request.FILES['file']\n\n if not csv_file.name.endswith('.csv'):\n\n messages.error(request,\"This is not csv file,Please try again \")\n return redirect('/index')\n \n\n data_set = csv_file.read().decode('UTF-8')\n io_string = io.StringIO(data_set)\n next(io_string)\n \n\n for column in csv.reader(io_string, delimiter=',', quotechar=\"|\"):\n\n regex = \"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n if(re.search(regex,column[0])):\n _, created = Profile.objects.update_or_create(email=column[0])\n \n else:\n _, created = Invalidmail.objects.update_or_create(email=column[0])\n \n context = {}\n messages.success(request,'Your Record Has Been Uploaded and Updated')\n return render(request,'index.html',context)\n \ndef about(request):\n\n return render(request,'about.html')\n\n\ndef emailslist(request):\n data = Invalidmail.objects.all()\n prompt = {'profiles': data }\n \n \n\n \n return render(request,'emails.html',prompt)\n\n\ndef sendmail(request):\n template=\"contact.html\"\n\n if request.method==\"POST\" and request.FILES['file'] and request.FILES['csv_files']:\n \n subject = request.POST.get('subject', '')\n message = request.POST.get('message', '')\n from_email=settings.EMAIL_HOST_USER\n csv = request.FILES['csv_files']\n csv_file_name = default_storage.save(csv.name, csv)\n\n csv_file = default_storage.open(csv_file_name)\n csv_file_url = default_storage.url(csv_file_name)\n print(csv_file_url)\n file = request.FILES['file']\n file_name = default_storage.save(file.name, file)\n connection = mail.get_connection()\n connection.open()\n\n df_file = pd.read_csv(csv_file)\n #print(df_file)\n\n df = pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n \n\n email= mail.EmailMessage(subject, message, from_email,bcc=list,connection=connection)\n\n file = default_storage.open(file_name)\n file_url = default_storage.url(file_name)\n email.attach(file_url, file.read())\n connection.send_messages([email])\n\n\n\n messages.success(request,\"Email sent Successfully\")\n \n connection.close()\n\n return render(request,'contact.html')\n\n\n\ndef valid(request):\n \n data = Profile.objects.all()\n prompt = {'profiles': data }\n \n return render(request,'validate.html',prompt)\n\n\ndef mailing(request):\n fields = ['Email']\n #df_file= pd.read_csv(\"/Users/ashishkumar/Desktop/email.csv\",skipinitialspace=True, usecols=fields)\n df_file = pd.read_csv(\"/Users/ashishkumar/Desktop/email.csv\")\n df=pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n\n context={'df':df_file.to_html,\n\n 'list':list,\n\n }\n return render(request, 'mailing.html',context)\n\n\ndef dashboard(request,pk_test):\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n customerss = Customer.objects.get(id=pk_test)\n\n\n context = {'campaign': campaign, 'email': email,'customer':customer,'customerss':customerss}\n\n return render(request, 'dashboard.html', context)\n\n\n\ndef profile(request,pk_test):\n users=User.objects.all()\n customer = Customer.objects.all()\n campaign = Campaign.objects.filter(my_customer=pk_test)\n current_user = request.user.id\n email = Email.objects.filter(my_customer=pk_test)\n\n\n\n context = {'campaign': campaign, 'email': email,'customer':customer,'current_user':current_user,'users':users}\n\n return render(request, 'profile.html', context)\n\n\n\n\ndef customer(request):\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n current_user = request.user\n\n\n\n context = {'campaign': campaign, 'email': email,'customer':customer,'current_user':current_user}\n\n return render(request, 'customerhome.html', context)\n\n\n\n\ndef campaign(request):\n\n current_user = request.user.id\n print(current_user)\n customer = Customer.objects.get(id=current_user)\n\n emails = Email.objects.filter(my_customer=current_user)\n file_names=\"\"\n\n if request.method == 'POST':\n name = request.POST.get('name', '')\n sender_name = request.POST.get('sender_name', '')\n sender_email = request.POST.get('sender_email', '')\n email_subject = request.POST.get('email_subject', '')\n mails = request.POST.get('mail')\n mailings = Email.objects.get(id=mails)\n for f in Email.objects.filter(id=mails):\n file_names=f.upload_file\n contact= Campaign(my_customer=customer,name=name,sender_name=sender_name,sender_email=sender_email,email_subject=email_subject,camp_emails=mailings)\n contact.save()\n form = CampaignForm(request.POST)\n print(request.POST)\n\n if form.is_valid():\n form.save()\n print(\"working\")\n return redirect('/customer')\n\n\n print(\"working\")\n return redirect('/customer')\n\n\n else:\n fm = CampaignForm()\n print(\"form is not valid\")\n\n context = {'form':fm,'emails':emails}\n return render(request, 'addcampaign.html', context)\n\n\n\n\n\n\ndef email(request):\n form = EmailForm()\n current_user = request.user.id\n print(current_user)\n customer = Customer.objects.get(id=current_user)\n if request.method == 'POST':\n name = request.POST.get('name', '')\n upload_file = request.FILES['upload_file']\n\n contact= Email(my_customer=customer,name=name,upload_file=upload_file)\n contact.save()\n return redirect('/customer')\n\n\n context = {'form':form}\n\n return render(request, 'addemail.html', context)\n\n\n\n\n\ndef handleSign(request):\n form = CreateUserForm()\n if request.method == 'POST':\n job = request.POST['job']\n print(job)\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user=form.save()\n if job==\"Customer\":\n group = Group.objects.get(name='Customer')\n user.groups.add(group)\n Customer.objects.create(\n user=user,\n name=user.username,\n )\n\n user = form.cleaned_data.get('username')\n messages.success(request, 'Account was created for ' + user)\n return redirect('/')\n else:\n print(\"wrong credentials\")\n context = {'form': form}\n return render(request, 'signup.html', context)\n\n\n\n\n\ndef handleLog(request):\n\n if request.method == 'POST':\n username = request.POST.get('username')\n password =request.POST.get('password')\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n\n group = None\n if request.user.groups.exists():\n group = request.user.groups.all()[0].name\n if group == 'Customer':\n\n return redirect('Customer')\n else:\n messages.info(request, 'Username OR password is incorrect')\n\n context = {}\n return render(request, 'login.html', context)\n\n\ndef updatecamp(request):\n current_user = request.user\n form = CampUpdateForm()\n pi = Customer.objects.get(pk=current_user.id)\n fm = CampUpdateForm(instance=pi)\n print(fm)\n\n if request.method == 'POST':\n\n print(request.POST)\n fm = CampUpdateForm(request.POST,instance=pi)\n fm.save()\n\n print(\"working\")\n return redirect('/customer')\n\n else:\n fm = CampUpdateForm(instance=pi)\n return render(request, 'updatecamp.html', {'form':fm})\n\n\n context = {'current_user ':current_user ,'fm':fm,'form':form}\n return render(request, 'updatecamp.html', context)\n\n\n\ndef updateemail(request):\n #form=CustomerForm()\n current_user = request.user\n\n pi = Customer.objects.get(pk=current_user.id)\n fm = EmailUpdateForm(instance=pi)\n\n if request.method == 'POST':\n\n print(request.POST)\n fm = EmailUpdateForm(request.POST,instance=pi)\n fm.save()\n\n #contact= Customer(user=current_user)\n #contact.save()\n\n print(\"working\")\n return redirect('/customer')\n\n context = {'current_user ':current_user ,'form':fm}\n return render(request, 'updateemail.html', context)\n\n\n\ndef sending(request,pk_test):\n users = User.objects.all()\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n campaigns = Campaign.objects.filter(my_customer=pk_test)\n emails = Email.objects.filter(my_customer=pk_test)\n\n\n\n current_user = request.user\n pi = Customer.objects.get(pk=current_user.id)\n\n if request.method == \"POST\" and request.FILES['file']:\n\n job = request.POST.get('job')\n mails = request.POST.get('mail')\n message= request.POST.get('message')\n subject=\"\"\n file_names=\"\"\n\n for e in Campaign.objects.filter(id=job):\n subject=e.email_subject\n\n for f in Email.objects.filter(id=mails):\n file_names=f.upload_file\n\n\n from_email = settings.EMAIL_HOST_USER\n file = request.FILES['file']\n file_name = default_storage.save(file.name, file)\n df_file = pd.read_csv(file_names)\n #print(df_file)\n connection = mail.get_connection()\n connection.open()\n\n\n df = pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n\n email = mail.EmailMessage(subject, message, from_email, bcc=list, connection=connection)\n\n file = default_storage.open(file_name)\n file_url = default_storage.url(file_name)\n email.attach(file_url, file.read())\n connection.send_messages([email])\n\n messages.success(request, \"Email sent Successfully\")\n\n connection.close()\n\n\n context = {'campaign': campaign, 'email': email,'customer':customer,'current_user':current_user,'campaigns': campaigns, 'emails': emails,}\n return render(request, 'sending.html', context)\n\n\n\ndef manytomany(request,pk_test):\n campmail = CampMail.objects.all()\n\n current_user = request.user.id\n print(current_user)\n customer = Customer.objects.get(id=current_user)\n form= CampaignForm()\n\n\n if request.method == 'GET':\n name = request.GET.get('name', '')\n sender_name = request.GET.get('sender_name', '')\n sender_email = request.GET.get('sender_email', '')\n email_subject = request.GET.get('email_subject', '')\n check = request.GET.get('check', '')\n contact= Campaign(my_customer=customer,name=name,sender_name=sender_name,sender_email=sender_email,email_subject=email_subject)\n #contact.save()\n print(contact)\n print(check)\n form = CampaignForm(request.GET)\n print(request.GET)\n\n if form.is_valid():\n #form.save()\n print(\"working\")\n\n print(\"working\")\n\n else:\n fm = CampaignForm()\n print(\"form is not valid\")\n\n context = {'form':fm}\n return render(request, 'manytomany.html', context)\n\n context={'form':form,'campmail':campmail}\n\n return render(request, 'manytomany.html',context)\n\n\nimport csv, io\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import *\nfrom .forms import CampaignForm, CreateUserForm, CustomerForm, EmailForm, EmailUpdateForm, CampUpdateForm\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.auth import authenticate, login, logout\nfrom .models import Profile, Invalidmail\nfrom django.core.mail import send_mail, EmailMultiAlternatives, send_mass_mail\nfrom django.core.mail import BadHeaderError, send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core import mail\nfrom django.conf import settings\nfrom django.core.mail.message import EmailMessage\nfrom django.contrib.auth.decorators import login_required\nimport re\nfrom django.core.files.storage import default_storage\nfrom django.core.mail import send_mail\nimport pandas as pd\n\n\n# # Create your views here.\ndef basic(request):\n return render(request, 'basic.html')\n\n\ndef index(request):\n template = \"index.html\"\n data = Profile.objects.all()\n invalid = Invalidmail.objects.all()\n if request.method == \"GET\":\n return render(request, template)\n\n csv_file = request.FILES['file']\n\n if not csv_file.name.endswith('.csv'):\n messages.error(request, \"This is not csv file,Please try again \")\n return redirect('/index')\n\n data_set = csv_file.read().decode('UTF-8')\n io_string = io.StringIO(data_set)\n next(io_string)\n\n for column in csv.reader(io_string, delimiter=',', quotechar=\"|\"):\n\n regex = \"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n if (re.search(regex, column[0])):\n _, created = Profile.objects.update_or_create(email=column[0])\n\n else:\n _, created = Invalidmail.objects.update_or_create(email=column[0])\n\n context = {}\n messages.success(request, 'Your Record Has Been Uploaded and Updated')\n return render(request, 'index.html', context)\n\n\ndef about(request):\n return render(request, 'about.html')\n\n\ndef emailslist(request):\n data = Invalidmail.objects.all()\n prompt = {'profiles': data}\n\n return render(request, 'emails.html', prompt)\n\n\ndef sendmail(request):\n template = \"contact.html\"\n\n if request.method == \"POST\" and request.FILES['file'] and request.FILES['csv_files']:\n subject = request.POST.get('subject', '')\n message = request.POST.get('message', '')\n from_email = settings.EMAIL_HOST_USER\n csv = request.FILES['csv_files']\n csv_file_name = default_storage.save(csv.name, csv)\n\n csv_file = default_storage.open(csv_file_name)\n csv_file_url = default_storage.url(csv_file_name)\n print(csv_file_url)\n file = request.FILES['file']\n file_name = default_storage.save(file.name, file)\n connection = mail.get_connection()\n connection.open()\n\n df_file = pd.read_csv(csv_file)\n # print(df_file)\n\n df = pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n\n email = mail.EmailMessage(subject, message, from_email, bcc=list, connection=connection)\n\n file = default_storage.open(file_name)\n file_url = default_storage.url(file_name)\n email.attach(file_url, file.read())\n connection.send_messages([email])\n\n messages.success(request, \"Email sent Successfully\")\n\n connection.close()\n\n return render(request, 'contact.html')\n\n\ndef valid(request):\n data = Profile.objects.all()\n prompt = {'profiles': data}\n\n return render(request, 'validate.html', prompt)\n\n\ndef mailing(request):\n fields = ['Email']\n # df_file= pd.read_csv(\"/Users/ashishkumar/Desktop/email.csv\",skipinitialspace=True, usecols=fields)\n df_file = pd.read_csv(\"/Users/ashishkumar/Desktop/email.csv\")\n df = pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n\n context = {'df': df_file.to_html,\n\n 'list': list,\n\n }\n return render(request, 'mailing.html', context)\n\n\ndef dashboard(request, pk_test):\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n customerss = Customer.objects.get(id=pk_test)\n\n context = {'campaign': campaign, 'email': email, 'customer': customer, 'customerss': customerss}\n\n return render(request, 'dashboard.html', context)\n\n\ndef profile(request, pk_test):\n users = User.objects.all()\n customer = Customer.objects.all()\n campaign = Campaign.objects.filter(my_customer=pk_test)\n current_user = request.user.id\n email = Email.objects.filter(my_customer=pk_test)\n\n context = {'campaign': campaign, 'email': email, 'customer': customer, 'current_user': current_user, 'users': users}\n\n return render(request, 'profile.html', context)\n\n\ndef customer(request):\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n current_user = request.user\n\n context = {'campaign': campaign, 'email': email, 'customer': customer, 'current_user': current_user}\n\n return render(request, 'customerhome.html', context)\n\n\ndef campaign(request):\n current_user = request.user.id\n print(current_user)\n customer = Customer.objects.get(id=current_user)\n\n emails = Email.objects.filter(my_customer=current_user)\n file_names = \"\"\n\n if request.method == 'POST':\n name = request.POST.get('name', '')\n sender_name = request.POST.get('sender_name', '')\n sender_email = request.POST.get('sender_email', '')\n email_subject = request.POST.get('email_subject', '')\n mails = request.POST.get('mail')\n mailings = Email.objects.get(id=mails)\n for f in Email.objects.filter(id=mails):\n file_names = f.upload_file\n contact = Campaign(my_customer=customer, name=name, sender_name=sender_name, sender_email=sender_email,\n email_subject=email_subject, camp_emails=mailings)\n contact.save()\n form = CampaignForm(request.POST)\n print(request.POST)\n\n if form.is_valid():\n form.save()\n print(\"working\")\n #return redirect('/customer')\n\n return redirect('/sendmail')\n\n print(\"working\")\n #return redirect('/customer')\n return redirect('/sendmail')\n\n\n else:\n fm = CampaignForm()\n print(\"form is not valid\")\n\n context = {'form': fm, 'emails': emails}\n return render(request, 'addcampaign.html', context)\n\n\ndef email(request):\n form = EmailForm()\n current_user = request.user.id\n print(current_user)\n customer = Customer.objects.get(id=current_user)\n if request.method == 'POST':\n name = request.POST.get('name', '')\n upload_file = request.FILES['upload_file']\n\n contact = Email(my_customer=customer, name=name, upload_file=upload_file)\n contact.save()\n return redirect('/customer')\n\n context = {'form': form}\n\n return render(request, 'addemail.html', context)\n\n\ndef handleSign(request):\n form = CreateUserForm()\n if request.method == 'POST':\n job = request.POST['job']\n print(job)\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user = form.save()\n if job == \"Customer\":\n group = Group.objects.get(name='Customer')\n user.groups.add(group)\n Customer.objects.create(\n user=user,\n name=user.username,\n )\n\n user = form.cleaned_data.get('username')\n messages.success(request, 'Account was created for ' + user)\n return redirect('/')\n else:\n print(\"wrong credentials\")\n context = {'form': form}\n return render(request, 'signup.html', context)\n\n\ndef handleLog(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n\n group = None\n if request.user.groups.exists():\n group = request.user.groups.all()[0].name\n if group == 'Customer':\n return redirect('Customer')\n else:\n messages.info(request, 'Username OR password is incorrect')\n\n context = {}\n return render(request, 'login.html', context)\n\n\ndef updatecamp(request):\n current_user = request.user\n form = CampUpdateForm()\n pi = Customer.objects.get(pk=current_user.id)\n fm = CampUpdateForm(instance=pi)\n print(fm)\n\n if request.method == 'POST':\n\n print(request.POST)\n fm = CampUpdateForm(request.POST, instance=pi)\n fm.save()\n\n print(\"working\")\n return redirect('/customer')\n\n else:\n fm = CampUpdateForm(instance=pi)\n return render(request, 'updatecamp.html', {'form': fm})\n\n context = {'current_user ': current_user, 'fm': fm, 'form': form}\n return render(request, 'updatecamp.html', context)\n\n\ndef updateemail(request):\n # form=CustomerForm()\n current_user = request.user\n\n pi = Customer.objects.get(pk=current_user.id)\n fm = EmailUpdateForm(instance=pi)\n\n if request.method == 'POST':\n print(request.POST)\n fm = EmailUpdateForm(request.POST, instance=pi)\n fm.save()\n\n # contact= Customer(user=current_user)\n # contact.save()\n\n print(\"working\")\n return redirect('/customer')\n\n context = {'current_user ': current_user, 'form': fm}\n return render(request, 'updateemail.html', context)\n\n\ndef sendmail(request):\n current_user = request.user\n users = User.objects.all()\n customer = Customer.objects.all()\n campaign = Campaign.objects.all()\n email = Email.objects.all()\n campaigns = Campaign.objects.filter(my_customer=current_user.id)\n campmaildata = Campaign.objects.filter(camp_emails=current_user.id)\n emails = Email.objects.filter(my_customer=current_user.id)\n print(campmaildata)\n\n pi = Customer.objects.get(pk=current_user.id)\n\n if request.method == \"POST\" and request.FILES['file']:\n\n job = request.POST.get('job')\n message = request.POST.get('message')\n subject = \"\"\n file_names = \"\"\n getid = \"\"\n\n for e in Campaign.objects.filter(id=job):\n subject = e.email_subject\n getid=e.camp_emails.id\n\n print(getid)\n\n for f in Email.objects.filter(id=getid):\n file_names=f.upload_file\n\n\n from_email = settings.EMAIL_HOST_USER\n file = request.FILES['file']\n file_name = default_storage.save(file.name, file)\n df_file = pd.read_csv(file_names)\n # print(df_file)\n connection = mail.get_connection()\n connection.open()\n\n df = pd.DataFrame(df_file)\n\n list = df['Email'].tolist()\n\n email = mail.EmailMessage(subject, message, from_email, bcc=list, connection=connection)\n\n file = default_storage.open(file_name)\n file_url = default_storage.url(file_name)\n email.attach(file_url, file.read())\n connection.send_messages([email])\n\n messages.success(request, \"Email sent Successfully\")\n\n\n connection.close()\n return redirect('/customer')\n\n\n context = {'campaign': campaign, 'email': email, 'customer': customer, 'current_user': current_user,\n 'campaigns': campaigns, 'emails': emails, }\n return render(request, 'sendmail.html', context)\n\n\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
semskurto/YOLOX
|
[
"1196be5ad7f25f013e512d2bfe4a743031321896"
] |
[
"yolox/exp/yolox_base.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.\n\nimport os\nimport random\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\n\nfrom .base_exp import BaseExp\n\n\nclass Exp(BaseExp):\n\n def __init__(self):\n super().__init__()\n\n # ---------------- model config ---------------- #\n self.num_classes = 80\n self.depth = 1.00\n self.width = 1.00\n\n # ---------------- dataloader config ---------------- #\n # set worker to 4 for shorter dataloader init time\n self.data_num_workers = 4\n self.input_size = (640, 640)\n self.random_size = (14, 26)\n self.data_dir = None\n self.train_ann = \"instances_train2017.json\"\n self.val_ann = \"instances_val2017.json\"\n\n # --------------- transform config ----------------- #\n self.degrees = 10.0\n self.translate = 0.1\n self.scale = (0.1, 2)\n self.mscale = (0.8, 1.6)\n self.shear = 2.0\n self.perspective = 0.0\n self.enable_mixup = True\n\n # -------------- training config --------------------- #\n self.warmup_epochs = 5\n self.max_epoch = 300\n self.warmup_lr = 0\n self.basic_lr_per_img = 0.01 / 64.0\n self.scheduler = \"yoloxwarmcos\"\n self.no_aug_epochs = 15\n self.min_lr_ratio = 0.05\n self.ema = True\n\n self.weight_decay = 5e-4\n self.momentum = 0.9\n self.print_interval = 10\n self.eval_interval = 10\n self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n\n # ----------------- testing config ------------------ #\n self.test_size = (640, 640)\n self.test_conf = 0.01\n self.nmsthre = 0.65\n\n def get_model(self):\n from YOLOX.yolox.models import YOLOX, YOLOPAFPN, YOLOXHead\n\n def init_yolo(M):\n for m in M.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eps = 1e-3\n m.momentum = 0.03\n\n if getattr(self, \"model\", None) is None:\n in_channels = [256, 512, 1024]\n backbone = YOLOPAFPN(self.depth, self.width, in_channels=in_channels)\n head = YOLOXHead(self.num_classes, self.width, in_channels=in_channels)\n self.model = YOLOX(backbone, head)\n\n self.model.apply(init_yolo)\n self.model.head.initialize_biases(1e-2)\n return self.model\n\n def get_data_loader(self, batch_size, is_distributed, no_aug=False):\n from yolox.data import (\n COCODataset,\n TrainTransform,\n YoloBatchSampler,\n DataLoader,\n InfiniteSampler,\n MosaicDetection,\n )\n\n dataset = COCODataset(\n data_dir=self.data_dir,\n json_file=self.train_ann,\n img_size=self.input_size,\n preproc=TrainTransform(\n rgb_means=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225),\n max_labels=50,\n ),\n )\n\n dataset = MosaicDetection(\n dataset,\n mosaic=not no_aug,\n img_size=self.input_size,\n preproc=TrainTransform(\n rgb_means=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225),\n max_labels=120,\n ),\n degrees=self.degrees,\n translate=self.translate,\n scale=self.scale,\n shear=self.shear,\n perspective=self.perspective,\n enable_mixup=self.enable_mixup,\n )\n\n self.dataset = dataset\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n\n sampler = InfiniteSampler(\n len(self.dataset), seed=self.seed if self.seed else 0\n )\n\n batch_sampler = YoloBatchSampler(\n sampler=sampler,\n batch_size=batch_size,\n drop_last=False,\n input_dimension=self.input_size,\n mosaic=not no_aug,\n )\n\n dataloader_kwargs = {\"num_workers\": self.data_num_workers, \"pin_memory\": True}\n dataloader_kwargs[\"batch_sampler\"] = batch_sampler\n train_loader = DataLoader(self.dataset, **dataloader_kwargs)\n\n return train_loader\n\n def random_resize(self, data_loader, epoch, rank, is_distributed):\n tensor = torch.LongTensor(2).cuda()\n\n if rank == 0:\n size_factor = self.input_size[1] * 1. / self.input_size[0]\n size = random.randint(*self.random_size)\n size = (int(32 * size), 32 * int(size * size_factor))\n tensor[0] = size[0]\n tensor[1] = size[1]\n\n if is_distributed:\n dist.barrier()\n dist.broadcast(tensor, 0)\n\n input_size = data_loader.change_input_dim(\n multiple=(tensor[0].item(), tensor[1].item()), random_range=None\n )\n return input_size\n\n def get_optimizer(self, batch_size):\n if \"optimizer\" not in self.__dict__:\n if self.warmup_epochs > 0:\n lr = self.warmup_lr\n else:\n lr = self.basic_lr_per_img * batch_size\n\n pg0, pg1, pg2 = [], [], [] # optimizer parameter groups\n\n for k, v in self.model.named_modules():\n if hasattr(v, \"bias\") and isinstance(v.bias, nn.Parameter):\n pg2.append(v.bias) # biases\n if isinstance(v, nn.BatchNorm2d) or \"bn\" in k:\n pg0.append(v.weight) # no decay\n elif hasattr(v, \"weight\") and isinstance(v.weight, nn.Parameter):\n pg1.append(v.weight) # apply decay\n\n optimizer = torch.optim.SGD(\n pg0, lr=lr, momentum=self.momentum, nesterov=True\n )\n optimizer.add_param_group(\n {\"params\": pg1, \"weight_decay\": self.weight_decay}\n ) # add pg1 with weight_decay\n optimizer.add_param_group({\"params\": pg2})\n self.optimizer = optimizer\n\n return self.optimizer\n\n def get_lr_scheduler(self, lr, iters_per_epoch):\n from yolox.utils import LRScheduler\n scheduler = LRScheduler(\n self.scheduler,\n lr,\n iters_per_epoch,\n self.max_epoch,\n warmup_epochs=self.warmup_epochs,\n warmup_lr_start=self.warmup_lr,\n no_aug_epochs=self.no_aug_epochs,\n min_lr_ratio=self.min_lr_ratio,\n )\n return scheduler\n\n def get_eval_loader(self, batch_size, is_distributed, testdev=False):\n from yolox.data import COCODataset, ValTransform\n\n valdataset = COCODataset(\n data_dir=self.data_dir,\n json_file=self.val_ann if not testdev else \"image_info_test-dev2017.json\",\n name=\"val2017\" if not testdev else \"test2017\",\n img_size=self.test_size,\n preproc=ValTransform(\n rgb_means=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)\n ),\n )\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n sampler = torch.utils.data.distributed.DistributedSampler(\n valdataset, shuffle=False\n )\n else:\n sampler = torch.utils.data.SequentialSampler(valdataset)\n\n dataloader_kwargs = {\n \"num_workers\": self.data_num_workers,\n \"pin_memory\": True,\n \"sampler\": sampler,\n }\n dataloader_kwargs[\"batch_size\"] = batch_size\n val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)\n\n return val_loader\n\n def get_evaluator(self, batch_size, is_distributed, testdev=False):\n from yolox.evaluators import COCOEvaluator\n\n val_loader = self.get_eval_loader(batch_size, is_distributed, testdev=testdev)\n evaluator = COCOEvaluator(\n dataloader=val_loader,\n img_size=self.test_size,\n confthre=self.test_conf,\n nmsthre=self.nmsthre,\n num_classes=self.num_classes,\n testdev=testdev,\n )\n return evaluator\n\n def eval(self, model, evaluator, is_distributed, half=False):\n return evaluator.evaluate(model, is_distributed, half)\n"
] |
[
[
"torch.distributed.broadcast",
"torch.LongTensor",
"torch.utils.data.distributed.DistributedSampler",
"torch.utils.data.SequentialSampler",
"torch.utils.data.DataLoader",
"torch.distributed.barrier",
"torch.optim.SGD",
"torch.distributed.get_world_size"
]
] |
cyberlabsai/watchdog-middleware
|
[
"d66805e7b5155cf6ca7b228d10dc80632ab6aa0d"
] |
[
"model.py"
] |
[
"import math\nimport numpy as np\nimport tensorflow as tf\nfrom enum import Enum, unique\n\n\n@unique\nclass InputType(Enum):\n TENSOR = 1\n BASE64_JPEG = 2\n\n\nclass OpenNsfwModel:\n \"\"\"Tensorflow implementation of Yahoo's Open NSFW Model\n\n Original implementation:\n https://github.com/yahoo/open_nsfw\n\n Weights have been converted using caffe-tensorflow:\n https://github.com/ethereon/caffe-tensorflow\n \"\"\"\n\n def __init__(self):\n self.weights = {}\n self.bn_epsilon = 1e-5 # Default used by Caffe\n\n def build(self, weights_path=\"nsfw_weights/open_nsfw-weights.npy\",\n input_type=InputType.TENSOR):\n\n self.weights = np.load(weights_path, encoding=\"latin1\").item()\n self.input_tensor = None\n\n if input_type == InputType.TENSOR:\n self.input = tf.placeholder(tf.float32,\n shape=[None, 224, 224, 3],\n name=\"input\")\n self.input_tensor = self.input\n elif input_type == InputType.BASE64_JPEG:\n from image_utils import load_base64_tensor\n\n self.input = tf.placeholder(tf.string, shape=(None,), name=\"input\")\n self.input_tensor = load_base64_tensor(self.input)\n else:\n raise ValueError(\"invalid input type '{}'\".format(input_type))\n\n x = self.input_tensor\n\n x = tf.pad(x, [[0, 0], [3, 3], [3, 3], [0, 0]], 'CONSTANT')\n x = self.__conv2d(\"conv_1\", x, filter_depth=64,\n kernel_size=7, stride=2, padding='valid')\n\n x = self.__batch_norm(\"bn_1\", x)\n x = tf.nn.relu(x)\n\n x = tf.layers.max_pooling2d(x, pool_size=3, strides=2, padding='same')\n\n x = self.__conv_block(stage=0, block=0, inputs=x,\n filter_depths=[32, 32, 128],\n kernel_size=3, stride=1)\n\n x = self.__identity_block(stage=0, block=1, inputs=x,\n filter_depths=[32, 32, 128], kernel_size=3)\n x = self.__identity_block(stage=0, block=2, inputs=x,\n filter_depths=[32, 32, 128], kernel_size=3)\n\n x = self.__conv_block(stage=1, block=0, inputs=x,\n filter_depths=[64, 64, 256],\n kernel_size=3, stride=2)\n x = self.__identity_block(stage=1, block=1, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n x = self.__identity_block(stage=1, block=2, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n x = self.__identity_block(stage=1, block=3, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n\n x = self.__conv_block(stage=2, block=0, inputs=x,\n filter_depths=[128, 128, 512],\n kernel_size=3, stride=2)\n x = self.__identity_block(stage=2, block=1, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=2, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=3, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=4, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=5, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n\n x = self.__conv_block(stage=3, block=0, inputs=x,\n filter_depths=[256, 256, 1024], kernel_size=3,\n stride=2)\n x = self.__identity_block(stage=3, block=1, inputs=x,\n filter_depths=[256, 256, 1024],\n kernel_size=3)\n x = self.__identity_block(stage=3, block=2, inputs=x,\n filter_depths=[256, 256, 1024],\n kernel_size=3)\n\n x = tf.layers.average_pooling2d(x, pool_size=7, strides=1,\n padding=\"valid\", name=\"pool\")\n\n x = tf.reshape(x, shape=(-1, 1024))\n\n self.logits = self.__fully_connected(name=\"fc_nsfw\",\n inputs=x, num_outputs=2)\n self.predictions = tf.nn.softmax(self.logits, name=\"predictions\")\n\n \"\"\"Get weights for layer with given name\n \"\"\"\n def __get_weights(self, layer_name, field_name):\n if not layer_name in self.weights:\n raise ValueError(\"No weights for layer named '{}' found\"\n .format(layer_name))\n\n w = self.weights[layer_name]\n if not field_name in w:\n raise (ValueError(\"No entry for field '{}' in layer named '{}'\"\n .format(field_name, layer_name)))\n\n return w[field_name]\n\n \"\"\"Layer creation and weight initialization\n \"\"\"\n def __fully_connected(self, name, inputs, num_outputs):\n return tf.layers.dense(\n inputs=inputs, units=num_outputs, name=name,\n kernel_initializer=tf.constant_initializer(\n self.__get_weights(name, \"weights\"), dtype=tf.float32),\n bias_initializer=tf.constant_initializer(\n self.__get_weights(name, \"biases\"), dtype=tf.float32))\n\n def __conv2d(self, name, inputs, filter_depth, kernel_size, stride=1,\n padding=\"same\", trainable=False):\n\n if padding.lower() == 'same' and kernel_size > 1:\n if kernel_size > 1:\n oh = inputs.get_shape().as_list()[1]\n h = inputs.get_shape().as_list()[1]\n\n p = int(math.floor(((oh - 1) * stride + kernel_size - h)//2))\n\n inputs = tf.pad(inputs,\n [[0, 0], [p, p], [p, p], [0, 0]],\n 'CONSTANT')\n else:\n raise Exception('unsupported kernel size for padding: \"{}\"'\n .format(kernel_size))\n\n return tf.layers.conv2d(\n inputs, filter_depth,\n kernel_size=(kernel_size, kernel_size),\n strides=(stride, stride), padding='valid',\n activation=None, trainable=trainable, name=name,\n kernel_initializer=tf.constant_initializer(\n self.__get_weights(name, \"weights\"), dtype=tf.float32),\n bias_initializer=tf.constant_initializer(\n self.__get_weights(name, \"biases\"), dtype=tf.float32))\n\n def __batch_norm(self, name, inputs, training=False):\n return tf.layers.batch_normalization(\n inputs, training=training, epsilon=self.bn_epsilon,\n gamma_initializer=tf.constant_initializer(\n self.__get_weights(name, \"scale\"), dtype=tf.float32),\n beta_initializer=tf.constant_initializer(\n self.__get_weights(name, \"offset\"), dtype=tf.float32),\n moving_mean_initializer=tf.constant_initializer(\n self.__get_weights(name, \"mean\"), dtype=tf.float32),\n moving_variance_initializer=tf.constant_initializer(\n self.__get_weights(name, \"variance\"), dtype=tf.float32),\n name=name)\n\n \"\"\"ResNet blocks\n \"\"\"\n def __conv_block(self, stage, block, inputs, filter_depths,\n kernel_size=3, stride=2):\n filter_depth1, filter_depth2, filter_depth3 = filter_depths\n\n conv_name_base = \"conv_stage{}_block{}_branch\".format(stage, block)\n bn_name_base = \"bn_stage{}_block{}_branch\".format(stage, block)\n shortcut_name_post = \"_stage{}_block{}_proj_shortcut\" \\\n .format(stage, block)\n\n shortcut = self.__conv2d(\n name=\"conv{}\".format(shortcut_name_post), stride=stride,\n inputs=inputs, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\"\n )\n\n shortcut = self.__batch_norm(\"bn{}\".format(shortcut_name_post),\n shortcut)\n\n x = self.__conv2d(\n name=\"{}2a\".format(conv_name_base),\n inputs=inputs, filter_depth=filter_depth1, kernel_size=1,\n stride=stride, padding=\"same\",\n )\n x = self.__batch_norm(\"{}2a\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2b\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2b\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2c\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2c\".format(bn_name_base), x)\n\n x = tf.add(x, shortcut)\n\n return tf.nn.relu(x)\n\n def __identity_block(self, stage, block, inputs,\n filter_depths, kernel_size):\n filter_depth1, filter_depth2, filter_depth3 = filter_depths\n conv_name_base = \"conv_stage{}_block{}_branch\".format(stage, block)\n bn_name_base = \"bn_stage{}_block{}_branch\".format(stage, block)\n\n x = self.__conv2d(\n name=\"{}2a\".format(conv_name_base),\n inputs=inputs, filter_depth=filter_depth1, kernel_size=1,\n stride=1, padding=\"same\",\n )\n\n x = self.__batch_norm(\"{}2a\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2b\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2b\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2c\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2c\".format(bn_name_base), x)\n\n x = tf.add(x, inputs)\n\n return tf.nn.relu(x)\n"
] |
[
[
"tensorflow.nn.relu",
"tensorflow.nn.softmax",
"tensorflow.reshape",
"tensorflow.layers.max_pooling2d",
"tensorflow.placeholder",
"tensorflow.add",
"tensorflow.pad",
"tensorflow.layers.average_pooling2d",
"numpy.load"
]
] |
bluesea0/pytorch-tutorial
|
[
"74dffb57fd8fc7e4298e83f9e0762d88d1e5768e"
] |
[
"tutorials/02-intermediate/deep_residual_network/main.py"
] |
[
"# ---------------------------------------------------------------------------- #\n# An implementation of https://arxiv.org/pdf/1512.03385.pdf #\n# See section 4.2 for the model architecture on CIFAR-10 #\n# Some part of the code was referenced from below #\n# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py #\n# ---------------------------------------------------------------------------- #\n\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\n\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Hyper-parameters\nnum_epochs = 80\nbatch_size = 100\nlearning_rate = 0.001\n\n# Image preprocessing modules\ntransform = transforms.Compose([\n transforms.Pad(4),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32),\n transforms.ToTensor()])\n\n# CIFAR-10 dataset\ntrain_dataset = torchvision.datasets.CIFAR10(root='../../data/',\n train=True, \n transform=transform,\n download=False)\n\ntest_dataset = torchvision.datasets.CIFAR10(root='../../data/',\n train=False, \n transform=transforms.ToTensor())\n\n# Data loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\n# 3x3 convolution\ndef conv3x3(in_channels, out_channels, stride=1):\n return nn.Conv2d(in_channels, out_channels, kernel_size=3, \n stride=stride, padding=1, bias=False)\n\n# Residual block\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n super(ResidualBlock, self).__init__()\n self.conv1 = conv3x3(in_channels, out_channels, stride)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(out_channels, out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.downsample = downsample\n \n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample:\n residual = self.downsample(x)\n out += residual#这样就保留了之前的输出和现在的结合了。\n out = self.relu(out)\n return out\n\n# ResNet\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes=10):\n super(ResNet, self).__init__()\n self.in_channels = 16\n self.conv = conv3x3(3, 16)\n self.bn = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self.make_layer(block, 16, layers[0])\n self.layer2 = self.make_layer(block, 32, layers[1], 2)\n self.layer3 = self.make_layer(block, 64, layers[2], 2)\n self.avg_pool = nn.AvgPool2d(8)\n self.fc = nn.Linear(64, num_classes)\n \n def make_layer(self, block, out_channels, blocks, stride=1):#好复杂啊\n downsample = None\n if (stride != 1) or (self.in_channels != out_channels):\n downsample = nn.Sequential(\n conv3x3(self.in_channels, out_channels, stride=stride),\n nn.BatchNorm2d(out_channels))\n layers = []\n layers.append(block(self.in_channels, out_channels, stride, downsample))\n self.in_channels = out_channels\n for i in range(1, blocks):\n layers.append(block(out_channels, out_channels))\n return nn.Sequential(*layers)\n \n def forward(self, x):\n out = self.conv(x)\n out = self.bn(out)\n out = self.relu(out)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.avg_pool(out)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n return out\n \nmodel = ResNet(ResidualBlock, [2, 2, 2]).to(device)\n\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n# For updating learning rate\ndef update_lr(optimizer, lr): \n for param_group in optimizer.param_groups:\n #相应的optimizer.state_dict()是函数,而这里是属性,不是函数调用。\n #因为lr是在param_groups里的。\n param_group['lr'] = lr\n\n# Train the model\ntotal_step = len(train_loader)\ncurr_lr = learning_rate\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 100 == 0:\n print (\"Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}\"\n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n\n # Decay learning rate\n if (epoch+1) % 20 == 0:\n curr_lr /= 3#对学习率衰减\n update_lr(optimizer, curr_lr)#更新\n\n# Test the model\nmodel.eval()\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))\n\n# Save the model checkpoint\ntorch.save(model.state_dict(), 'resnet.ckpt')\n#因为我应该以后也用不到这个,所以没有特别认真地看。"
] |
[
[
"torch.nn.Sequential",
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.nn.Conv2d",
"torch.utils.data.DataLoader",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
PirateX0/MAMS-for-ABSA
|
[
"cddcdb0f423b3fdb2c76b70744737abed3a00d17"
] |
[
"src/module/attention/attention.py"
] |
[
"from torch import nn\nimport torch.nn.functional as F\nfrom src.module.utils import constants\n\nclass Attention(nn.Module):\n \"\"\"\n The base class of attention.\n \"\"\"\n\n def __init__(self, dropout):\n super(Attention, self).__init__()\n self.dropout = dropout\n\n def forward(self, query, key, value, mask=None):\n \"\"\"\n query: FloatTensor (batch_size, query_size) or FloatTensor (batch_size, num_queries, query_size)\n key: FloatTensor (batch_size, time_step, key_size)\n value: FloatTensor (batch_size, time_step, hidden_size)\n mask: ByteTensor (batch_size, time_step) or ByteTensor (batch_size, num_queries, time_step)\n \"\"\"\n single_query = False\n if len(query.size()) == 2:\n query = query.unsqueeze(1)\n single_query = True\n if mask is not None:\n if len(mask.size()) == 2:\n mask = mask.unsqueeze(1)\n else:\n assert mask.size(1) == query.size(1)\n score = self._score(query, key) # FloatTensor (batch_size, num_queries, time_step)\n weights = self._weights_normalize(score, mask)\n weights = F.dropout(weights, p=self.dropout, training=self.training)\n output = weights.matmul(value)\n if single_query:\n output = output.squeeze(1)\n return output\n\n def _score(self, query, key):\n raise NotImplementedError('Attention score method is not implemented.')\n\n def _weights_normalize(self, score, mask):\n if not mask is None:\n score = score.masked_fill(mask == 0, -constants.INF)\n weights = F.softmax(score, dim=-1)\n return weights\n\n def get_attention_weights(self, query, key, mask=None):\n single_query = False\n if len(query.size()) == 2:\n query = query.unsqueeze(1)\n single_query = True\n if mask is not None:\n if len(mask.size()) == 2:\n mask = mask.unsqueeze(1)\n else:\n assert mask.size(1) == query.size(1)\n score = self._score(query, key) # FloatTensor (batch_size, num_queries, time_step)\n weights = self._weights_normalize(score, mask)\n weights = F.dropout(weights, p=self.dropout, training=self.training)\n if single_query:\n weights = weights.squeeze(1)\n return weights"
] |
[
[
"torch.nn.functional.softmax",
"torch.nn.functional.dropout"
]
] |
ewanlee/Learning-to-Group
|
[
"a32f00cd4c7244c5d5c32dfa68bfdac8eb71a4ae"
] |
[
"code/GDL/knn.py"
] |
[
"# k-nearest neighbors algorithm\n# input : set of samples X\n# output : the array of length k\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n\ndef knn(k, X):\n neigh = NearestNeighbors(k + 1, metric='euclidean', n_jobs=-1).fit(X)\n kneighbors = neigh.kneighbors(\n X,\n k + 1,\n )\n distance = np.array(kneighbors[0][:, 1:])\n indices = np.array(kneighbors[1][:, 1:])\n return distance, indices\n"
] |
[
[
"numpy.array",
"sklearn.neighbors.NearestNeighbors"
]
] |
njwardhan/colour
|
[
"fedf769764b46cd0b4484cde7e4f59a09b37515c"
] |
[
"colour/colorimetry/illuminants.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nIlluminants\n===========\n\nDefines *CIE* illuminants computation related objects:\n\n- :func:`colour.sd_CIE_standard_illuminant_A`\n- :func:`colour.sd_CIE_illuminant_D_series`\n- :func:`colour.daylight_locus_function`\n\nReferences\n----------\n- :cite:`CIETC1-482004` : CIE TC 1-48. (2004). EXPLANATORY COMMENTS - 5. In\n CIE 015:2004 Colorimetry, 3rd Edition (pp. 68-68). ISBN:978-3-901906-33-6\n- :cite:`CIETC1-482004n` : CIE TC 1-48. (2004). 3.1 Recommendations\n concerning standard physical data of illuminants. In CIE 015:2004\n Colorimetry, 3rd Edition (pp. 12-13). ISBN:978-3-901906-33-6\n- :cite:`Wyszecki2000a` : Wyszecki, Günther, & Stiles, W. S. (2000).\n Equation I(1.2.1). In Color Science: Concepts and Methods, Quantitative\n Data and Formulae (p. 8). Wiley. ISBN:978-0-471-39918-6\n- :cite:`Wyszecki2000z` : Wyszecki, Günther, & Stiles, W. S. (2000). CIE\n Method of Calculating D-Illuminants. In Color Science: Concepts and\n Methods, Quantitative Data and Formulae (pp. 145-146). Wiley.\n ISBN:978-0-471-39918-6\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.algebra import LinearInterpolator\nfrom colour.colorimetry import (SPECTRAL_SHAPE_DEFAULT,\n SDS_ILLUMINANTS_D_SERIES, SpectralDistribution)\nfrom colour.utilities import as_float_array, as_numeric, tsplit\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n 'sd_CIE_standard_illuminant_A', 'sd_CIE_illuminant_D_series',\n 'daylight_locus_function'\n]\n\n\ndef sd_CIE_standard_illuminant_A(shape=SPECTRAL_SHAPE_DEFAULT):\n \"\"\"\n *CIE Standard Illuminant A* is intended to represent typical, domestic,\n tungsten-filament lighting.\n\n Its spectral distribution is that of a Planckian radiator at a temperature\n of approximately 2856 K. *CIE Standard Illuminant A* should be used in all\n applications of colorimetry involving the use of incandescent lighting,\n unless there are specific reasons for using a different illuminant.\n\n Parameters\n ----------\n shape : SpectralShape, optional\n Spectral shape used to create the spectral distribution of the\n *CIE Standard Illuminant A*.\n\n Returns\n -------\n SpectralDistribution\n *CIE Standard Illuminant A*. spectral distribution.\n\n References\n ----------\n :cite:`CIETC1-482004n`\n\n Examples\n --------\n >>> from colour import SpectralShape\n >>> sd_CIE_standard_illuminant_A(SpectralShape(400, 700, 10))\n ... # doctest: +ELLIPSIS\n SpectralDistribution([[ 400. , 14.7080384...],\n [ 410. , 17.6752521...],\n [ 420. , 20.9949572...],\n [ 430. , 24.6709226...],\n [ 440. , 28.7027304...],\n [ 450. , 33.0858929...],\n [ 460. , 37.8120566...],\n [ 470. , 42.8692762...],\n [ 480. , 48.2423431...],\n [ 490. , 53.9131532...],\n [ 500. , 59.8610989...],\n [ 510. , 66.0634727...],\n [ 520. , 72.4958719...],\n [ 530. , 79.1325945...],\n [ 540. , 85.9470183...],\n [ 550. , 92.9119589...],\n [ 560. , 100. ...],\n [ 570. , 107.1837952...],\n [ 580. , 114.4363383...],\n [ 590. , 121.7312009...],\n [ 600. , 129.0427389...],\n [ 610. , 136.3462674...],\n [ 620. , 143.6182057...],\n [ 630. , 150.8361944...],\n [ 640. , 157.9791857...],\n [ 650. , 165.0275098...],\n [ 660. , 171.9629200...],\n [ 670. , 178.7686175...],\n [ 680. , 185.4292591...],\n [ 690. , 191.9309499...],\n [ 700. , 198.2612232...]],\n interpolator=SpragueInterpolator,\n interpolator_kwargs={},\n extrapolator=Extrapolator,\n extrapolator_kwargs={...})\n \"\"\"\n\n wavelengths = shape.range()\n values = (100 * (560 / wavelengths) ** 5 * (((np.exp(\n (1.435 * 10 ** 7) / (2848 * 560)) - 1) / (np.exp(\n (1.435 * 10 ** 7) / (2848 * wavelengths)) - 1))))\n\n return SpectralDistribution(\n values, wavelengths, name='CIE Standard Illuminant A')\n\n\ndef sd_CIE_illuminant_D_series(xy, M1_M2_rounding=True):\n \"\"\"\n Returns the spectral distribution of given *CIE Illuminant D Series* using\n given *CIE xy* chromaticity coordinates.\n\n Parameters\n ----------\n xy : array_like\n *CIE xy* chromaticity coordinates.\n M1_M2_rounding : bool, optional\n Whether to round :math:`M1` and :math:`M2` variables to 3 decimal\n places in order to yield the internationally agreed values.\n\n Returns\n -------\n SpectralDistribution\n *CIE Illuminant D Series* spectral\n distribution.\n\n Notes\n -----\n - The nominal *CIE xy* chromaticity coordinates which have been computed\n with :func:`colour.temperature.CCT_to_xy_CIE_D` must be given according\n to *CIE 015:2004* recommendation and thus multiplied by\n 1.4388 / 1.4380.\n - :math:`M1` and :math:`M2` variables are rounded to 3 decimal places\n according to *CIE 015:2004* recommendation.\n\n References\n ----------\n :cite:`CIETC1-482004`, :cite:`Wyszecki2000z`\n\n Examples\n --------\n >>> from colour.utilities import numpy_print_options\n >>> from colour.temperature import CCT_to_xy_CIE_D\n >>> CCT_D65 = 6500 * 1.4388 / 1.4380\n >>> xy = CCT_to_xy_CIE_D(CCT_D65)\n >>> with numpy_print_options(suppress=True):\n ... sd_CIE_illuminant_D_series(xy) # doctest: +ELLIPSIS\n SpectralDistribution([[ 300. , 0.0341...],\n [ 305. , 1.6643...],\n [ 310. , 3.2945...],\n [ 315. , 11.7652...],\n [ 320. , 20.236 ...],\n [ 325. , 28.6447...],\n [ 330. , 37.0535...],\n [ 335. , 38.5011...],\n [ 340. , 39.9488...],\n [ 345. , 42.4302...],\n [ 350. , 44.9117...],\n [ 355. , 45.775 ...],\n [ 360. , 46.6383...],\n [ 365. , 49.3637...],\n [ 370. , 52.0891...],\n [ 375. , 51.0323...],\n [ 380. , 49.9755...],\n [ 385. , 52.3118...],\n [ 390. , 54.6482...],\n [ 395. , 68.7015...],\n [ 400. , 82.7549...],\n [ 405. , 87.1204...],\n [ 410. , 91.486 ...],\n [ 415. , 92.4589...],\n [ 420. , 93.4318...],\n [ 425. , 90.0570...],\n [ 430. , 86.6823...],\n [ 435. , 95.7736...],\n [ 440. , 104.8649...],\n [ 445. , 110.9362...],\n [ 450. , 117.0076...],\n [ 455. , 117.4099...],\n [ 460. , 117.8122...],\n [ 465. , 116.3365...],\n [ 470. , 114.8609...],\n [ 475. , 115.3919...],\n [ 480. , 115.9229...],\n [ 485. , 112.3668...],\n [ 490. , 108.8107...],\n [ 495. , 109.0826...],\n [ 500. , 109.3545...],\n [ 505. , 108.5781...],\n [ 510. , 107.8017...],\n [ 515. , 106.2957...],\n [ 520. , 104.7898...],\n [ 525. , 106.2396...],\n [ 530. , 107.6895...],\n [ 535. , 106.0475...],\n [ 540. , 104.4055...],\n [ 545. , 104.2258...],\n [ 550. , 104.0462...],\n [ 555. , 102.0231...],\n [ 560. , 100. ...],\n [ 565. , 98.1671...],\n [ 570. , 96.3342...],\n [ 575. , 96.0611...],\n [ 580. , 95.788 ...],\n [ 585. , 92.2368...],\n [ 590. , 88.6856...],\n [ 595. , 89.3459...],\n [ 600. , 90.0062...],\n [ 605. , 89.8026...],\n [ 610. , 89.5991...],\n [ 615. , 88.6489...],\n [ 620. , 87.6987...],\n [ 625. , 85.4936...],\n [ 630. , 83.2886...],\n [ 635. , 83.4939...],\n [ 640. , 83.6992...],\n [ 645. , 81.863 ...],\n [ 650. , 80.0268...],\n [ 655. , 80.1207...],\n [ 660. , 80.2146...],\n [ 665. , 81.2462...],\n [ 670. , 82.2778...],\n [ 675. , 80.281 ...],\n [ 680. , 78.2842...],\n [ 685. , 74.0027...],\n [ 690. , 69.7213...],\n [ 695. , 70.6652...],\n [ 700. , 71.6091...],\n [ 705. , 72.9790...],\n [ 710. , 74.349 ...],\n [ 715. , 67.9765...],\n [ 720. , 61.604 ...],\n [ 725. , 65.7448...],\n [ 730. , 69.8856...],\n [ 735. , 72.4863...],\n [ 740. , 75.087 ...],\n [ 745. , 69.3398...],\n [ 750. , 63.5927...],\n [ 755. , 55.0054...],\n [ 760. , 46.4182...],\n [ 765. , 56.6118...],\n [ 770. , 66.8054...],\n [ 775. , 65.0941...],\n [ 780. , 63.3828...],\n [ 785. , 63.8434...],\n [ 790. , 64.304 ...],\n [ 795. , 61.8779...],\n [ 800. , 59.4519...],\n [ 805. , 55.7054...],\n [ 810. , 51.959 ...],\n [ 815. , 54.6998...],\n [ 820. , 57.4406...],\n [ 825. , 58.8765...],\n [ 830. , 60.3125...]],\n interpolator=LinearInterpolator,\n interpolator_kwargs={},\n extrapolator=Extrapolator,\n extrapolator_kwargs={...})\n \"\"\"\n\n x, y = tsplit(xy)\n\n M = 0.0241 + 0.2562 * x - 0.7341 * y\n M1 = (-1.3515 - 1.7703 * x + 5.9114 * y) / M\n M2 = (0.0300 - 31.4424 * x + 30.0717 * y) / M\n\n if M1_M2_rounding:\n M1 = np.around(M1, 3)\n M2 = np.around(M2, 3)\n\n S0 = SDS_ILLUMINANTS_D_SERIES['S0']\n S1 = SDS_ILLUMINANTS_D_SERIES['S1']\n S2 = SDS_ILLUMINANTS_D_SERIES['S2']\n\n distribution = S0.values + M1 * S1.values + M2 * S2.values\n\n return SpectralDistribution(\n distribution,\n S0.wavelengths,\n name='CIE xy ({0}, {1}) - CIE Illuminant D Series'.format(*xy),\n interpolator=LinearInterpolator)\n\n\ndef daylight_locus_function(x_D):\n \"\"\"\n Returns the daylight locus as *CIE xy* chromaticity coordinates.\n\n Parameters\n ----------\n x_D : numeric or array_like\n *x* chromaticity coordinates\n\n Returns\n -------\n numeric or array_like\n Daylight locus as *CIE xy* chromaticity coordinates.\n\n References\n ----------\n :cite:`Wyszecki2000a`\n\n Examples\n --------\n >>> daylight_locus_function(0.31270) # doctest: +ELLIPSIS\n 0.3291051...\n \"\"\"\n\n x_D = as_float_array(x_D)\n\n y_D = -3.000 * x_D ** 2 + 2.870 * x_D - 0.275\n\n return as_numeric(y_D)\n"
] |
[
[
"numpy.around",
"numpy.exp"
]
] |
ViKrAm-Bais/Machine-Learning-with-Python
|
[
"35dcaac6f3c60353962b69b35e185f4e09e26adf",
"35dcaac6f3c60353962b69b35e185f4e09e26adf"
] |
[
"classification/logistic_regression/logistic regression.py",
"classification/random_forest/Random_Forest.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# # logistic regression\n\n# importing modules\n\n# In[33]:\n\n\nimport numpy as np\nfrom sklearn.datasets import make_classification\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nimport seaborn as sns\n\n\n# In[34]:\n\n\nx, y = make_classification(\n n_samples=100,\n n_features=1,\n n_classes=2,\n n_clusters_per_class=1,\n flip_y=0.03,\n n_informative=1,\n n_redundant=0,\n n_repeated=0\n)\n\n\n# In[35]:\n\n\nplt.scatter(x,y,c=y,cmap=\"rainbow\")\nplt.title(\"classification using logistic regression\")\n\n\n# split the dataset\n\n# In[36]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1)\n\n\n# performing logistic regression\n\n# In[37]:\n\n\nlog_reg=LogisticRegression()\nlog_reg.fit(x_train,y_train)\nprint(\"Coefficient: \",log_reg.coef_)\nprint(\"Intercept: \",log_reg.intercept_)\n\n\n# testing the model\n\n# In[38]:\n\n\ny_pred=log_reg.predict(x_test)\nprint(\"x shape: \",x_test.shape)\nprint(\"y_pred shape: \",y_pred.shape)\nprint(\"y_test shape: \",y_test.shape)\n\n\n# results\n\n# In[68]:\n\n\nconfusion_matrix(y_test,y_pred)\n\n\n# In[ ]:\n\n\n\n\n",
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Random Forest\n\n# In[3]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_digits\ndigits=load_digits()\n\n\n# In[16]:\n\n\nprint(digits.keys())\nprint(digits.data.shape)\n\n\n# In[7]:\n\n\nplt.gray()\nfor i in range(4):\n plt.matshow(digits.images[i])\n\n\n# In[15]:\n\n\ndf=pd.DataFrame(digits.data)\ndf.head()\n\n\n# In[18]:\n\n\ndf['target']=digits.target\ndf.head()\n\n\n# In[22]:\n\n\nfrom sklearn.model_selection import train_test_split\nx=df.drop(['target'],axis='columns')\ny=df['target']\nx_train, x_test, y_train, y_test=train_test_split(x,y,test_size=0.2)\n\n\n# In[40]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nmodel=RandomForestClassifier()\nmodel.fit(x_train,y_train)\n\n\n# In[41]:\n\n\nmodel.score(x_test, y_test)\n\n\n# In[42]:\n\n\ny_predicted=model.predict(x_test)\n\n\n# In[43]:\n\n\nfrom sklearn.metrics import confusion_matrix\ncm=confusion_matrix(y_test,y_predicted)\n\n\n# In[44]:\n\n\ncm\n\n\n# In[46]:\n\n\nimport seaborn as sns\nsns.heatmap(cm,annot=True)\nplt.xlabel(\"y_test\")\nplt.ylabel(\"y_predicted\")\n\n\n# In[ ]:\n\n\n\n\n"
] |
[
[
"sklearn.datasets.make_classification",
"sklearn.linear_model.LogisticRegression",
"matplotlib.pyplot.title",
"matplotlib.pyplot.scatter",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.confusion_matrix"
],
[
"matplotlib.pyplot.gray",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.metrics.confusion_matrix",
"sklearn.datasets.load_digits",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.matshow",
"matplotlib.pyplot.ylabel"
]
] |
KennCoder7/LearnToPayAttention-tensorflow
|
[
"33e32830602ed1ca35c26918d433e9de37438af8"
] |
[
"vgg_att.py"
] |
[
"import os\r\nfrom tensorflow.keras import Input, Model, optimizers, datasets\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint\r\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, BatchNormalization, Activation, Layer\r\nfrom tensorflow.keras import utils\r\nfrom attention import Attention\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\n\r\nclass ConvBlock(Layer):\r\n def __init__(self, filters, kernel_size, padding='same', pooling=False):\r\n super(ConvBlock, self).__init__()\r\n self.__filters = filters\r\n self.__ks = kernel_size\r\n self.__padding = padding\r\n self.__pooling = pooling\r\n\r\n def __call__(self, inputs, *args, **kwargs):\r\n _x = Conv2D(self.__filters, self.__ks, padding=self.__padding)(inputs)\r\n _x = BatchNormalization()(_x)\r\n _x = Activation('relu')(_x)\r\n if self.__pooling:\r\n _x = MaxPooling2D()(_x)\r\n return _x\r\n\r\n\r\ndef main(output_path=r'D:\\pyproject\\data\\CIFAR10-tensorflow'):\r\n (x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data(r'D:\\pyproject\\data\\cifar-10-batches-py')\r\n x_train = x_train / 255.0\r\n x_test = x_test / 255.0\r\n y_train = utils.to_categorical(y_train, num_classes=10)\r\n y_test = utils.to_categorical(y_test, num_classes=10)\r\n epochs = 30\r\n batch_size = 128\r\n n_classes = 10\r\n model_path_loss = output_path + r\"\\vgg-att.h5\"\r\n save_model_loss = ModelCheckpoint(model_path_loss, monitor='val_loss', save_best_only=True, verbose=2)\r\n\r\n _inputs = Input(shape=(32, 32, 3), name='input')\r\n _layer = ConvBlock(64, 3)(_inputs)\r\n _layer = ConvBlock(128, 3)(_layer)\r\n c1 = ConvBlock(256, 3, pooling=True)(_layer)\r\n c2 = ConvBlock(512, 3, pooling=True)(c1)\r\n c3 = ConvBlock(512, 3, pooling=True)(c2)\r\n _layer = ConvBlock(512, 3, pooling=True)(c3)\r\n _layer = ConvBlock(512, 3, pooling=True)(_layer)\r\n _layer = Flatten()(_layer)\r\n _g = Dense(512, activation='relu')(_layer)\r\n _outputs = Dense(n_classes, activation='softmax')(_g)\r\n vgg = Model(_inputs, _outputs)\r\n vgg.load_weights(output_path + r\"\\vgg.h5\")\r\n\r\n att1_f, att1_map = Attention((16, 16, 256), 512, method='pc')([c1, _g])\r\n att2_f, att2_map = Attention((8, 8, 512), 512, method='pc')([c2, _g])\r\n att3_f, att3_map = Attention((4, 4, 512), 512, method='pc')([c3, _g])\r\n f_concat = tf.concat([att1_f, att2_f, att3_f], axis=1)\r\n _out = Dense(n_classes, 'softmax')(f_concat)\r\n model = Model(_inputs, _out)\r\n opt = optimizers.SGD(learning_rate=0.01, momentum=0.9)\r\n model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\r\n model.summary()\r\n model.fit(x_train, y_train,\r\n batch_size=batch_size,\r\n validation_data=(x_test, y_test),\r\n epochs=epochs,\r\n verbose=1,\r\n callbacks=[save_model_loss])\r\n\r\n\r\ndef visualization(nums=5):\r\n (x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data(r'D:\\pyproject\\data\\cifar-10-batches-py')\r\n x_test = x_test / 255.0\r\n n_classes = 10\r\n\r\n _inputs = Input(shape=(32, 32, 3), name='input')\r\n _layer = ConvBlock(64, 3)(_inputs)\r\n _layer = ConvBlock(128, 3)(_layer)\r\n c1 = ConvBlock(256, 3, pooling=True)(_layer)\r\n c2 = ConvBlock(512, 3, pooling=True)(c1)\r\n c3 = ConvBlock(512, 3, pooling=True)(c2)\r\n _layer = ConvBlock(512, 3, pooling=True)(c3)\r\n _layer = ConvBlock(512, 3, pooling=True)(_layer)\r\n _layer = Flatten()(_layer)\r\n _g = Dense(512, activation='relu')(_layer)\r\n att1_f, att1_map = Attention((16, 16, 256), 512, method='pc')([c1, _g])\r\n att2_f, att2_map = Attention((8, 8, 512), 512, method='pc')([c2, _g])\r\n att3_f, att3_map = Attention((4, 4, 512), 512, method='pc')([c3, _g])\r\n f_concat = tf.concat([att1_f, att2_f, att3_f], axis=1)\r\n _out = Dense(n_classes, 'softmax')(f_concat)\r\n model = Model(_inputs, [_out, att1_map, att2_map, att3_map])\r\n model.load_weights(r'D:\\pyproject\\data\\CIFAR10-tensorflow\\vgg-att.h5')\r\n # model.compile()\r\n index_lst = np.arange(len(x_test))\r\n np.random.shuffle(index_lst)\r\n x_test = x_test[index_lst]\r\n x_test = x_test[0:nums]\r\n y_test = y_test[index_lst]\r\n y_test = y_test[0:nums]\r\n pred, att1_map, att2_map, att3_map, = model.predict(x_test)\r\n pred = tf.argmax(pred, axis=1)\r\n att1_map = tf.squeeze(tf.image.resize(tf.expand_dims(att1_map, -1), (32, 32)), -1)\r\n att2_map = tf.squeeze(tf.image.resize(tf.expand_dims(att2_map, -1), (32, 32)), -1)\r\n att3_map = tf.squeeze(tf.image.resize(tf.expand_dims(att3_map, -1), (32, 32)), -1)\r\n classes = ('plane', 'car', 'bird', 'cat',\r\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n for i in range(nums):\r\n img = x_test[i]\r\n plt.subplot(141)\r\n plt.imshow(img)\r\n plt.title('Img')\r\n plt.subplot(142)\r\n plt.imshow(img)\r\n plt.imshow(att1_map[i], alpha=0.4, cmap='rainbow')\r\n plt.title('att1_map')\r\n plt.subplot(143)\r\n plt.imshow(img)\r\n plt.imshow(att2_map[i], alpha=0.4, cmap='rainbow')\r\n plt.title('att2_map')\r\n plt.subplot(144)\r\n plt.imshow(img)\r\n plt.imshow(att3_map[i], alpha=0.4, cmap='rainbow')\r\n plt.title('att3_map')\r\n plt.suptitle(f'Prediction={classes[pred[i]]} True={classes[y_test[i][0]]}')\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n # main()\r\n visualization()"
] |
[
[
"matplotlib.pyplot.imshow",
"tensorflow.concat",
"tensorflow.keras.optimizers.SGD",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Conv2D",
"matplotlib.pyplot.subplot",
"tensorflow.argmax",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.title",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Model",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.datasets.cifar10.load_data",
"numpy.random.shuffle",
"tensorflow.expand_dims",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.utils.to_categorical"
]
] |
rafalbojarczuk/MusicGenreClassifier
|
[
"259a8f30a057c165f67b44278ad21b140e688759"
] |
[
"train.py"
] |
[
"import tensorflow as tf\nimport tensorflow.keras as keras\nimport librosa\nimport librosa.feature\nimport glob\nimport numpy as np\nfrom utils import load_data\nfrom models import simple_cnn\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\ntrainX, trainY, validationX, validationY, testX, testY = load_data(split_into_k_equal_parts=True, k=7)\n\nY_True = []\nfor i in testY:\n Y_True.append(list(i).index(1))\n\n#Reshaping into (batch_size, height, width, channels)\ntrainX = trainX.reshape((trainX.shape[0], trainX.shape[1], trainX.shape[2], 1))\nvalidationX = validationX.reshape((validationX.shape[0], validationX.shape[1], validationX.shape[2], 1))\ntestX = testX.reshape((testX.shape[0], testX.shape[1], testX.shape[2], 1))\n\nprint(trainX.shape)\nprint(trainY.shape)\nprint(validationX.shape)\nprint(validationY.shape)\n\nindim_x = trainX.shape[1]\nindim_y = trainX.shape[2]\n\nmodel = simple_cnn((indim_x,indim_y), conv_layers=[16, 32, 48])\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\nmodel.fit(trainX, trainY, batch_size = 128, validation_data=(validationX, validationY), epochs=25)\n\nmodel.evaluate(testX, testY, verbose=2)\n\n\n\n# predict probabilities for test set\nY_PredictedProbabilities = model.predict(testX, verbose=0)\n# predict classes for test set\nY_Predicted = model.predict_classes(testX, verbose=0)\nprint(Y_PredictedProbabilities)\nprint(Y_Predicted)\nprint(Y_True)\n\ntarget_names = ['Classical', 'Electronic', 'Pop', 'Rock', 'Hip-Hop']\nprint(classification_report(Y_True, Y_Predicted,target_names=target_names))\nprint(confusion_matrix(Y_True, Y_Predicted))\n\n\n\n"
] |
[
[
"sklearn.metrics.classification_report",
"sklearn.metrics.confusion_matrix"
]
] |
raminaghods/NATS
|
[
"175e2a495fffac4161bbee5501053068e3391885"
] |
[
"Synthetic_Code/SyntheticRun.py"
] |
[
"'''\nCode for the work:\n\n``Multi Agent Active Search using Realistic Depth-Aware Noise Model'', Ramina Ghods, William J Durkin and Jeff Schneider\n\n(C) Ramina Ghods 2020 (rghods@cs.cmu.edu)\nPlease cite the following paper to use the code:\n\n@article{ghods2020multi,\n title={Multi-Agent Active Search using Realistic Depth-Aware Noise Model},\n author={Ghods, Ramina and Durkin, William J and Schneider, Jeff},\n journal={arXiv preprint arXiv:2011.04825},\n year={2020}\n}\n'''\n\nfrom BinaryTS import BinaryTS\nfrom Random import Random\nfrom NATS import NATS\nfrom RSI import RSI\nfrom bayesian_optimization import Bayesian_optimizer\nfrom worker_manager import WorkerManager\nfrom argparse import Namespace\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pickle\nfrom joblib import Parallel, delayed\nimport seaborn as sb\nfrom matplotlib.pyplot import cm\nfrom scipy import stats\nimport tikzplotlib\n\ndef trials(func_class,mu,max_capital, num_agents, mode, trl):\n\n rng = np.random.RandomState(trl)\n idx = rng.choice(n,k,replace=False)\n beta = np.zeros((n,1))\n beta[idx,:] = mu\n\n with open('posteriorfile.txt', 'a+') as f:\n print(' '.join(map(str,np.transpose(idx))),'\\n',file=f)\n\n func_class.set_beta(beta)\n worker_manager = WorkerManager(func_caller=func_class, worker_ids=num_agents, poll_time=1e-15, trialnum=trl)\n\n options = Namespace(max_num_steps=max_capital, num_init_evals=num_agents, num_workers=num_agents, mode=mode, GP=func_class,check_performance=False)\n\n beta_hats = Bayesian_optimizer(worker_manager, func_class, options).optimize(max_capital)\n\n full_recovery_rate = []\n partial_recovery_rate = []\n\n for i in range(max_capital):\n beta_hat = beta_hats[i]\n\n est = (beta_hat>(np.amax(beta_hat)/2))\n real = (beta>0)\n\n partial_recovery_rate.append(np.sum(est==real)/(n))\n correct = 0.0\n if(np.all(est==real)):\n correct = 1.0\n full_recovery_rate.append(correct)\n\n return full_recovery_rate\n\n\n\nif __name__ == \"__main__\":\n\n #creating empty files:\n open('resfile.txt', 'w').close()\n open('posteriorfile.txt', 'w').close()\n open('positionfile.txt', 'w').close()\n open('testresults.txt', 'w').close()\n mu = 1.0 # signal intensity to create nonzero entries of vector beta, this parameter is not used for estimation\n theta2 = 0 # signal variance to create nonzero entries of vector beta\n lmbd = 10 # Laplace hyper parameter lmbd = sqrt(eta) where eta is introduced in the paper\n sigma2 = 0.005 # noise variance on observations\n EMitr = 30 # number of iterations for the Expectation-Maximization estimator\n k_arr = np.array([5]) # sparsity rate list\n num_trials = 3 # number of trials\n n1 = 6 # length n1 of matrix beta\n n2 = 6\n n = n1*n2\n T = 4# list on number of measurements T\n err = 0.05 # hyperparameter for RSI algorithm\n alpha = 1 # hyper parameter for LATSI algorithm\n noise_vec = np.append(np.append(np.array(1*[sigma2,sigma2]),\n np.repeat(4*sigma2,4)),np.repeat(9*sigma2,6))\n num_agents = np.array([4]) # list on number of agents\n mode = 'asy' #alternatively 'syn' defines synchronous vs. asynchronous parallelisation. we focus on 'asy' in this paper\n n = n1*n2\n x_axis = 'measurements' # options for x axis are 'sparsity','agents','measurements'\n recovery_thr = 0.5 # recovry threshold\n\n full_recovery_rate = np.zeros((num_agents.shape[0], k_arr.shape[0],T, num_trials,4)) # percentage of results where we fully recover a vector beta\n partial_recovery_rate = np.zeros((num_agents.shape[0], k_arr.shape[0],T, num_trials,4)) # percentage of estimating correct entries\n\n savepath = 'results/'\n filename = ('k-arr_%s_agents_%s_n1_%d_n2_%d_trials_%d.pkl'%(str(k_arr),str(num_agents),n1,n2,num_trials))\n\n kid = -1\n for k in k_arr:\n kid += 1\n aid = 0\n for agents in num_agents:\n\n #initialize:\n res_NATS = np.ones((num_trials))\n res_BinaryTS = np.ones((num_trials))\n res_RSI = np.ones((num_trials))\n res_Random = np.ones((num_trials))\n\n\n\n print('agents: %d k=%d'%(agents,k))\n schftseed = T * (num_trials+1)\n beta_temp = np.zeros((n,1)) # temporary value\n num_jobs = 3#40//agents\n\n result_NATS = Parallel(n_jobs=num_jobs, prefer='processes')(delayed(trials)\\\n (NATS(beta_temp, n1, mu, theta2, noise_vec, lmbd, EMitr,agents, schftseed+T*trl),\\\n mu,T, agents, mode, schftseed+T*trl) for trl in range(num_trials))\n res_NATS = np.array(result_NATS)\n\n result_Random = Parallel(n_jobs=num_jobs, prefer='processes')(delayed(trials)\\\n (Random(beta_temp,n1,mu,theta2,noise_vec,EMitr, agents,schftseed+T*trl),mu,T, agents, \\\n mode, schftseed+T*trl) for trl in range(num_trials))\n res_Random = np.array(result_Random)\n #\n result_RSI = Parallel(n_jobs=num_jobs, prefer='processes')(delayed(trials)\\\n (RSI(beta_temp,n1,mu,theta2,noise_vec,lmbd,EMitr,err,agents,schftseed+T*trl),mu,T, \\\n agents, mode, schftseed+T*trl) for trl in range(num_trials))\n res_RSI = np.array(result_RSI)\n #\n result_BinaryTS = Parallel(n_jobs=num_jobs, prefer='processes')(delayed(trials)\\\n (BinaryTS(beta_temp, n1, mu, theta2, noise_vec, lmbd, EMitr, agents, schftseed+T*trl),\\\n mu,T,agents, mode, schftseed+T*trl) for trl in range(num_trials))\n res_BinaryTS = np.array(result_BinaryTS)\n\n\n full_recovery_rate[aid,kid,:,:,0] = np.stack(res_NATS).T#NATS\n full_recovery_rate[aid,kid,:,:,1] = np.stack(res_BinaryTS).T#BinaryTS\n full_recovery_rate[aid,kid,:,:,2] = np.stack(res_RSI).T#RSI\n full_recovery_rate[aid,kid,:,:,3] = np.stack(res_Random).T#Random\n\n aid += 1\n with open(os.path.join(savepath,'k_%d_g_%d_n1_%d_n2_%d_trials_%d.pkl'%(k,agents,n1,n2,num_trials)),'wb') as f:\n pickle.dump([noise_vec,T,full_recovery_rate],f)\n\n # plot_animation2(n1,n2,k,T,mu)\n\n\n with open(os.path.join(savepath,filename),'wb') as f:\n pickle.dump([noise_vec,T,full_recovery_rate],f)\n\n print('saved!')\n\n\n\n with open(os.path.join(savepath,filename), 'rb') as f:\n data = pickle.load(f)\n\n measurements = np.zeros((num_agents.shape[0],k_arr.shape[0],3,4))\n\n if (x_axis == 'sparsity' or x_axis == 'agents'):\n for gid in range(num_agents.shape[0]):\n for kid in range(k_arr.shape[0]):\n recovery = np.mean(data[2][gid,kid,:,:,0],axis=1)\n measurements[gid,kid,1,0] = np.amin(np.argwhere(recovery>recovery_thr))\n m_std_err = stats.sem(data[2][gid,kid,:,:,0], axis=1)\n measurements[gid,kid,0,0] = np.amin(np.argwhere(recovery+m_std_err>recovery_thr))\n measurements[gid,kid,2,0] = np.amin(np.argwhere(recovery-m_std_err>recovery_thr))\n\n recovery = np.mean(data[2][gid,kid,:,:,1],axis=1)\n measurements[gid,kid,1,1] = np.amin(np.argwhere(recovery>recovery_thr))\n m_std_err = stats.sem(data[2][gid,kid,:,:,1], axis=1)\n measurements[gid,kid,0,1] = np.amin(np.argwhere(recovery+m_std_err>recovery_thr))\n measurements[gid,kid,2,1] = np.amin(np.argwhere(recovery-m_std_err>recovery_thr))\n\n recovery = np.mean(data[2][gid,kid,:,:,2],axis=1)\n measurements[gid,kid,1,2] = np.amin(np.argwhere(recovery>recovery_thr))\n m_std_err = stats.sem(data[2][gid,kid,:,:,2], axis=1)\n measurements[gid,kid,0,2] = np.amin(np.argwhere(recovery+m_std_err>recovery_thr))\n measurements[gid,kid,2,2] = np.amin(np.argwhere(recovery-m_std_err>recovery_thr))\n\n recovery = np.mean(data[2][gid,kid,:,:,3],axis=1)\n measurements[gid,kid,1,3] = np.amin(np.argwhere(recovery>recovery_thr))\n m_std_err = stats.sem(data[2][gid,kid,:,:,3], axis=1)\n measurements[gid,kid,0,3] = np.amin(np.argwhere(recovery+m_std_err>recovery_thr))\n measurements[gid,kid,2,3] = np.amin(np.argwhere(recovery-m_std_err>recovery_thr))\n\n NATScolor='mediumvioletred'\n Randomcolor='steelblue'\n BinaryTScolor='forestgreen'\n RSIcolor='orange'\n # Pointcolor='saddlebrown'\n\n marker = [\"o\",\"d\",\"s\",\"*\",\"X\"]\n\n if (x_axis == 'sparsity'):\n for gid,g in enumerate(num_agents):\n plt.figure(figsize = (8,6))\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,0], color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,1], color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,2], color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,3], color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(k_arr, measurements[gid,:,0,0],measurements[gid,:,2,0], color=NATScolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,1],measurements[gid,:,2,1], color=BinaryTScolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,2],measurements[gid,:,2,2], color=RSIcolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,3],measurements[gid,:,2,3], color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"sparsity (k)\",fontsize = 18)\n plt.ylabel(\"measurements (T)\",fontsize = 18)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.title(\"recovery rate=%1.2f,g=%d\"%(recovery_thr,g), fontsize=18)\n plt.savefig('results/sparsity_measurements_recovery_%1.2f_g_%d_n_%d_trials_%d.pdf'%(recovery_thr,g,n,num_trials))\n plt.show()\n\n plt.figure(figsize = (8,6))\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,0]/g, color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,1]/g, color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,2], color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=k_arr,data=measurements[gid,:,1,3]/g, color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(k_arr, measurements[gid,:,0,0]/g,measurements[gid,:,2,0]/g, color=NATScolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,1]/g,measurements[gid,:,2,1]/g, color=BinaryTScolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,2],measurements[gid,:,2,2], color=RSIcolor, alpha=0.2)\n plt.fill_between(k_arr, measurements[gid,:,0,3]/g,measurements[gid,:,2,3]/g, color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"sparsity (k)\",fontsize = 18)\n plt.ylabel(\"time (T/g)\",fontsize = 18)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.title(\"recovery rate=%1.2f,g=%d\"%(recovery_thr,g), fontsize=18)\n plt.savefig('results/sparsity_time_recovery_%1.2f_g_%d_n_%d_trials_%d.pdf'%(recovery_thr,g,n,num_trials))\n plt.show()\n\n elif (x_axis == 'agents'):\n for kid,k in enumerate(k_arr):\n plt.figure(figsize = (8,6))\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,0], color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,1], color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,2], color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,3], color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(num_agents, measurements[:,kid,0,0],measurements[:,kid,2,0], color=NATScolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,1],measurements[:,kid,2,1], color=BinaryTScolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,2],measurements[:,kid,2,2], color=RSIcolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,3],measurements[:,kid,2,3], color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"agents (g)\",fontsize = 18)\n plt.ylabel(\"measurements (T)\",fontsize = 18)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.title(\"recovery rate=%1.2f,k=%d\"%(recovery_thr,k), fontsize=18)\n plt.savefig('results/agents_measurements_recovery_%1.2f_k_%d_n_%d_trials_%d.pdf'%(recovery_thr,k,n,num_trials))\n plt.show()\n\n plt.figure(figsize = (8,6))\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,0]/num_agents, color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,1]/num_agents, color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,2], color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=num_agents,data=measurements[:,kid,1,3]/num_agents, color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(num_agents, measurements[:,kid,0,0]/num_agents,measurements[:,kid,2,0]/num_agents, color=NATScolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,1]/num_agents,measurements[:,kid,2,1]/num_agents, color=BinaryTScolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,2],measurements[:,kid,2,2], color=RSIcolor, alpha=0.2)\n plt.fill_between(num_agents, measurements[:,kid,0,3]/num_agents,measurements[:,kid,2,3]/num_agents, color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"agents (g)\",fontsize = 18)\n plt.ylabel(\"time (T/g)\",fontsize = 18)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.title(\"recovery rate=%1.2f,k=%d\"%(recovery_thr,k), fontsize=18)\n plt.savefig('results/agents_time_recovery_%1.2f_k_%d_n_%d_trials_%d.pdf'%(recovery_thr,k,n,num_trials))\n plt.show()\n\n elif(x_axis == 'measurements'):\n for kid,k in enumerate(k_arr):\n for gid,g in enumerate(num_agents):\n recovery_NATS = np.mean(data[2][gid,kid,:,:,0], axis=1)\n recovery_BinaryTS = np.mean(data[2][gid,kid,:,:,1], axis=1)\n recovery_RSI = np.mean(data[2][gid,kid,:,:,2], axis=1)\n recovery_Random = np.mean(data[2][gid,kid,:,:,3], axis=1)\n f_std_err_NATS = stats.sem(data[2][gid,kid,:,:,0], axis=1)\n f_std_err_BinaryTS = stats.sem(data[2][gid,kid,:,:,1], axis=1)\n f_std_err_RSI = stats.sem(data[2][gid,kid,:,:,2], axis=1)\n f_std_err_Random = stats.sem(data[2][gid,kid,:,:,3], axis=1)\n\n plt.figure(figsize = (8,6))\n sb.tsplot(time=np.arange(1,T+1),data=recovery_NATS, color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=np.arange(1,T+1),data=recovery_BinaryTS, color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=np.arange(1,T+1),data=recovery_RSI, color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=np.arange(1,T+1),data=recovery_Random, color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(np.arange(1,T+1), recovery_NATS+f_std_err_NATS, recovery_NATS-f_std_err_NATS, color=NATScolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1), recovery_BinaryTS+f_std_err_BinaryTS,recovery_BinaryTS-f_std_err_BinaryTS, color=BinaryTScolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1), recovery_RSI+f_std_err_RSI, recovery_RSI-f_std_err_RSI, color=RSIcolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1), recovery_Random+f_std_err_Random,recovery_Random-f_std_err_Random, color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"number of measurements (T)\",fontsize = 18)\n plt.ylabel(\"full recovery rate\",fontsize = 18)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.ylim((0,1))\n plt.title(\"k=%d,g=%d\"%(k,g), fontsize=18)\n plt.savefig('results/measurements_full_recovery_g_%d_k_%d_n_%d_trials_%d.pdf'%(g,k,n,num_trials))\n plt.show()\n\n plt.figure(figsize = (8,6))\n sb.tsplot(time=np.arange(1,T+1)/g,data=recovery_NATS, color=NATScolor, condition='NATS', linestyle='solid',marker=marker[0])\n sb.tsplot(time=np.arange(1,T+1)/g,data=recovery_BinaryTS, color=BinaryTScolor, condition='BinaryTS', linestyle='dashdot',marker=marker[1])\n sb.tsplot(time=np.arange(1,T+1)/g,data=recovery_RSI, color=RSIcolor, condition='RSI', linestyle='dotted',marker=marker[2])\n sb.tsplot(time=np.arange(1,T+1)/g,data=recovery_Random, color=Randomcolor, condition='Random', linestyle='dashed',marker=marker[3])\n\n plt.fill_between(np.arange(1,T+1)/g, recovery_NATS+f_std_err_NATS, recovery_NATS-f_std_err_NATS, color=NATScolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1)/g, recovery_BinaryTS+f_std_err_BinaryTS,recovery_BinaryTS-f_std_err_BinaryTS, color=BinaryTScolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1)/g, recovery_RSI+f_std_err_RSI, recovery_RSI-f_std_err_RSI, color=RSIcolor, alpha=0.2)\n plt.fill_between(np.arange(1,T+1)/g, recovery_Random+f_std_err_Random,recovery_Random-f_std_err_Random, color=Randomcolor, alpha=0.2)\n\n plt.legend()\n plt.xlabel(\"time (T/g)\",fontsize = 18)\n plt.ylabel(\"full recovery rate\",fontsize = 18)\n plt.xlim(0,n)\n plt.xticks(fontsize = 18)\n plt.yticks(fontsize = 18)\n plt.ylim((0,1))\n plt.title(\"k=%d,g=%d\"%(k,g), fontsize=18)\n plt.savefig('results/Time_full_recovery_g_%d_k_%d_n_%d_trials_%d.pdf'%(g,k,n,num_trials))\n plt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.amax",
"scipy.stats.sem",
"numpy.all",
"numpy.mean",
"numpy.arange",
"numpy.stack",
"numpy.repeat",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.fill_between",
"numpy.transpose",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.random.RandomState",
"numpy.ones",
"numpy.argwhere",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks"
]
] |
Karthik-Suresh93/fpn_visdrone
|
[
"5a360e2b26e1c12416b9fd79f99cd96c6f8577e9"
] |
[
"lib_original/datasets/uav.py"
] |
[
"from __future__ import print_function\r\nfrom __future__ import absolute_import\r\n# --------------------------------------------------------\r\n# Fast R-CNN\r\n# Copyright (c) 2015 Microsoft\r\n# Licensed under The MIT License [see LICENSE for details]\r\n# Written by Ross Girshick\r\n# --------------------------------------------------------\r\n\r\nimport xml.dom.minidom as minidom\r\n\r\nimport os\r\n# import PIL\r\nimport numpy as np\r\nimport scipy.sparse\r\nimport subprocess\r\nimport math\r\nimport glob\r\nimport uuid\r\nimport scipy.io as sio\r\nimport xml.etree.ElementTree as ET\r\nimport cPickle\r\nfrom .imdb import imdb\r\nfrom .imdb import ROOT_DIR\r\nfrom . import ds_utils\r\nfrom .voc_eval import voc_eval\r\n\r\n# TODO: make fast_rcnn irrelevant\r\n# >>>> obsolete, because it depends on sth outside of this project\r\nfrom model.utils.config import cfg\r\n\r\ntry:\r\n xrange # Python 2\r\nexcept NameError:\r\n xrange = range # Python 3\r\n\r\n# <<<< obsolete\r\n\r\n\r\nclass uav(imdb):\r\n def __init__(self, image_set, year, devkit_path=None):\r\n imdb.__init__(self, 'uav_' + year + '_' + image_set)\r\n self._year = year\r\n self._image_set = image_set\r\n self._devkit_path = self._get_default_path() if devkit_path is None \\\r\n else devkit_path\r\n #EDIT: DEVKIT PATH IS EDITED FOR FPN.PYTORCH-MASTER STYLE DIR OF UAVDT\r\n self._devkit_path = \"/home/ksuresh/fpn.pytorch-master/data/uavdt/data/VOCdevkit2007\"\r\n self._data_path = os.path.join(self._devkit_path, 'UAV' + self._year)\r\n self._classes = ('__background__', 'car')\r\n self._weathers = ('daylight', 'night', 'fog')\r\n self._altitudes = ('low-alt', 'medium-alt', 'high-alt')\r\n self._angles = ('front-side-view', 'front-view', 'side-view', 'bird-view')\r\n self._class_to_ind = dict(zip(self.classes, xrange(self.num_classes)))\r\n self._weather_to_ind = {'daylight':0, 'night':1, 'fog':2}\r\n self._altitude_to_ind = {'low-alt':0, 'medium-alt':1, 'high-alt':2}\r\n self._angle_to_ind = {'front-side-view':0, 'front-view':1, 'side-view':2, 'bird-view':3}\r\n self._image_ext = '.jpg'\r\n self._image_index = self._load_image_set_index()\r\n # Default to roidb handler\r\n self._roidb_handler = self.selective_search_roidb\r\n self._salt = str(uuid.uuid4())\r\n self._comp_id = 'comp4'\r\n # PASCAL specific config options\r\n self.config = {'cleanup' : True,\r\n 'use_salt' : True,\r\n 'use_diff' : True,\r\n 'matlab_eval' : False,\r\n 'rpn_file' : None,\r\n 'min_size' : 4}\r\n\r\n assert os.path.exists(self._devkit_path), \\\r\n 'VOCdevkit path does not exist: {}'.format(self._devkit_path)\r\n assert os.path.exists(self._data_path), \\\r\n 'Path does not exist: {}'.format(self._data_path)\r\n self._gamma = None\r\n self._epoch = None\r\n self._ckpt = None\r\n\r\n def set_gamma(self, gamma):\r\n self._gamma = gamma\r\n\r\n def set_epoch(self, epoch):\r\n self._epoch = epoch\r\n\r\n def set_ckpt(self, ckpt):\r\n self._ckpt = ckpt\r\n\r\n def image_path_at(self, i):\r\n \"\"\"\r\n Return the absolute path to image i in the image sequence.\r\n \"\"\"\r\n return self.image_path_from_index(self._image_index[i])\r\n\r\n def image_id_at(self, i):\r\n \"\"\"\r\n Return the absolute path to image i in the image sequence.\r\n \"\"\"\r\n return self._image_index[i]\r\n\r\n def image_path_from_index(self, index):\r\n \"\"\"\r\n Construct an image path from the image's \"index\" identifier.\r\n \"\"\"\r\n image_path = os.path.join(self._data_path, 'JPEGImages',\r\n index + self._image_ext)\r\n assert os.path.exists(image_path), \\\r\n 'Path does not exist: {}'.format(image_path)\r\n return image_path\r\n\r\n def _load_image_set_index(self):\r\n \"\"\"\r\n Load the indexes listed in this dataset's image set file.\r\n \"\"\"\r\n # Example path to image set file:\r\n # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt\r\n image_set_file = os.path.join(self._data_path, 'ImageSets', 'Layout',\r\n self._image_set + '.txt')\r\n assert os.path.exists(image_set_file), \\\r\n 'Path does not exist: {}'.format(image_set_file)\r\n with open(image_set_file) as f:\r\n image_index = [x.strip() for x in f.readlines()]\r\n return image_index\r\n\r\n def _get_default_path(self):\r\n \"\"\"\r\n Return the default path where PASCAL VOC is expected to be installed.\r\n \"\"\"\r\n return os.path.join('data', 'VOCdevkit2007')\r\n\r\n def gt_roidb(self):\r\n \"\"\"\r\n Return the database of ground-truth regions of interest.\r\n This function loads/saves from/to a cache file to speed up future calls.\r\n \"\"\"\r\n cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')\r\n if os.path.exists(cache_file):\r\n with open(cache_file, 'rb') as fid:\r\n roidb = cPickle.load(fid)\r\n print('{} gt roidb loaded from {}'.format(self.name, cache_file))\r\n return roidb\r\n\r\n gt_roidb = [self._load_pascal_annotation(index)\r\n for index in self.image_index]\r\n with open(cache_file, 'wb') as fid:\r\n cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)\r\n print('wrote gt roidb to {}'.format(cache_file))\r\n\r\n return gt_roidb\r\n\r\n def selective_search_roidb(self):\r\n \"\"\"\r\n Return the database of selective search regions of interest.\r\n Ground-truth ROIs are also included.\r\n This function loads/saves from/to a cache file to speed up future calls.\r\n \"\"\"\r\n cache_file = os.path.join(self.cache_path,\r\n self.name + '_selective_search_roidb.pkl')\r\n\r\n if os.path.exists(cache_file):\r\n with open(cache_file, 'rb') as fid:\r\n roidb = cPickle.load(fid)\r\n print('{} ss roidb loaded from {}'.format(self.name, cache_file))\r\n return roidb\r\n\r\n if self._image_set != 'test':\r\n gt_roidb = self.gt_roidb()\r\n ss_roidb = self._load_selective_search_roidb(gt_roidb)\r\n roidb = imdb.merge_roidbs(gt_roidb, ss_roidb)\r\n else:\r\n roidb = self._load_selective_search_roidb(None)\r\n with open(cache_file, 'wb') as fid:\r\n cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL)\r\n print('wrote ss roidb to {}'.format(cache_file))\r\n\r\n return roidb\r\n\r\n def rpn_roidb(self):\r\n if self._image_set != 'test':\r\n gt_roidb = self.gt_roidb()\r\n rpn_roidb = self._load_rpn_roidb(gt_roidb)\r\n roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb)\r\n else:\r\n roidb = self._load_rpn_roidb(None)\r\n\r\n return roidb\r\n\r\n def _load_rpn_roidb(self, gt_roidb):\r\n filename = self.config['rpn_file']\r\n print('loading {}'.format(filename))\r\n assert os.path.exists(filename), \\\r\n 'rpn data not found at: {}'.format(filename)\r\n with open(filename, 'rb') as f:\r\n box_list = cPickle.load(f)\r\n return self.create_roidb_from_box_list(box_list, gt_roidb)\r\n\r\n def _load_selective_search_roidb(self, gt_roidb):\r\n filename = os.path.abspath(os.path.join(cfg.DATA_DIR,\r\n 'selective_search_data',\r\n self.name + '.mat'))\r\n assert os.path.exists(filename), \\\r\n 'Selective search data not found at: {}'.format(filename)\r\n raw_data = sio.loadmat(filename)['boxes'].ravel()\r\n\r\n box_list = []\r\n for i in xrange(raw_data.shape[0]):\r\n boxes = raw_data[i][:, (1, 0, 3, 2)] - 1\r\n keep = ds_utils.unique_boxes(boxes)\r\n boxes = boxes[keep, :]\r\n keep = ds_utils.filter_small_boxes(boxes, self.config['min_size'])\r\n boxes = boxes[keep, :]\r\n box_list.append(boxes)\r\n\r\n return self.create_roidb_from_box_list(box_list, gt_roidb)\r\n\r\n def _load_pascal_annotation(self, index):\r\n \"\"\"\r\n Load image and bounding boxes info from XML file in the PASCAL VOC\r\n format.\r\n \"\"\"\r\n filename = os.path.join(self._data_path, 'Annotations', index + '.xml')\r\n tree = ET.parse(filename)\r\n objs = tree.findall('object')\r\n weather = self._weather_to_ind[tree.find('weather').text.lower().strip()]\r\n altitude = self._altitude_to_ind[tree.find('altitude').text.lower().strip()]\r\n angle = self._angle_to_ind[tree.find('angle').text.lower().strip()]\r\n if not self.config['use_diff']:\r\n # Exclude the samples labeled as difficult\r\n non_diff_objs = [\r\n obj for obj in objs if int(obj.find('difficult').text) == 0]\r\n if len(non_diff_objs) != len(objs):\r\n print('Removed {} difficult objects'.format(\r\n len(objs) - len(non_diff_objs)))\r\n objs = non_diff_objs\r\n num_objs = len(objs)\r\n\r\n boxes = np.zeros((num_objs, 4), dtype=np.uint16)\r\n gt_classes = np.zeros((num_objs), dtype=np.int32)\r\n overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)\r\n # \"Seg\" area for pascal is just the box area\r\n seg_areas = np.zeros((num_objs), dtype=np.float32)\r\n\r\n # Load object bounding boxes into a data frame.\r\n for ix, obj in enumerate(objs):\r\n bbox = obj.find('bndbox')\r\n # Make pixel indexes 0-based\r\n x1 = float(bbox.find('xmin').text) - 1\r\n y1 = float(bbox.find('ymin').text) - 1\r\n x2 = float(bbox.find('xmax').text) - 1\r\n y2 = float(bbox.find('ymax').text) - 1\r\n cls = self._class_to_ind[obj.find('name').text.lower().strip()]\r\n boxes[ix, :] = [x1, y1, x2, y2]\r\n gt_classes[ix] = cls\r\n overlaps[ix, cls] = 1.0\r\n seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n\r\n overlaps = scipy.sparse.csr_matrix(overlaps)\r\n\r\n return {'boxes' : boxes,\r\n 'weather': weather,\r\n 'altitude': altitude,\r\n 'angle': angle,\r\n 'gt_classes': gt_classes,\r\n 'gt_overlaps' : overlaps,\r\n 'flipped' : False,\r\n 'seg_areas' : seg_areas}\r\n\r\n def _get_comp_id(self):\r\n comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt']\r\n else self._comp_id)\r\n return comp_id\r\n\r\n def _get_voc_results_file_template(self):\r\n # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt\r\n filename = self._get_comp_id() + '_det_' + self._image_set + '_{:s}.txt'\r\n path = os.path.join('data/results', 'UAV' + self._year, str(self._gamma), str(self._epoch), str(self._ckpt))\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n return os.path.join(path, filename)\r\n\r\n def _write_voc_results_file(self, all_boxes):\r\n for cls_ind, cls in enumerate(self.classes):\r\n if cls == '__background__':\r\n continue\r\n print('Writing {} VOC results file'.format(cls))\r\n filename = self._get_voc_results_file_template().format(cls)\r\n with open(filename, 'wt') as f:\r\n for im_ind, index in enumerate(self.image_index):\r\n dets = all_boxes[cls_ind][im_ind]\r\n if dets == []:\r\n continue\r\n # the VOCdevkit expects 1-based indices\r\n for k in xrange(dets.shape[0]):\r\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\r\n format(index, dets[k, 4],\r\n dets[k, 0] + 1, dets[k, 1] + 1,\r\n dets[k, 2] + 1, dets[k, 3] + 1))\r\n\r\n def _write_voc_results_file_attributes(self, all_boxes, attr_name):\r\n if attr_name == 'weather':\r\n attr_ind = 5\r\n attributes = self._weathers\r\n elif attr_name == 'altitude':\r\n attr_ind = 6\r\n attributes = self._altitudes\r\n else:\r\n attr_ind = 7\r\n attributes = self._angles\r\n\r\n for ind, attr in enumerate(attributes):\r\n print('Writing {} VOC results file'.format(attr))\r\n filename = self._get_voc_results_file_template().format(attr)\r\n with open(filename, 'wt') as f:\r\n for im_ind, index in enumerate(self.image_index):\r\n dets = all_boxes[1][im_ind]\r\n #print('{} = {}'.format(int(np.sum(dets[:, attr_ind])), ind * dets.shape[0]))\r\n if dets == [] or int(np.sum(dets[:, attr_ind])) != ind * dets.shape[0]:\r\n continue\r\n for k in xrange(dets.shape[0]):\r\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\r\n format(index, dets[k, 4],\r\n dets[k, 0] + 1, dets[k, 1] + 1,\r\n dets[k, 2] + 1, dets[k, 3] + 1))\r\n\r\n def _do_python_eval(self, output_dir = 'output'):\r\n annopath = os.path.join(\r\n self._devkit_path,\r\n 'UAV' + self._year,\r\n 'Annotations',\r\n '{:s}.xml')\r\n imagesetfile = os.path.join(\r\n self._devkit_path,\r\n 'UAV' + self._year,\r\n 'ImageSets',\r\n 'Layout',\r\n self._image_set + '.txt')\r\n cachedir = os.path.join(self._devkit_path, 'annotations_cache')\r\n aps = []\r\n # The PASCAL VOC metric changed in 2010\r\n use_07_metric = True if int(self._year) < 2020 else False\r\n print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))\r\n if not os.path.isdir(output_dir):\r\n os.mkdir(output_dir)\r\n filename = '_det_' + self._image_set + '_ap.txt'\r\n path = os.path.join('data/results', 'UAV' + self._year, str(self._gamma), str(self._epoch), str(self._ckpt))\r\n with open(os.path.join(path, filename), 'wt') as f:\r\n for classes in [self._classes, self._weathers, self._altitudes, self._angles]:\r\n for i, cls in enumerate(classes):\r\n if cls == '__background__':\r\n continue\r\n filename = self._get_voc_results_file_template().format(cls)\r\n rec, prec, ap = voc_eval(\r\n filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5,\r\n use_07_metric=use_07_metric)\r\n aps += [ap]\r\n f.write('AP for {} = {:.4f}\\n'.format(cls, ap))\r\n # with open(os.path.join(output_dir, cls + '_pr.pkl'), 'w') as f:\r\n # cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\r\n\r\n # print('Mean AP = {:.4f}'.format(np.mean(aps)))\r\n # print('~~~~~~~~')\r\n # print('Results:')\r\n # for ap in aps:\r\n # print('{:.3f}'.format(ap))\r\n # print('{:.3f}'.format(np.mean(aps)))\r\n # print('~~~~~~~~')\r\n # print('')\r\n # print('--------------------------------------------------------------')\r\n # print('Results computed with the **unofficial** Python eval code.')\r\n # print('Results should be very close to the official MATLAB eval code.')\r\n # print('Recompute with `./tools/reval.py --matlab ...` for your paper.')\r\n # print('-- Thanks, The Management')\r\n # print('--------------------------------------------------------------')\r\n\r\n def _do_matlab_eval(self, output_dir='output'):\r\n print('-----------------------------------------------------')\r\n print('Computing results with the official MATLAB eval code.')\r\n print('-----------------------------------------------------')\r\n path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets',\r\n 'VOCdevkit-matlab-wrapper')\r\n cmd = 'cd {} && '.format(path)\r\n cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB)\r\n cmd += '-r \"dbstop if error; '\r\n cmd += 'voc_eval(\\'{:s}\\',\\'{:s}\\',\\'{:s}\\',\\'{:s}\\'); quit;\"' \\\r\n .format(self._devkit_path, self._get_comp_id(),\r\n self._image_set, output_dir)\r\n print('Running:\\n{}'.format(cmd))\r\n status = subprocess.call(cmd, shell=True)\r\n\r\n def evaluate_detections(self, all_boxes, output_dir):\r\n self._write_voc_results_file(all_boxes)\r\n self._write_voc_results_file_attributes(all_boxes, attr_name='weather')\r\n self._write_voc_results_file_attributes(all_boxes, attr_name='altitude')\r\n self._write_voc_results_file_attributes(all_boxes, attr_name='angle')\r\n self._do_python_eval(output_dir)\r\n if self.config['matlab_eval']:\r\n self._do_matlab_eval(output_dir)\r\n if self.config['cleanup']:\r\n for cls in self._classes:\r\n if cls == '__background__':\r\n continue\r\n filename = self._get_voc_results_file_template().format(cls)\r\n os.remove(filename)\r\n\r\n def competition_mode(self, on):\r\n if on:\r\n self.config['use_salt'] = False\r\n self.config['cleanup'] = False\r\n else:\r\n self.config['use_salt'] = True\r\n self.config['cleanup'] = True\r\n\r\nif __name__ == '__main__':\r\n d = uav('trainval', '2017')\r\n res = d.roidb\r\n from IPython import embed; embed()"
] |
[
[
"scipy.io.loadmat",
"numpy.zeros",
"numpy.sum"
]
] |
RiceD2KLab/TCH_CardiacSignals_F20
|
[
"ea6e84703086ddb7bfc5ba164aa67acdc9e78b7d",
"ea6e84703086ddb7bfc5ba164aa67acdc9e78b7d"
] |
[
"src/archive/LSTM/LSTMAEts10.py",
"src/exploration/ecg_signal_animation.py"
] |
[
"import tensorflow\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout, RepeatVector, TimeDistributed\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport sys\n\n\ndef create_model(X):\n model = Sequential()\n model.add(LSTM(10, input_shape=(X.shape[1], X.shape[2])))\n model.add(Dropout(rate=0.2))\n model.add(RepeatVector(X.shape[1]))\n model.add(LSTM(10, return_sequences=True))\n model.add(Dropout(rate=0.2))\n model.add(TimeDistributed(Dense(X.shape[2])))\n model.compile(optimizer='adam', loss='mse')\n model.summary()\n\n history = model.fit(X, X, epochs=100, batch_size=1, validation_split=0.1,\n callbacks=[keras.callbacks.EarlyStopping(monitor='loss', patience=3, mode='min')],\n shuffle=False)\n\n model.save('Working_Data/lstm_model')\n # model.predict(X[0:10, :])\n\n # plot the loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(\"Working_Data/lstm_loss.png\")\n plt.show()\n\n print(\"loss of the model is: \")\n print(history.history['loss'])\n\n\ndef create_sequences(data):\n Xs, ys = [], []\n time_steps = 10\n for i in range(len(data) - time_steps):\n Xs.append(data[i:(i + time_steps)].reshape(100*time_steps,4))\n ys.append(data[i + time_steps].reshape(100,4))\n\n return np.array(Xs), np.array(ys)\n\n\ndata = np.load(os.path.join(\"Working_Data/Normalized_Fixed_Dim_HBs_Idx\" + str(1) + \".npy\"))\ndata = data[0:1000, :, :]\n# print(data[0:10].reshape(10000,4).shape)\nX, y = create_sequences(data)\nprint(X.shape, y.shape)\n# create_model(X)\n\nmodel = keras.models.load_model('Working_Data/lstm_model')\nmodel.predict(create_sequences(X[0:5, :, :])[0])\n\n\n\n",
"\"\"\"\nGenerate .gif files for animation of heartbeat and instability detection (for the 5 minute video).\n\"\"\"\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom src.utils import h5_interface\n\n########################################################################################################################\n# Read in the data\nfilename = 'Reference_idx_16_Time_block_1.h5'\nh5f = h5_interface.readh5(filename)\n\nfour_lead, time, heartrate = h5_interface.ecg_np(h5f)\nlead1, lead2, lead3, lead4 = np.vsplit(four_lead, 4)\nlead1, lead2, lead3, lead4 = [lead1[0], lead2[0], lead3[0], lead4[0]]\n\n########################################################################################################################\n# Generate gif for an ECG signal\nplt.rcParams[\"figure.figsize\"] = [12, 3]\nfig, ax = plt.subplots()\nfig.set_tight_layout(True)\n\n# Plot an ECG signal that persists\nline, = ax.plot(time[0:3000], lead1[0:3000], 'b-', linewidth=2)\nline2, = ax.plot(np.linspace(time[0 + 300], time[0 + 300], 100), np.linspace(-1, 1, 100), color='red')\nplt.ylim([-1, 0.8])\nplt.xlim([time[0], 5.5])\nax.set_ylabel('Amplitude', fontsize=20)\nax.set_xlabel('Time (sec)', fontsize=20)\n\n\n# Input function for the updating the gif animation\ndef update_ecg_gif(i):\n \"\"\"\n Moves a red vertical line across the x-axis (time)\n :param i: [int] an iterator\n :return: None\n \"\"\"\n line2.set_xdata(np.linspace(time[i + 300], time[i + 300], 100))\n\n\n# Save and show the gif\nanim = FuncAnimation(fig, update_ecg_gif, frames=np.arange(0, 1000, 2), interval=20)\nanim.save('images//ECG.gif', dpi=80, writer='imagemagick')\nplt.show()\n\n########################################################################################################################\n# Generate gif for an example detection of heartbeat instability\nfig, ax = plt.subplots()\nfig.set_tight_layout(True)\n\n# Plot a detection metric signal that persists\nline, = ax.plot(time[0:300], np.linspace(0, 0, 300), 'g-', linewidth=2)\nline2, = ax.plot(np.linspace(time[0 + 300], time[0 + 300], 100), np.linspace(-1, 2, 100), color='red')\nplt.ylim([0, 1.2])\nplt.xlim([time[0], 5.5])\nax.set_ylabel('Detection Metric', fontsize=20)\nax.set_xlabel('Time (sec)', fontsize=20)\n\n\n# Input function for the updating the gif animation\ndef update_detection_gif(i):\n \"\"\"\n Moves a red vertical line across the x-axis (time), plotting out a sigmoid when instability is detected.\n :param i: [int] an iterator\n :return: None\n \"\"\"\n time_vector = time[0:i + 300]\n line.set_xdata(time_vector)\n\n sigmoid = 1 / (1 + np.exp(12 * (-time_vector + 4)))\n line.set_ydata(sigmoid)\n\n line2.set_xdata(np.linspace(time[i + 300], time[i + 300], 100))\n\n\n# Save and show the gif\nanim = FuncAnimation(fig, update_detection_gif, frames=np.arange(0, 1000, 2), interval=20)\nanim.save('images//Detection.gif', dpi=80, writer='imagemagick')\nplt.show()\n\n########################################################################################################################\n"
] |
[
[
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.legend",
"tensorflow.keras.layers.Dropout",
"matplotlib.pyplot.title",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.callbacks.EarlyStopping",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"tensorflow.keras.layers.RepeatVector",
"tensorflow.keras.layers.LSTM",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.ylabel"
],
[
"numpy.linspace",
"matplotlib.pyplot.ylim",
"numpy.arange",
"numpy.vsplit",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlim",
"numpy.exp",
"matplotlib.pyplot.show"
]
] |
v7labs/darwin-lib
|
[
"13efb4867effd3d312bcfafe1ee242aed61fae3a"
] |
[
"darwin/dataset/local_dataset.py"
] |
[
"import json\nimport multiprocessing as mp\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterator, List, Optional, Tuple\n\nimport numpy as np\nfrom darwin.dataset.utils import get_classes, get_release_path, load_pil_image\nfrom darwin.utils import SUPPORTED_IMAGE_EXTENSIONS\nfrom PIL import Image as PILImage\n\n\nclass LocalDataset(object):\n \"\"\"\n Base class representing a V7 Darwin dataset that has been pulled locally already.\n It can be used with PyTorch dataloaders. See ``darwin.torch`` module for more specialized dataset classes, extending this one.\n\n Parameters\n ----------\n dataset_path : Path\n Path to the location of the dataset on the file system.\n annotation_type : str\n The type of annotation classes ``[\"tag\", \"bounding_box\", \"polygon\"]``.\n partition : Optional[str], default: None\n Selects one of the partitions ``[\"train\", \"val\", \"test\"]``.\n split : str, default: \"default\"\n Selects the split that defines the percentages used (use 'default' to select the default split).\n split_type : str, default: \"random\"\n Heuristic used to do the split ``[\"random\", \"stratified\"]``.\n release_name : Optional[str], default: None\n Version of the dataset.\n\n Attributes\n ----------\n dataset_path : Path\n Path to the location of the dataset on the file system.\n annotation_type : str\n The type of annotation classes ``[\"tag\", \"bounding_box\", \"polygon\"]``.\n partition : Optional[str], default: None\n Selects one of the partitions ``[\"train\", \"val\", \"test\"]``.\n split : str, default: \"default\"\n Selects the split that defines the percentages used (use 'default' to select the default split).\n split_type : str, default: \"random\"\n Heuristic used to do the split ``[\"random\", \"stratified\"]``.\n release_name : Optional[str], default: None\n Version of the dataset.\n\n Raises\n ------\n ValueError\n\n - If ``partition``, ``split_type`` or ``annotation_type`` have an invalid value.\n - If an annotation has no corresponding image\n - If an image has multiple extensions (meaning it is present in multiple formats)\n - If no images are found\n \"\"\"\n\n def __init__(\n self,\n dataset_path: Path,\n annotation_type: str,\n partition: Optional[str] = None,\n split: str = \"default\",\n split_type: str = \"random\",\n release_name: Optional[str] = None,\n ):\n assert dataset_path is not None\n release_path = get_release_path(dataset_path, release_name)\n annotations_dir = release_path / \"annotations\"\n assert annotations_dir.exists()\n images_dir = dataset_path / \"images\"\n assert images_dir.exists()\n\n if partition not in [\"train\", \"val\", \"test\", None]:\n raise ValueError(\"partition should be either 'train', 'val', or 'test'\")\n if split_type not in [\"random\", \"stratified\"]:\n raise ValueError(\"split_type should be either 'random', 'stratified'\")\n if annotation_type not in [\"tag\", \"polygon\", \"bounding_box\"]:\n raise ValueError(\"annotation_type should be either 'tag', 'bounding_box', or 'polygon'\")\n\n self.dataset_path = dataset_path\n self.annotation_type = annotation_type\n self.images_path: List[Path] = []\n self.annotations_path: List[Path] = []\n self.original_classes = None\n self.original_images_path: Optional[List[Path]] = None\n self.original_annotations_path: Optional[List[Path]] = None\n\n # Get the list of classes\n self.classes = get_classes(\n self.dataset_path, release_name, annotation_type=self.annotation_type, remove_background=True\n )\n self.num_classes = len(self.classes)\n\n stems = build_stems(release_path, annotations_dir, annotation_type, split, partition, split_type)\n\n # Find all the annotations and their corresponding images\n for stem in stems:\n annotation_path = annotations_dir / f\"{stem}.json\"\n images = []\n for ext in SUPPORTED_IMAGE_EXTENSIONS:\n image_path = images_dir / f\"{stem}{ext}\"\n if image_path.exists():\n images.append(image_path)\n if len(images) < 1:\n raise ValueError(f\"Annotation ({annotation_path}) does not have a corresponding image\")\n if len(images) > 1:\n raise ValueError(f\"Image ({stem}) is present with multiple extensions. This is forbidden.\")\n assert len(images) == 1\n self.images_path.append(images[0])\n self.annotations_path.append(annotation_path)\n\n if len(self.images_path) == 0:\n raise ValueError(f\"Could not find any {SUPPORTED_IMAGE_EXTENSIONS} file\", f\" in {images_dir}\")\n\n assert len(self.images_path) == len(self.annotations_path)\n\n def get_img_info(self, index: int) -> Dict[str, Any]:\n \"\"\"\n Returns the annotation information for a given image.\n\n Parameters\n ----------\n index : int\n The index of the image.\n\n Returns\n -------\n Dict[str, Any]\n A dictionary with the image's class and annotaiton information.\n\n Raises\n ------\n ValueError\n If there are no annotations downloaded in this machine. You can pull them by using the\n command ``darwin dataset pull $DATASET_NAME --only-annotations`` in the CLI.\n \"\"\"\n if not len(self.annotations_path):\n raise ValueError(\"There are no annotations downloaded.\")\n\n with self.annotations_path[index].open() as f:\n data = json.load(f)[\"image\"]\n return data\n\n def get_height_and_width(self, index: int) -> Tuple[float, float]:\n \"\"\"\n Returns the width and height of the image with the given index.\n\n Parameters\n ----------\n index : int\n The index of the image.\n\n Returns\n -------\n Tuple[float, float]\n A tuple where the first element is the ``height`` of the image and the second is the\n ``width``.\n \"\"\"\n data: Dict[str, Any] = self.get_img_info(index)\n return data[\"height\"], data[\"width\"]\n\n def extend(self, dataset: \"LocalDataset\", extend_classes: bool = False) -> \"LocalDataset\":\n \"\"\"\n Extends the current dataset with another one.\n\n Parameters\n ----------\n dataset : Dataset\n Dataset to merge\n extend_classes : bool, default: False\n Extend the current set of classes by merging it with the set of classes belonging to the\n given dataset.\n\n Returns\n -------\n LocalDataset\n This ``LocalDataset`` extended with the classes of the give one.\n\n Raises\n ------\n ValueError\n\n - If the ``annotation_type`` of this ``LocalDataset`` differs from the\n ``annotation_type`` of the given one.\n - If the set of classes from this ``LocalDataset`` differs from the set of classes\n from the given one AND ``extend_classes`` is ``False``.\n \"\"\"\n if self.annotation_type != dataset.annotation_type:\n raise ValueError(\"Annotation type of both datasets should match\")\n if self.classes != dataset.classes and not extend_classes:\n raise ValueError(\n f\"Operation dataset_a + dataset_b could not be computed: classes \"\n f\"should match. Use flag extend_classes=True to combine both lists \"\n f\"of classes.\"\n )\n self.classes = list(set(self.classes).union(set(dataset.classes)))\n\n self.original_images_path = self.images_path\n self.images_path += dataset.images_path\n self.original_annotations_path = self.annotations_path\n self.annotations_path += dataset.annotations_path\n return self\n\n def get_image(self, index: int) -> PILImage.Image:\n \"\"\"\n Returns the correspoding ``PILImage.Image``.\n\n Parameters\n ----------\n index : int\n The index of the image in this ``LocalDataset``.\n\n Returns\n -------\n PILImage.Image\n The image.\n \"\"\"\n return load_pil_image(self.images_path[index])\n\n def get_image_path(self, index: int) -> Path:\n \"\"\"\n Returns the path of the image with the given index.\n\n Parameters\n ----------\n index : int\n The index of the image in this ``LocalDataset``.\n\n Returns\n -------\n Path\n The ``Path`` of the image.\n \"\"\"\n return self.images_path[index]\n\n def parse_json(self, index: int) -> Dict[str, Any]:\n \"\"\"\n Load an annotation and filter out the extra classes according to what is\n specified in ``self.classes`` and the ``annotation_type``.\n\n Parameters\n ----------\n index : int\n Index of the annotation to read.\n\n Returns\n -------\n Dict[str, Any]\n A dictionary containing the index and the filtered annotation.\n \"\"\"\n with self.annotations_path[index].open() as f:\n data = json.load(f)\n # Filter out unused classes and annotations of a different type\n annotations = data[\"annotations\"]\n if self.classes is not None:\n annotations = [a for a in annotations if a[\"name\"] in self.classes and self.annotation_type in a]\n return {\n \"image_id\": index,\n \"image_path\": str(self.images_path[index]),\n \"height\": data[\"image\"][\"height\"],\n \"width\": data[\"image\"][\"width\"],\n \"annotations\": annotations,\n }\n\n def measure_mean_std(self, multi_threaded: bool = True) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Computes mean and std of trained images, given the train loader.\n\n Parameters\n ----------\n multi_threaded : bool, default: True\n Uses multiprocessing to download the dataset in parallel.\n\n Returns\n -------\n mean : ndarray[double]\n Mean value (for each channel) of all pixels of the images in the input folder.\n std : ndarray[double]\n Standard deviation (for each channel) of all pixels of the images in the input folder.\n \"\"\"\n if multi_threaded:\n # Set up a pool of workers\n with mp.Pool(mp.cpu_count()) as pool:\n # Online mean\n results = pool.map(self._return_mean, self.images_path)\n mean = np.sum(np.array(results), axis=0) / len(self.images_path)\n # Online image_classification deviation\n results = pool.starmap(self._return_std, [[item, mean] for item in self.images_path])\n std_sum = np.sum(np.array([item[0] for item in results]), axis=0)\n total_pixel_count = np.sum(np.array([item[1] for item in results]))\n std = np.sqrt(std_sum / total_pixel_count)\n # Shut down the pool\n pool.close()\n pool.join()\n return mean, std\n else:\n # Online mean\n results = [self._return_mean(f) for f in self.images_path]\n mean = np.sum(np.array(results), axis=0) / len(self.images_path)\n # Online image_classification deviation\n results = [self._return_std(f, mean) for f in self.images_path]\n std_sum = np.sum(np.array([item[0] for item in results]), axis=0)\n total_pixel_count = np.sum(np.array([item[1] for item in results]))\n std = np.sqrt(std_sum / total_pixel_count)\n return mean, std\n\n @staticmethod\n def _compute_weights(labels: List[int]) -> np.ndarray:\n \"\"\"\n Given an array of labels computes the weights normalized.\n\n Parameters\n ----------\n labels : List[int]\n Array of labels.\n\n Returns\n -------\n ndarray[float]\n Array of weights (one for each unique class) which are the inverse of their frequency.\n \"\"\"\n class_support: np.ndarray = np.unique(labels, return_counts=True)[1]\n class_frequencies = class_support / len(labels)\n # Class weights are the inverse of the class frequencies\n class_weights = 1 / class_frequencies\n # Normalize vector to sum up to 1.0 (in case the Loss function does not do it)\n class_weights /= class_weights.sum()\n return class_weights\n\n # Loads an image with Pillow and returns the channel wise means of the image.\n @staticmethod\n def _return_mean(image_path: Path) -> np.ndarray:\n img = np.array(load_pil_image(image_path))\n mean = np.array([np.mean(img[:, :, 0]), np.mean(img[:, :, 1]), np.mean(img[:, :, 2])])\n return mean / 255.0\n\n # Loads an image with OpenCV and returns the channel wise std of the image.\n @staticmethod\n def _return_std(image_path: Path, mean: np.ndarray) -> Tuple[np.ndarray, float]:\n img = np.array(load_pil_image(image_path)) / 255.0\n m2 = np.square(np.array([img[:, :, 0] - mean[0], img[:, :, 1] - mean[1], img[:, :, 2] - mean[2]]))\n return np.sum(np.sum(m2, axis=1), 1), m2.size / 3.0\n\n def __getitem__(self, index: int):\n img = load_pil_image(self.images_path[index])\n target = self.parse_json(index)\n return img, target\n\n def __len__(self):\n return len(self.images_path)\n\n def __str__(self):\n return (\n f\"{self.__class__.__name__}():\\n\"\n f\" Root: {self.dataset_path}\\n\"\n f\" Number of images: {len(self.images_path)}\\n\"\n f\" Number of classes: {len(self.classes)}\"\n )\n\n\ndef build_stems(\n release_path: Path,\n annotations_dir: Path,\n annotation_type: str,\n split: str,\n partition: Optional[str] = None,\n split_type: str = \"random\",\n) -> Iterator[str]:\n \"\"\"\n Builds the stems for the given release with the given annotations as base.\n\n Parameters\n ----------\n release_path : Path\n The path of the ``Release`` saved locally.\n annotations_dir : Path\n The path for a directory where annotations.\n annotation_type : str\n The type of the annotations.\n split : str\n The split name.\n partition : Optional[str], default: None\n How to partition files. If no partition is specified, then it takes all the json files in\n the annotations directory.\n The resulting generator prepends parent directories relative to the main annotation\n directory.\n\n E.g.: ``[\"annotations/test/1.json\", \"annotations/2.json\", \"annotations/test/2/3.json\"]``:\n\n - annotations/test/1\n - annotations/2\n - annotations/test/2/3\n split_type str, default: \"random\"\n The type of split. Can be ``\"random\"`` or ``\"stratified\"``.\n\n Returns\n -------\n Iterator[str]\n An iterator with the path for the stem files.\n\n Raises\n ------\n ValueError\n If the provided ``split_type`` is invalid.\n\n FileNotFoundError\n If no dataset partitions are found.\n \"\"\"\n\n if partition is None:\n return (str(e.relative_to(annotations_dir).parent / e.stem) for e in sorted(annotations_dir.glob(\"**/*.json\")))\n\n if split_type == \"random\":\n split_filename = f\"{split_type}_{partition}.txt\"\n elif split_type == \"stratified\":\n split_filename = f\"{split_type}_{annotation_type}_{partition}.txt\"\n else:\n raise ValueError(f'Unknown split type \"{split_type}\"')\n\n split_path = release_path / \"lists\" / split / split_filename\n if split_path.is_file():\n return (e.strip(\"\\n\\r\") for e in split_path.open())\n\n raise FileNotFoundError(\n f\"could not find a dataset partition. \"\n f\"Split the dataset using `split_dataset()` from `darwin.dataset.split_manager`\"\n )\n"
] |
[
[
"numpy.sqrt",
"numpy.unique",
"numpy.mean",
"numpy.array",
"numpy.sum"
]
] |
thlautenschlaeger/sds
|
[
"710e7c6b1b15afd0476b6f0f60c03415571bebeb",
"710e7c6b1b15afd0476b6f0f60c03415571bebeb"
] |
[
"evaluation/l4dc2020/pendulum_bayesian/pendulum_bayesian_compare.py",
"sds_numpy/utils.py"
] |
[
"import torch\nimport numpy as np\nimport numpy.random as npr\n\nfrom sds_numpy import rARHMM, ARHMM\nfrom sds_bayesian_numpy.vbrarhmm import VBrARHMM\nfrom sds_bayesian_numpy.vbarhmm import VBARHMM\nfrom sds_bayesian_numpy.vbhmm import VBHMM\nfrom sds_numpy.utils import sample_env\n\n# from reg.gp import DynamicMultiTaskGPRegressor\nfrom reg.nn import DynamicNNRegressor\nfrom reg.nn import DynamicRNNRegressor\nfrom reg.nn import DynamicLSTMRegressor\n\nimport random\n\nimport joblib\nfrom joblib import Parallel, delayed\nnb_cores = joblib.cpu_count()\n\nfrom matplotlib import rc\n\n\nrc('lines', **{'linewidth': 1})\nrc('text', usetex=True)\n\n\ndef beautify(ax):\n ax.set_frame_on(True)\n ax.minorticks_on()\n\n ax.grid(True)\n ax.grid(linestyle=':')\n\n ax.tick_params(which='both', direction='in',\n bottom=True, labelbottom=True,\n top=True, labeltop=False,\n right=True, labelright=False,\n left=True, labelleft=True)\n\n ax.tick_params(which='major', length=6)\n ax.tick_params(which='minor', length=3)\n\n ax.autoscale(tight=True)\n # ax.set_aspect('equal')\n\n if ax.get_legend():\n ax.legend(loc='best')\n\n return ax\n\n\ndef parallel_hmm_fit(obs, act, options, nb_jobs):\n\n def fit_arhmm_job(args):\n obs, act, options = args\n\n rarhmm = VBHMM(n_states=options['nb_states'],\n obs=obs, act=act,\n init_prior=options['init_prior'],\n obs_prior=options['obs_prior'],\n trans_prior=options['trans_prior'])\n\n # if options['initialize']:\n # rarhmm.initialize(obs, act)\n\n rarhmm.em(obs=obs, act=act,\n n_iter=30, prec=1e-4, verbose=True,\n obs_mstep_kwargs=options['obs_mstep_kwargs'],\n trans_mstep_kwargs=options['trans_mstep_kwargs'])\n\n return rarhmm\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, options)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n return Parallel(nb_jobs, verbose=10, backend='loky')\\\n (map(delayed(fit_arhmm_job), args))\n\n\ndef parallel_hmm_test(models, obs, act, horizon):\n\n def test_arhmm_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon=horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n res = Parallel(len(models), verbose=10, backend='loky')\\\n (map(delayed(test_arhmm_job), args))\n\n return list(map(list, zip(*res)))\n\n\ndef parallel_arhmm_fit(obs, act, options, nb_jobs):\n\n def fit_arhmm_job(args):\n obs, act, options = args\n\n rarhmm = VBARHMM(n_states=options['nb_states'],\n obs=obs, act=act,\n init_prior=options['init_prior'],\n obs_prior=options['obs_prior'],\n trans_prior=options['trans_prior'])\n\n # if options['initialize']:\n # rarhmm.initialize(obs, act)\n\n rarhmm.em(obs=obs, act=act,\n n_iter=30, prec=1e-4, verbose=True,\n obs_mstep_kwargs=options['obs_mstep_kwargs'],\n trans_mstep_kwargs=options['trans_mstep_kwargs'])\n\n return rarhmm\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, options)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n return Parallel(nb_jobs, verbose=10, backend='loky')\\\n (map(delayed(fit_arhmm_job), args))\n\n\ndef parallel_arhmm_test(models, obs, act, horizon):\n\n def test_arhmm_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon=horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n res = Parallel(len(models), verbose=10, backend='loky')\\\n (map(delayed(test_arhmm_job), args))\n\n return list(map(list, zip(*res)))\n\n\ndef parallel_rarhmm_fit(obs, act, options, nb_jobs):\n\n def fit_rarhmm_job(args):\n obs, act, options = args\n\n rarhmm = VBrARHMM(n_states=options['nb_states'],\n obs=obs, act=act,\n init_prior=options['init_prior'],\n obs_prior=options['obs_prior'],\n trans_type=options['trans_type'],\n trans_prior=options['trans_prior'],\n trans_kwargs=options['trans_kwargs'])\n\n # if options['initialize']:\n # rarhmm.initialize(obs, act)\n\n rarhmm.em(obs=obs, act=act,\n n_iter=30, prec=1e-4, verbose=True,\n obs_mstep_kwargs=options['obs_mstep_kwargs'],\n trans_mstep_kwargs=options['trans_mstep_kwargs'])\n\n return rarhmm\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, options)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n return Parallel(nb_jobs, verbose=10, backend='loky')\\\n (map(delayed(fit_rarhmm_job), args))\n\n\ndef parallel_rarhmm_test(models, obs, act, horizon):\n\n def test_rarhmm_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon=horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n res = Parallel(len(models), verbose=10, backend='loky')\\\n (map(delayed(test_rarhmm_job), args))\n\n return list(map(list, zip(*res)))\n\n\n# def parallel_gp_fit(obs, act, incremental, preprocess,\n# nb_iter, nb_jobs, gpu):\n#\n# def fit_gp_job(args):\n# obs, act, incremental, preprocess, nb_iter, gpu = args\n#\n# input = np.vstack([np.hstack((_x[:-1, :], _u[:-1, :]))\n# for _x, _u in zip(obs, act)])\n# if incremental:\n# target = np.vstack([_x[1:, :] - _x[:-1, :] for _x in obs])\n# else:\n# target = np.vstack([_x[1:, :] for _x in obs])\n#\n# gp = DynamicMultiTaskGPRegressor(input_size=input.shape[-1],\n# target_size=target.shape[-1],\n# incremental=incremental,\n# device='gpu' if gpu else 'cpu')\n# gp.fit(target, input, nb_iter, preprocess=preprocess)\n#\n# return gp\n#\n# from sklearn.model_selection import ShuffleSplit\n# spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n#\n# obs_lists, act_lists = [], []\n# for idx, _ in spliter.split(np.arange(len(obs))):\n# obs_lists.append([obs[i] for i in idx])\n# act_lists.append([act[i] for i in idx])\n#\n# args = [(_obs, _act, incremental, preprocess, nb_iter, gpu)\n# for _obs, _act in zip(obs_lists, act_lists)]\n#\n# nb_threads = 6 if gpu else min(nb_jobs, nb_cores)\n# return Parallel(nb_threads, verbose=10, backend='loky')\\\n# (map(delayed(fit_gp_job), args))\n#\n#\n# def parallel_gp_test(models, obs, act, horizon, gpu):\n#\n# def test_gp_job(args):\n# model, obs, act, horizon = args\n# return model.kstep_mse(obs, act, horizon)\n#\n# args = [(model, obs, act, horizon) for model in models]\n#\n# nb_threads = 6 if gpu else len(models)\n# res = Parallel(nb_threads, verbose=10, backend='loky')\\\n# (map(delayed(test_gp_job), args))\n#\n# return list(map(list, zip(*res)))\n\n\ndef parallel_fnn_fit(obs, act, size, incremental, preprocess,\n nb_epochs, nb_jobs, gpu):\n\n def fit_fnn_job(args):\n obs, act, size, incremental, preprocess, nb_epochs, gpu = args\n\n input = np.vstack([np.hstack((_x[:-1, :], _u[:-1, :]))\n for _x, _u in zip(obs, act)])\n if incremental:\n target = np.vstack([_x[1:, :] - _x[:-1, :] for _x in obs])\n else:\n target = np.vstack([_x[1:, :] for _x in obs])\n\n fnn = DynamicNNRegressor([input.shape[-1], size, size, target.shape[-1]],\n nonlin='tanh', incremental=incremental,\n device='gpu' if gpu else 'cpu')\n fnn.fit(target, input, nb_epochs, batch_size=32, preprocess=preprocess)\n\n return fnn\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, size, incremental, preprocess, nb_epochs, gpu)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n nb_threads = 6 if gpu else min(nb_jobs, nb_cores)\n return Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(fit_fnn_job), args))\n\n\ndef parallel_fnn_test(models, obs, act, horizon, gpu):\n\n def test_fnn_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n nb_threads = 6 if gpu else len(models)\n res = Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(test_fnn_job), args))\n\n return list(map(list, zip(*res)))\n\n\ndef parallel_rnn_fit(obs, act, size, preprocess, nb_epochs, nb_jobs, gpu):\n\n def fit_rnn_job(args):\n obs, act, size, preprocess, nb_epochs, gpu = args\n\n input = np.stack((np.hstack((_obs[:-1, :], _act[:-1, :]))\n for _obs, _act in zip(obs, act)), axis=0)\n target = np.stack((_obs[1:, :] for _obs in obs), axis=0)\n\n input_size = input.shape[-1]\n target_size = target.shape[-1]\n\n rnn = DynamicRNNRegressor(input_size, target_size,\n hidden_size=size, nb_layers=2,\n nonlinearity='tanh',\n device='gpu' if gpu else 'cpu')\n rnn.fit(target, input, nb_epochs, preprocess=preprocess)\n\n return rnn\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, size, preprocess, nb_epochs, gpu)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n nb_threads = 6 if gpu else min(nb_jobs, nb_cores)\n return Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(fit_rnn_job), args))\n\n\ndef parallel_rnn_test(models, obs, act, horizon, gpu):\n\n def test_rnn_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n nb_threads = 6 if gpu else len(models)\n res = Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(test_rnn_job), args))\n\n return list(map(list, zip(*res)))\n\n\ndef parallel_lstm_fit(obs, act, size, preprocess, nb_epochs, nb_jobs, gpu):\n\n def fit_lstm_job(args):\n obs, act, size, preprocess, nb_epochs, gpu = args\n\n input = np.stack((np.hstack((_obs[:-1, :], _act[:-1, :]))\n for _obs, _act in zip(obs, act)), axis=0)\n target = np.stack((_obs[1:, :] for _obs in obs), axis=0)\n\n input_size = input.shape[-1]\n target_size = target.shape[-1]\n\n lstm = DynamicLSTMRegressor(input_size, target_size,\n hidden_size=size, nb_layers=2,\n device='gpu' if gpu else 'cpu')\n lstm.fit(target, input, nb_epochs, lr=0.1, preprocess=preprocess)\n\n return lstm\n\n from sklearn.model_selection import ShuffleSplit\n spliter = ShuffleSplit(n_splits=nb_jobs, train_size=0.4)\n\n obs_lists, act_lists = [], []\n for idx, _ in spliter.split(np.arange(len(obs))):\n obs_lists.append([obs[i] for i in idx])\n act_lists.append([act[i] for i in idx])\n\n args = [(_obs, _act, size, preprocess, nb_epochs, gpu)\n for _obs, _act in zip(obs_lists, act_lists)]\n\n nb_threads = 6 if gpu else min(nb_jobs, nb_cores)\n return Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(fit_lstm_job), args))\n\n\ndef parallel_lstm_test(models, obs, act, horizon, gpu):\n\n def test_lstm_job(args):\n model, obs, act, horizon = args\n return model.kstep_mse(obs, act, horizon)\n\n args = [(model, obs, act, horizon) for model in models]\n\n nb_threads = 6 if gpu else len(models)\n res = Parallel(nb_threads, verbose=10, backend='loky')\\\n (map(delayed(test_lstm_job), args))\n\n return list(map(list, zip(*res)))\n\n\nif __name__ == \"__main__\":\n\n import os\n import argparse\n\n import gym\n import sds_numpy\n\n parser = argparse.ArgumentParser(description='Compare SOTA Models on Pendulum')\n parser.add_argument('--env', help='environment observation', default='cart')\n parser.add_argument('--model', help='representation model', default='fnn')\n parser.add_argument('--nb_jobs', help='number of data splits', default=16, type=int)\n parser.add_argument('--incremental', help='approximate delta', action='store_true', default=False)\n parser.add_argument('--preprocess', help='whiten data', action='store_true', default=False)\n parser.add_argument('--nn_size', help='size of NN layer', default=64, type=int)\n parser.add_argument('--nb_states', help='number of linear components', default=7, type=int)\n parser.add_argument('--initialize', help='initialize HMM models', action='store_true', default=True)\n parser.add_argument('--no_init', help='do not initialize HMM models', dest='initialize', action='store_false')\n parser.add_argument('--gpu', help='use gpu', action='store_true', default=False)\n\n args = parser.parse_args()\n\n import json\n print(json.dumps(vars(args), indent=4))\n\n random.seed(1337)\n npr.seed(1337)\n torch.manual_seed(1337)\n torch.set_num_threads(1)\n\n model_string = str(args.model)\n\n if args.env == 'cart':\n env = gym.make('Pendulum-ID-v1')\n elif args.env == 'polar':\n env = gym.make('Pendulum-ID-v0')\n else:\n raise NotImplementedError\n\n env._max_episode_steps = 5000\n env.unwrapped._dt = 0.01\n env.unwrapped._sigma = 1e-4\n env.seed(1337)\n\n nb_train_rollouts, nb_train_steps = 25, 250\n nb_test_rollouts, nb_test_steps = 5, 100\n\n hr = [1, 5, 10, 15, 20, 25]\n\n train_obs, train_act = sample_env(env, nb_train_rollouts, nb_train_steps)\n test_obs, test_act = sample_env(env, nb_test_rollouts, nb_test_steps)\n\n k, k_mse_avg, k_mse_std = [], [], []\n k_smse_avg, k_smse_std = [], []\n k_evar_avg, k_evar_std = [], []\n\n if args.model == 'hmm':\n # fit hmm\n init_prior = {'omega0': np.ones(args.nb_states) / args.nb_states}\n obs_prior = {'W0': np.eye(env.dm_obs),\n 'nu0': env.dm_obs + 2,\n 'm0': np.zeros(env.dm_obs),\n # 'm0': np.random.random(dm_obs),\n 'beta0': 0.05,\n 'P0': np.eye(env.dm_obs),\n 'eta0': env.dm_obs + 2,\n 'K0': np.eye((env.dm_obs + env.dm_act) + 1), # * 0.25,\n 'M0': np.zeros((env.dm_obs, (env.dm_obs + env.dm_act) + 1))\n # 'M0': np.random.multivariate_normal(np.zeros(dm_obs + dm_act + 1), np.eye(dm_obs + dm_act + 1), dm_obs)\n }\n\n obs_mstep_kwargs = {'use_prior': True}\n\n trans_type = 'bayesian_neural'\n trans_prior = {'l2_penalty': 1e-32, 'alpha': 1, 'kappa': 1, 'omega0': np.ones((args.nb_states, args.nb_states)) / args.nb_states}\n trans_mstep_kwargs = {'n_iter': 50, 'batch_size': 128, 'lr': 5e-4}\n\n if args.env == 'cart':\n trans_kwargs = {'hidden_neurons': (24,),\n 'norm': {'mean': np.array([0., 0., 0., 0.]),\n 'std': np.array([1., 1., 8., 2.5])},\n 'lr': 5e-3}\n elif args.env == 'polar':\n trans_kwargs = {'hidden_layer_sizes': (24,),\n 'norm': {'mean': np.array([0., 0., 0.]),\n 'std': np.array([np.pi, 8., 2.5])}}\n\n options = {'dm_obs': env.dm_obs, 'dm_act': env.dm_act, 'nb_states': args.nb_states,\n 'obs_prior': obs_prior, 'obs_mstep_kwargs': obs_mstep_kwargs,\n 'trans_prior': trans_prior,\n 'trans_kwargs': trans_kwargs, 'trans_mstep_kwargs': trans_mstep_kwargs,\n 'initialize': args.initialize, 'init_prior': init_prior}\n\n rarhmms = parallel_hmm_fit(obs=train_obs, act=train_act,\n options=options, nb_jobs=args.nb_jobs)\n\n model_string = model_string + '_' + str(args.nb_states)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_hmm_test(rarhmms, test_obs, test_act, int(h))\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n if args.model == 'arhmm':\n # fit rarhmm\n init_prior = {'omega0': np.ones(args.nb_states) / args.nb_states}\n obs_prior = {'W0': np.eye(env.dm_obs),\n 'nu0': env.dm_obs + 2,\n 'm0': np.zeros(env.dm_obs),\n # 'm0': np.random.random(dm_obs),\n 'beta0': 0.05,\n 'P0': np.eye(env.dm_obs),\n 'eta0': env.dm_obs + 2,\n 'K0': np.eye((env.dm_obs + env.dm_act) + 1), # * 0.25,\n 'M0': np.zeros((env.dm_obs, (env.dm_obs + env.dm_act) + 1))\n # 'M0': np.random.multivariate_normal(np.zeros(dm_obs + dm_act + 1), np.eye(dm_obs + dm_act + 1), dm_obs)\n }\n\n obs_mstep_kwargs = {'use_prior': True}\n\n trans_type = 'neural'\n trans_prior = {'l2_penalty': 1e-32, 'alpha': 1, 'kappa': 1, 'omega0': np.ones((args.nb_states, args.nb_states)) / args.nb_states}\n trans_mstep_kwargs = {'n_iter': 50, 'batch_size': 128, 'lr': 5e-4}\n\n if args.env == 'cart':\n trans_kwargs = {'hidden_neurons': (24,),\n 'norm': {'mean': np.array([0., 0., 0., 0.]),\n 'std': np.array([1., 1., 8., 2.5])},\n 'lr': 5e-3}\n elif args.env == 'polar':\n trans_kwargs = {'hidden_layer_sizes': (24,),\n 'norm': {'mean': np.array([0., 0., 0.]),\n 'std': np.array([np.pi, 8., 2.5])}}\n\n options = {'dm_obs': env.dm_obs, 'dm_act': env.dm_act, 'nb_states': args.nb_states,\n 'obs_prior': obs_prior, 'obs_mstep_kwargs': obs_mstep_kwargs,\n 'trans_prior': trans_prior,\n 'trans_kwargs': trans_kwargs, 'trans_mstep_kwargs': trans_mstep_kwargs,\n 'initialize': args.initialize, 'init_prior': init_prior}\n\n rarhmms = parallel_arhmm_fit(obs=train_obs, act=train_act,\n options=options, nb_jobs=args.nb_jobs)\n\n model_string = model_string + '_' + str(args.nb_states)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_arhmm_test(rarhmms, test_obs, test_act, int(h))\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n if args.model == 'rarhmm':\n # fit rarhmm\n init_prior = {'omega0': np.ones(args.nb_states) / args.nb_states}\n obs_prior = {'W0': np.eye(env.dm_obs),\n 'nu0': env.dm_obs + 2,\n 'm0': np.zeros(env.dm_obs),\n # 'm0': np.random.random(dm_obs),\n 'beta0': 0.05,\n 'P0': np.eye(env.dm_obs),\n 'eta0': env.dm_obs + 2,\n 'K0': np.eye((env.dm_obs + env.dm_act) + 1), # * 0.25,\n 'M0': np.zeros((env.dm_obs, (env.dm_obs + env.dm_act) + 1))\n # 'M0': np.random.multivariate_normal(np.zeros(dm_obs + dm_act + 1), np.eye(dm_obs + dm_act + 1), dm_obs)\n }\n\n obs_mstep_kwargs = {'use_prior': True}\n\n trans_type = 'bayes_neural'\n trans_prior = {'l2_penalty': 1e-32, 'alpha': 1, 'kappa': 1, 'omega0': np.ones((args.nb_states, args.nb_states)) / args.nb_states}\n trans_mstep_kwargs = {'n_iter': 50, 'batch_size': 128, 'lr': 5e-4}\n\n if args.env == 'cart':\n trans_kwargs = {'hidden_neurons': (24,),\n 'norm': {'mean': np.array([0., 0., 0., 0.]),\n 'std': np.array([1., 1., 8., 2.5])},\n 'lr': 5e-4}\n elif args.env == 'polar':\n trans_kwargs = {'hidden_layer_sizes': (24,),\n 'norm': {'mean': np.array([0., 0., 0.]),\n 'std': np.array([np.pi, 8., 2.5])}}\n else:\n raise NotImplementedError\n\n options = {'dm_obs': env.dm_obs, 'dm_act': env.dm_act, 'nb_states': args.nb_states,\n 'obs_prior': obs_prior, 'obs_mstep_kwargs': obs_mstep_kwargs,\n 'trans_type': trans_type, 'trans_prior': trans_prior,\n 'trans_kwargs': trans_kwargs, 'trans_mstep_kwargs': trans_mstep_kwargs,\n 'initialize': args.initialize, 'init_prior': init_prior}\n\n rarhmms = parallel_rarhmm_fit(obs=train_obs, act=train_act,\n options=options, nb_jobs=args.nb_jobs)\n\n model_string = model_string + '_' + str(args.nb_states)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_rarhmm_test(rarhmms, test_obs, test_act, int(h))\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n # elif args.model == 'gp':\n # # fit gp\n # gps = parallel_gp_fit(obs=train_obs, act=train_act,\n # nb_iter=75, nb_jobs=args.nb_jobs,\n # incremental=args.incremental,\n # preprocess=args.preprocess,\n # gpu=args.gpu)\n #\n # for h in hr:\n # print(\"Horizon: \", h)\n # mse, smse, evar = parallel_gp_test(gps, test_obs, test_act,\n # int(h), args.gpu)\n #\n # k_mse_avg.append(np.mean(mse))\n # k_mse_std.append(np.std(mse))\n #\n # k_smse_avg.append(np.mean(smse))\n # k_smse_std.append(np.std(smse))\n #\n # k_evar_avg.append(np.mean(evar))\n # k_evar_std.append(np.std(evar))\n #\n # k.append(h)\n\n elif args.model == 'fnn':\n # fit fnn\n fnns = parallel_fnn_fit(obs=train_obs, act=train_act,\n size=args.nn_size, incremental=args.incremental,\n preprocess=args.preprocess, nb_epochs=1000,\n nb_jobs=args.nb_jobs, gpu=args.gpu)\n\n model_string = model_string + '_' + str(args.nn_size)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_fnn_test(fnns, test_obs, test_act,\n int(h), args.gpu)\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n elif args.model == 'rnn':\n # fit rnn\n rnns = parallel_rnn_fit(obs=train_obs, act=train_act,\n size=args.nn_size, preprocess=args.preprocess,\n nb_epochs=10000, nb_jobs=args.nb_jobs,\n gpu=args.gpu)\n\n model_string = model_string + '_' + str(args.nn_size)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_rnn_test(rnns, test_obs, test_act,\n int(h), args.gpu)\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n elif args.model == 'lstm':\n # fit lstm\n lstms = parallel_lstm_fit(obs=train_obs, act=train_act,\n size=args.nn_size, preprocess=args.preprocess,\n nb_epochs=100, nb_jobs=args.nb_jobs,\n gpu=args.gpu)\n\n model_string = model_string + '_' + str(args.nn_size)\n\n for h in hr:\n print(\"Horizon: \", h)\n mse, smse, evar = parallel_lstm_test(lstms, test_obs, test_act,\n int(h), args.gpu)\n\n k_mse_avg.append(np.mean(mse))\n k_mse_std.append(np.std(mse))\n\n k_smse_avg.append(np.mean(smse))\n k_smse_std.append(np.std(smse))\n\n k_evar_avg.append(np.mean(evar))\n k_evar_std.append(np.std(evar))\n\n k.append(h)\n\n import matplotlib.pyplot as plt\n from tikzplotlib import save\n\n plt.figure()\n plt.errorbar(np.array(k), np.array(k_mse_avg),\n yerr=np.array(k_mse_std),\n fmt='-o', capsize=7, markersize=5)\n ax = plt.gca()\n ax = beautify(ax)\n\n save(str(args.env) + \"_pendulum_\" + str(model_string) + \"_mse.tex\")\n plt.close()\n\n plt.figure()\n plt.errorbar(np.array(k), np.array(k_smse_avg),\n yerr=np.array(k_smse_std),\n fmt='-o', capsize=7, markersize=5)\n ax = plt.gca()\n ax = beautify(ax)\n\n save(str(args.env) + \"_pendulum_\" + str(model_string) + \"_smse.tex\")\n plt.close()\n\n plt.figure()\n plt.errorbar(np.array(k), np.array(k_evar_avg),\n yerr=np.array(k_evar_std),\n fmt='-o', capsize=7, markersize=5)\n ax = plt.gca()\n ax = beautify(ax)\n plt.show()\n\n save(str(args.env) + \"_pendulum_\" + str(model_string) + \"_evar.tex\")\n plt.close()\n",
"import numpy as np\nimport numpy.random as npr\n\nfrom scipy.linalg import block_diag\n\nfrom scipy.optimize import linear_sum_assignment\n\nfrom functools import lru_cache\nfrom functools import wraps\n\nimport torch\n\n\ndef brownian(x0, n, dt, delta, out=None):\n\n x0 = np.asarray(x0)\n\n # For each element of x0, generate a sample of n numbers from a\n # normal distribution.\n r = npr.randn(x0.shape[0], n) * delta * np.sqrt(dt)\n\n # If `out` was not given, create an output array.\n if out is None:\n out = np.empty(r.shape)\n\n # This computes the Brownian motion by forming the cumulative sum of\n # the random samples.\n np.cumsum(r, axis=-1, out=out)\n\n # Add the initial condition.\n out += np.expand_dims(x0, axis=-1)\n\n return np.reshape(out, x0.shape[0])\n\n\ndef sample_env(env, nb_rollouts, nb_steps,\n ctl=None, noise_std=0.1,\n apply_limit=True):\n obs, act = [], []\n\n dm_obs = env.observation_space.shape[0]\n dm_act = env.action_space.shape[0]\n\n ulim = env.action_space.high\n\n for n in range(nb_rollouts):\n _obs = np.zeros((nb_steps, dm_obs))\n _act = np.zeros((nb_steps, dm_act))\n\n x = env.reset()\n\n for t in range(nb_steps):\n if ctl is None:\n # unifrom distribution\n u = np.random.uniform(-ulim, ulim)\n else:\n u = ctl(x)\n u = u + noise_std * npr.randn(1, )\n\n if apply_limit:\n u = np.clip(u, -ulim, ulim)\n\n _obs[t, :] = x\n _act[t, :] = u\n\n x, r, _, _ = env.step(u)\n\n obs.append(_obs)\n act.append(_act)\n\n return obs, act\n\n\n# list of dicts to dict of lists\ndef lod2dol(*dicts):\n d = {}\n for dict in dicts:\n for key in dict:\n try:\n d[key].append(dict[key])\n except KeyError:\n d[key] = [dict[key]]\n return d\n\n\ndef ensure_args_are_viable_lists(f):\n def wrapper(self, obs, act=None, **kwargs):\n assert obs is not None\n obs = [np.atleast_2d(obs)] if not isinstance(obs, (list, tuple)) else obs\n\n if act is None:\n act = []\n for _obs in obs:\n act.append(np.zeros((_obs.shape[0], self.dm_act)))\n\n act = [np.atleast_2d(act)] if not isinstance(act, (list, tuple)) else act\n\n return f(self, obs, act, **kwargs)\n return wrapper\n\n\ndef np_cache(function):\n @lru_cache()\n def cached_wrapper(hashable_array, *args):\n array = np.array(hashable_array)\n return function(array, *args)\n\n @wraps(function)\n def wrapper(array, *args):\n array_tuple = tuple(zip(*array.T.tolist()))\n return cached_wrapper(array_tuple, *args)\n\n # copy lru_cache attributes over too\n wrapper.cache_info = cached_wrapper.cache_info\n wrapper.cache_clear = cached_wrapper.cache_clear\n\n return wrapper\n\n\n# stack ar observations and controls\n@np_cache\ndef stack(x, shift):\n _hr = len(x) - shift\n _x = np.vstack([np.hstack([x[t + l] for l in range(shift + 1)])\n for t in range(_hr)])\n return np.squeeze(_x)\n\n\ndef flatten_to_dim(X, d):\n assert X.ndim >= d\n assert d > 0\n return np.reshape(X[None, ...], (-1,) + X.shape[-d:])\n\n\ndef state_overlap(z1, z2, K1=None, K2=None):\n assert z1.dtype == int and z2.dtype == int\n assert z1.shape == z2.shape\n assert z1.min() >= 0 and z2.min() >= 0\n\n K1 = z1.max() + 1 if K1 is None else K1\n K2 = z2.max() + 1 if K2 is None else K2\n\n overlap = np.zeros((K1, K2))\n for k1 in range(K1):\n for k2 in range(K2):\n overlap[k1, k2] = np.sum((z1 == k1) & (z2 == k2))\n return overlap\n\n\ndef permutation(z1, z2, K1=None, K2=None):\n overlap = state_overlap(z1, z2, K1=K1, K2=K2)\n K1, K2 = overlap.shape\n\n tmp, perm = linear_sum_assignment(-overlap)\n assert np.all(tmp == np.arange(K1)), \"All indices should have been matched!\"\n\n # Pad permutation if K1 < K2\n if K1 < K2:\n unused = np.array(list(set(np.arange(K2)) - set(perm)))\n perm = np.concatenate((perm, unused))\n\n return perm\n\n\ndef random_rotation(n, theta=None):\n if theta is None:\n # Sample a random, slow rotation\n theta = 0.5 * np.pi * npr.rand()\n\n if n == 1:\n return npr.rand() * np.eye(1)\n\n rot = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n out = np.zeros((n, n))\n out[:2, :2] = rot\n q = np.linalg.qr(npr.randn(n, n))[0]\n return q.dot(out).dot(q.T)\n\n\ndef linear_regression(Xs, ys, weights=None,\n mu0=0., sigma0=1e32,\n nu0=0, psi0=1e-32,\n fit_intercept=True):\n\n Xs = Xs if isinstance(Xs, (list, tuple)) else [Xs]\n ys = ys if isinstance(ys, (list, tuple)) else [ys]\n assert len(Xs) == len(ys)\n\n D = Xs[0].shape[1]\n P = ys[0].shape[1]\n assert all([X.shape[1] == D for X in Xs])\n assert all([y.shape[1] == P for y in ys])\n assert all([X.shape[0] == y.shape[0] for X, y in zip(Xs, ys)])\n\n mu0 = mu0 * np.ones((P, D))\n sigma0 = sigma0 * np.eye(D)\n\n # Make sure the weights are the weights\n if weights is not None:\n weights = weights if isinstance(weights, (list, tuple)) else [weights]\n else:\n weights = [np.ones(X.shape[0]) for X in Xs]\n\n # Add weak prior on intercept\n if fit_intercept:\n mu0 = np.column_stack((mu0, np.zeros(P)))\n sigma0 = block_diag(sigma0, np.eye(1))\n\n # Compute the posterior\n J = np.linalg.inv(sigma0)\n h = np.dot(J, mu0.T)\n\n for X, y, weight in zip(Xs, ys, weights):\n X = np.column_stack((X, np.ones(X.shape[0]))) if fit_intercept else X\n J += np.dot(X.T * weight, X)\n h += np.dot(X.T * weight, y)\n\n # Solve for the MAP estimate\n # W = np.linalg.solve(J, h).T\n # W = np.dot(h.T, np.linalg.pinv(J))\n WT, _, _, _ = np.linalg.lstsq(J, h, rcond=None)\n W = WT.T\n\n if fit_intercept:\n W, b = W[:, :-1], W[:, -1]\n else:\n b = 0\n\n # Compute the residual and the posterior variance\n nu = nu0\n Psi = psi0 * np.eye(P)\n for X, y, weight in zip(Xs, ys, weights):\n yhat = np.dot(X, W.T) + b\n resid = y - yhat\n nu += np.sum(weight)\n tmp = np.einsum('t,ti,tj->ij', weight, resid, resid)\n # tmp = np.sum(weight[:, None, None] * resid[:, :, None] * resid[:, None, :], axis=0)\n # assert np.allclose(tmp1, tmp2)\n Psi += tmp\n\n # Get MAP estimate of posterior covariance\n Sigma = Psi / (nu + P + 1)\n if fit_intercept:\n return W, b, Sigma\n else:\n return W, Sigma\n\n\ndef to_float(arr, device=torch.device('cpu')):\n if isinstance(arr, np.ndarray):\n return torch.from_numpy(arr).float().to(device)\n elif isinstance(arr, torch.FloatTensor):\n return arr.to(device)\n else:\n raise arr\n\n\ndef np_float(arr):\n if isinstance(arr, torch.Tensor):\n return arr.detach().double().cpu().numpy()\n elif isinstance(arr, np.ndarray):\n return arr\n else:\n raise TypeError\n\n\ndef ensure_args_torch_floats(f):\n @wraps(f)\n def wrapper(self, *args, **kwargs):\n _args = []\n for arg in args:\n if isinstance(arg, list):\n print(self.device)\n _args.append([to_float(_arr, self.device) for _arr in arg])\n elif isinstance(arg, np.ndarray):\n _args.append(to_float(arg, self.device))\n else:\n _args.append(arg)\n\n return f(self, *_args, **kwargs)\n return wrapper\n\n\ndef ensure_res_numpy_floats(f):\n @wraps(f)\n def wrapper(self, *args, **kwargs):\n outputs = f(self, *args, **kwargs)\n\n _outputs = []\n for out in outputs:\n if isinstance(out, torch.Tensor):\n _outputs.append(np_float(out))\n elif isinstance(out, list):\n _outputs.append([np_float(x) for x in out])\n\n return _outputs\n return wrapper\n"
] |
[
[
"matplotlib.pyplot.gca",
"numpy.hstack",
"sklearn.model_selection.ShuffleSplit",
"numpy.random.seed",
"torch.manual_seed",
"numpy.vstack",
"numpy.eye",
"numpy.stack",
"numpy.ones",
"numpy.std",
"torch.set_num_threads",
"numpy.mean",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.rc",
"matplotlib.pyplot.figure"
],
[
"numpy.dot",
"numpy.expand_dims",
"numpy.sqrt",
"numpy.einsum",
"numpy.asarray",
"numpy.squeeze",
"numpy.cumsum",
"numpy.concatenate",
"numpy.random.randn",
"torch.device",
"scipy.optimize.linear_sum_assignment",
"numpy.clip",
"numpy.reshape",
"numpy.arange",
"numpy.eye",
"torch.from_numpy",
"numpy.sin",
"numpy.zeros",
"numpy.linalg.inv",
"numpy.linalg.lstsq",
"numpy.atleast_2d",
"numpy.random.rand",
"numpy.array",
"numpy.sum",
"numpy.cos",
"numpy.ones",
"numpy.random.uniform",
"numpy.empty"
]
] |
YoushaaMurhij/3d-tracking-approaches
|
[
"0fcb9d6d1ff9cc9bb637e8e988f510a80c04f695"
] |
[
"Probabilistic_Tracker/get_nuscenes_stats.py"
] |
[
"import os\nimport sys\n\nimport numpy as np\nfrom main import iou3d, convert_3dbox_to_8corner\nfrom sklearn.utils.linear_assignment_ import linear_assignment\n\nfrom nuscenes import NuScenes\nfrom nuscenes.eval.common.config import config_factory\nfrom nuscenes.eval.tracking.evaluate import TrackingEval\nfrom nuscenes.eval.detection.data_classes import DetectionConfig\nfrom nuscenes.eval.detection.data_classes import DetectionBox\nfrom nuscenes.eval.tracking.data_classes import TrackingBox\nfrom nuscenes.eval.common.loaders import load_prediction, load_gt, add_center_dist, filter_eval_boxes\nfrom nuscenes.eval.tracking.loaders import create_tracks\nfrom pyquaternion import Quaternion\n\nimport argparse\n\nNUSCENES_TRACKING_NAMES = [\n 'bicycle',\n 'bus',\n 'car',\n 'motorcycle',\n 'pedestrian',\n 'trailer',\n 'truck'\n]\n\ndef rotation_to_positive_z_angle(rotation):\n q = Quaternion(rotation)\n angle = q.angle if q.axis[2] > 0 else -q.angle\n return angle\n\ndef get_mean(tracks):\n '''\n Input:\n tracks: {scene_token: {t: [TrackingBox]}}\n '''\n print('len(tracks.keys()): ', len(tracks.keys()))\n\n # gt_trajectory_map to compute residual or velocity\n # tracking_name: {scene_token -> {tracking_id: {t_idx -> det_data}}\n # [h, w, l, x, y, z, yaw] #x_dot, y_dot, z_dot, yaw_dot]\n gt_trajectory_map = {tracking_name: {scene_token: {} for scene_token in tracks.keys()} for tracking_name in NUSCENES_TRACKING_NAMES}\n\n # store every detection data to compute mean and variance\n gt_box_data = {tracking_name: [] for tracking_name in NUSCENES_TRACKING_NAMES}\n\n for scene_token in tracks.keys():\n #print('scene_token: ', scene_token)\n #print('tracks[scene_token].keys(): ', tracks[scene_token].keys())\n for t_idx in range(len(tracks[scene_token].keys())):\n #print('t_idx: ', t_idx)\n t = sorted(tracks[scene_token].keys())[t_idx]\n for box_id in range(len(tracks[scene_token][t])):\n #print('box_id: ', box_id)\n box = tracks[scene_token][t][box_id]\n #print('box: ', box)\n \n if box.tracking_name not in NUSCENES_TRACKING_NAMES:\n continue\n # box: {'sample_token': '6a808b09e5f34d33ba1de76cc8dab423', 'translation': [2131.657, 1108.874, 3.453], 'size': [3.078, 6.558, 2.95], 'rotation': [0.8520240186812739, 0.0, 0.0, 0.5235026949216329], 'velocity': array([-0.01800415, 0.0100023 ]), 'ego_dist': 54.20556415873658, 'num_pts': 4, 'tracking_id': 'cbaabbf2a83a4177b2145ab1317e296e', 'tracking_name': 'truck', 'tracking_score': -1.0}\n # [h, w, l, x, y, z, ry, \n # x_t - x_{t-1}, ..., for [x,y,z,ry]\n # (x_t - x_{t-1}) - (x_{t-1} - x_{t-2}), ..., for [x,y,z,ry]\n box_data = np.array([\n box.size[2], box.size[0], box.size[1], \n box.translation[0], box.translation[1], box.translation[2],\n rotation_to_positive_z_angle(box.rotation),\n 0, 0, 0, 0, \n 0, 0, 0, 0])\n\n\n if box.tracking_id not in gt_trajectory_map[box.tracking_name][scene_token]:\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id] = {t_idx: box_data}\n else: \n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx] = box_data\n\n # if we can find the same object in the previous frame, get the velocity\n if box.tracking_id in gt_trajectory_map[box.tracking_name][scene_token] and t_idx-1 in gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id]:\n residual_vel = box_data[3:7] - gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][3:7]\n box_data[7:11] = residual_vel\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx] = box_data\n # back fill\n if gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][7] == 0:\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][7:11] = residual_vel\n\n # if we can find the same object in the previous two frames, get the acceleration\n if box.tracking_id in gt_trajectory_map[box.tracking_name][scene_token] and t_idx-2 in gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id]:\n residual_a = residual_vel - (gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][3:7] - gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-2][3:7])\n box_data[11:15] = residual_a\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx] = box_data\n # back fill\n if gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][11] == 0:\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-1][11:15] = residual_a\n if gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-2][11] == 0:\n gt_trajectory_map[box.tracking_name][scene_token][box.tracking_id][t_idx-2][11:15] = residual_a\n\n #print(det_data)\n gt_box_data[box.tracking_name].append(box_data)\n \n\n gt_box_data = {tracking_name: np.stack(gt_box_data[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n\n mean = {tracking_name: np.mean(gt_box_data[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n std = {tracking_name: np.std(gt_box_data[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n var = {tracking_name: np.var(gt_box_data[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n\n return mean, std, var\n\n\ndef matching_and_get_diff_stats(pred_boxes, gt_boxes, tracks_gt, matching_dist):\n '''\n For each sample token, find matches of pred_boxes and gt_boxes, then get stats.\n tracks_gt has the temporal order info for each sample_token\n '''\n\n\n diff = {tracking_name: [] for tracking_name in NUSCENES_TRACKING_NAMES} # [h, w, l, x, y, z, a]\n diff_vel = {tracking_name: [] for tracking_name in NUSCENES_TRACKING_NAMES} # [x_dot, y_dot, z_dot, a_dot]\n\n # similar to main.py class AB3DMOT update()\n reorder = [3, 4, 5, 6, 2, 1, 0]\n reorder_back = [6, 5, 4, 0, 1, 2, 3]\n\n for scene_token in tracks_gt.keys():\n #print('scene_token: ', scene_token)\n #print('tracks[scene_token].keys(): ', tracks[scene_token].keys())\n # {tracking_name: t_idx: tracking_id: det(7) }\n match_diff_t_map = {tracking_name: {} for tracking_name in NUSCENES_TRACKING_NAMES}\n for t_idx in range(len(tracks_gt[scene_token].keys())):\n #print('t_idx: ', t_idx)\n t = sorted(tracks_gt[scene_token].keys())[t_idx]\n #print(len(tracks_gt[scene_token][t]))\n if len(tracks_gt[scene_token][t]) == 0:\n continue\n box = tracks_gt[scene_token][t][0]\n sample_token = box.sample_token\n\n for tracking_name in NUSCENES_TRACKING_NAMES:\n \n #print('t: ', t)\n gt_all = [box for box in gt_boxes.boxes[sample_token] if box.tracking_name == tracking_name]\n if len(gt_all) == 0:\n continue\n gts = np.stack([np.array([\n box.size[2], box.size[0], box.size[1],\n box.translation[0], box.translation[1], box.translation[2],\n rotation_to_positive_z_angle(box.rotation)\n ]) for box in gt_all], axis=0)\n gts_ids = [box.tracking_id for box in gt_all]\n\n det_all = [box for box in pred_boxes.boxes[sample_token] if box.detection_name == tracking_name]\n if len(det_all) == 0:\n continue\n dets = np.stack([np.array([\n box.size[2], box.size[0], box.size[1],\n box.translation[0], box.translation[1], box.translation[2],\n rotation_to_positive_z_angle(box.rotation)\n ]) for box in det_all], axis=0)\n \n\n dets = dets[:, reorder]\n gts = gts[:, reorder]\n\n if matching_dist == '3d_iou':\n dets_8corner = [convert_3dbox_to_8corner(det_tmp) for det_tmp in dets]\n gts_8corner = [convert_3dbox_to_8corner(gt_tmp) for gt_tmp in gts]\n iou_matrix = np.zeros((len(dets_8corner),len(gts_8corner)),dtype=np.float32)\n for d,det in enumerate(dets_8corner):\n for g,gt in enumerate(gts_8corner):\n iou_matrix[d,g] = iou3d(det,gt)[0]\n #print('iou_matrix: ', iou_matrix)\n distance_matrix = -iou_matrix\n threshold = -0.1\n elif matching_dist == '2d_center':\n distance_matrix = np.zeros((dets.shape[0], gts.shape[0]),dtype=np.float32)\n for d in range(dets.shape[0]):\n for g in range(gts.shape[0]):\n distance_matrix[d][g] = np.sqrt((dets[d][0] - gts[g][0])**2 + (dets[d][1] - gts[g][1])**2) \n threshold = 2\n else:\n assert(False) \n\n matched_indices = linear_assignment(distance_matrix)\n #print('matched_indices: ', matched_indices)\n dets = dets[:, reorder_back]\n gts = gts[:, reorder_back]\n for pair_id in range(matched_indices.shape[0]):\n if distance_matrix[matched_indices[pair_id][0]][matched_indices[pair_id][1]] < threshold:\n diff_value = dets[matched_indices[pair_id][0]] - gts[matched_indices[pair_id][1]]\n diff[tracking_name].append(diff_value)\n gt_track_id = gts_ids[matched_indices[pair_id][1]]\n if t_idx not in match_diff_t_map[tracking_name]:\n match_diff_t_map[tracking_name][t_idx] = {gt_track_id: diff_value}\n else:\n match_diff_t_map[tracking_name][t_idx][gt_track_id] = diff_value\n # check if we have previous time_step's matching pair for current gt object\n #print('t: ', t)\n #print('len(match_diff_t_map): ', len(match_diff_t_map))\n if t_idx > 0 and t_idx-1 in match_diff_t_map[tracking_name] and gt_track_id in match_diff_t_map[tracking_name][t_idx-1]:\n diff_vel_value = diff_value - match_diff_t_map[tracking_name][t_idx-1][gt_track_id]\n diff_vel[tracking_name].append(diff_vel_value)\n\n\n\n diff = {tracking_name: np.stack(diff[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n mean = {tracking_name: np.mean(diff[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n std = {tracking_name: np.std(diff[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n var = {tracking_name: np.var(diff[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n \n diff_vel = {tracking_name: np.stack(diff_vel[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n mean_vel = {tracking_name: np.mean(diff_vel[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n std_vel = {tracking_name: np.std(diff_vel[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n var_vel = {tracking_name: np.var(diff_vel[tracking_name], axis=0) for tracking_name in NUSCENES_TRACKING_NAMES}\n\n return mean, std, var, mean_vel, std_vel, var_vel\n\nif __name__ == '__main__':\n # Settings.\n parser = argparse.ArgumentParser(description='Get nuScenes stats.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--eval_set', type=str, default='train',\n help='Which dataset split to evaluate on, train, val or test.')\n parser.add_argument('--config_path', type=str, default='',\n help='Path to the configuration file.'\n 'If no path given, the NIPS 2019 configuration will be used.')\n parser.add_argument('--verbose', type=int, default=1,\n help='Whether to print to stdout.')\n parser.add_argument('--matching_dist', type=str, default='2d_center',\n help='Which distance function for matching, 3d_iou or 2d_center.')\n args = parser.parse_args()\n\n eval_set_ = args.eval_set\n config_path = args.config_path\n verbose_ = bool(args.verbose)\n matching_dist = args.matching_dist\n\n if config_path == '':\n cfg_ = config_factory('tracking_nips_2019')\n else:\n with open(config_path, 'r') as _f:\n cfg_ = DetectionConfig.deserialize(json.load(_f))\n\n if 'train' in eval_set_:\n detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_train.json'\n data_root = '/juno/u/hkchiu/dataset/nuscenes/trainval'\n version='v1.0-trainval'\n elif 'val' in eval_set_:\n detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_val.json'\n data_root = '/juno/u/hkchiu/dataset/nuscenes/trainval'\n version='v1.0-trainval'\n elif 'test' in eval_set_:\n detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_test.json'\n data_root = '/juno/u/hkchiu/dataset/nuscenes/test'\n version='v1.0-test'\n\n nusc = NuScenes(version=version, dataroot=data_root, verbose=True)\n\n pred_boxes, _ = load_prediction(detection_file, 10000, DetectionBox)\n gt_boxes = load_gt(nusc, eval_set_, TrackingBox)\n\n assert set(pred_boxes.sample_tokens) == set(gt_boxes.sample_tokens), \\\n \"Samples in split don't match samples in predicted tracks.\"\n\n # Add center distances.\n pred_boxes = add_center_dist(nusc, pred_boxes)\n gt_boxes = add_center_dist(nusc, gt_boxes)\n\n \n print('len(pred_boxes.sample_tokens): ', len(pred_boxes.sample_tokens))\n print('len(gt_boxes.sample_tokens): ', len(gt_boxes.sample_tokens))\n\n tracks_gt = create_tracks(gt_boxes, nusc, eval_set_, gt=True)\n\n mean, std, var = get_mean(tracks_gt)\n print('GT: Global coordinate system')\n print('h, w, l, x, y, z, a, x_dot, y_dot, z_dot, a_dot, x_dot_dot, y_dot_dot, z_dot_dot, a_dot_dot')\n print('mean: ', mean)\n print('std: ', std)\n print('var: ', var)\n\n # for observation noise covariance\n mean, std, var, mean_vel, std_vel, var_vel = matching_and_get_diff_stats(pred_boxes, gt_boxes, tracks_gt, matching_dist)\n print('Diff: Global coordinate system')\n print('h, w, l, x, y, z, a')\n print('mean: ', mean)\n print('std: ', std)\n print('var: ', var)\n print('h_dot, w_dot, l_dot, x_dot, y_dot, z_dot, a_dot')\n print('mean_vel: ', mean_vel)\n print('std_vel: ', std_vel)\n print('var_vel: ', var_vel)\n\n"
] |
[
[
"sklearn.utils.linear_assignment_.linear_assignment",
"numpy.sqrt",
"numpy.stack",
"numpy.std",
"numpy.mean",
"numpy.var",
"numpy.zeros"
]
] |
letylu/bootcamp-bringing-ML-models-into-production-intermediary-jun-aug2021
|
[
"bdb3a8dfd5232bf6d999458c1e8cad1736469b32"
] |
[
"bootcamp/lesson3/blob_function/LRBlobTrigger/__init__.py"
] |
[
"import io\r\nimport logging\r\nimport joblib\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nimport azure.functions as func\r\nfrom azureml.core import Model\r\n\r\n\r\ndef main(inputBlob: func.InputStream, predictions: func.Out[str]):\r\n logging.info(\"Python blob trigger function processed blob\")\r\n\r\n #ws = Workspace.from_config() ya no se necesita y se quita de model_path y tampoco se importa\r\n\r\n model_path = Model.get_model_path('linear_regression')\r\n #model_path = Model.get_model_path('ridge')\r\n #model_path = os.path.join('..', 'models', \"linear_regression.pkl\")\r\n model = joblib.load(model_path)\r\n #logging.info(f\"{model}\")\r\n logging.info(\"model loaded\")\r\n\r\n\r\n data = pd.read_csv(io.BytesIO(inputBlob.read()), header=None, sep=',')\r\n logging.info(\"data loaded\")\r\n\r\n\r\n data_array = data.to_numpy()\r\n logging.info(\"data array created\")\r\n\r\n prediction = model.predict(data_array.reshape(1, -1))\r\n logging.info(\"predicted values\")\r\n\r\n result = np.array_str(prediction)\r\n logging.info(\"result\")\r\n\r\n predictions.set(result)"
] |
[
[
"numpy.array_str"
]
] |
detritus3872/kartothek
|
[
"e4155e4ec72decd6d5ee67d6258f7683cc690c01"
] |
[
"tests/core/test_index.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\nimport datetime\nimport logging\nimport pickle\nfrom itertools import permutations\n\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nimport pytest\nimport pytz\nfrom hypothesis import assume, given\nfrom pandas.testing import assert_series_equal\n\nfrom kartothek.core.index import ExplicitSecondaryIndex, IndexBase, merge_indices\nfrom kartothek.core.testing import get_numpy_array_strategy\n\n\n@pytest.mark.parametrize(\"inplace\", [True, False])\ndef test_index_update(inplace):\n original_index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]}\n )\n\n new_index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={1: [\"part_4\"], 4: [\"part_4\"]}\n )\n\n updated_index = original_index.update(new_index, inplace=inplace)\n\n expected_index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_2\", \"part_4\", \"part_1\"], 3: [\"part_3\"], 4: [\"part_4\"]},\n )\n assert updated_index == expected_index\n\n\n@pytest.mark.parametrize(\"inplace\", [True, False])\ndef test_storage_key_after_update(inplace):\n \"\"\"\n Assert that the storage key is not set after mutation of the index object\n \"\"\"\n original_index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]},\n index_storage_key=\"storage_key\",\n )\n updated_index = original_index.remove_partitions([], inplace=inplace)\n assert updated_index.index_storage_key == \"storage_key\"\n updated_index = original_index.remove_partitions([\"part_1\"], inplace=inplace)\n assert updated_index.index_storage_key is None\n\n original_index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]},\n index_storage_key=\"storage_key\",\n )\n updated_index = original_index.remove_values([], inplace=inplace)\n assert updated_index.index_storage_key == \"storage_key\"\n\n updated_index = original_index.remove_values([1], inplace=inplace)\n assert updated_index.index_storage_key is None\n\n original_index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]},\n index_storage_key=\"storage_key\",\n )\n updated_index = original_index.copy()\n assert updated_index.index_storage_key == \"storage_key\"\n updated_index = original_index.copy(column=\"something_different\")\n assert updated_index.index_storage_key is None\n\n\ndef test_eq_explicit():\n def assert_eq(a, b):\n assert a == b\n assert b == a\n assert not (a != b)\n assert not (b != a)\n\n def assert_ne(a, b):\n assert a != b\n assert b != a\n assert not (a == b)\n assert not (b == a)\n\n original_index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\"]},\n dtype=pa.int64(),\n index_storage_key=\"dataset_uuid/some_index.parquet\",\n )\n\n idx1 = original_index.copy()\n assert_eq(idx1, original_index)\n\n idx2 = original_index.copy()\n idx2.column = \"col2\"\n assert_ne(idx2, original_index)\n\n idx3 = original_index.copy()\n idx3.dtype = pa.uint64()\n assert_ne(idx3, original_index)\n\n idx4 = original_index.copy()\n idx4.index_dct = {1: [\"part_1\"], 2: [\"part_2\"]}\n assert_ne(idx4, original_index)\n\n idx5 = original_index.copy()\n idx5.index_dct = {1: [\"part_1\", \"part_2\"]}\n assert_ne(idx5, original_index)\n\n idx6 = original_index.copy()\n idx6.index_dct = {1: [\"part_2\"]}\n assert_ne(idx6, original_index)\n\n idx7 = original_index.copy()\n idx7.index_dct = {2: [\"part_1\"]}\n assert_ne(idx7, original_index)\n\n idx8 = original_index.copy()\n idx8.dtype = None\n assert_ne(idx8, original_index)\n\n idx9a = original_index.copy()\n idx9b = original_index.copy()\n idx9a.dtype = None\n idx9b.dtype = None\n assert_eq(idx9a, idx9b)\n\n\ndef test_index_update_wrong_col():\n original_index = ExplicitSecondaryIndex(column=\"col\", index_dct={1: [\"part_1\"]})\n\n new_index = ExplicitSecondaryIndex(column=\"another_col\", index_dct={1: [\"part_4\"]})\n with pytest.raises(ValueError) as e:\n original_index.update(new_index)\n assert (\n str(e.value)\n == \"Trying to update an index with the wrong column. Got `another_col` but expected `col`\"\n )\n\n\ndef test_index_empty():\n ExplicitSecondaryIndex(column=\"col\", index_dct={})\n\n\ndef test_index_no_source():\n with pytest.raises(ValueError) as e:\n ExplicitSecondaryIndex(column=\"col\")\n assert str(e.value) == \"No valid index source specified\"\n\n\n@pytest.mark.parametrize(\"inplace\", [True, False])\ndef test_index_remove_values(inplace):\n original_index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={1: [\"part_1\", \"part_2\"], 2: [\"part_1\"], 3: [\"part_3\"]}\n )\n new_index = original_index.remove_values([1, 2], inplace=inplace)\n expected_index = ExplicitSecondaryIndex(column=\"col\", index_dct={3: [\"part_3\"]})\n assert new_index == expected_index\n\n\n@pytest.mark.parametrize(\"inplace\", [True, False])\n@pytest.mark.parametrize(\n \"remove, expected\",\n [\n ([\"part_1\"], {1: [\"part_2\"], 3: [\"part_3\"]}),\n ([\"part_1\", \"part_2\"], {3: [\"part_3\"]}),\n ([\"part_1\", \"part_2\", \"part_3\"], {}),\n ],\n)\ndef test_index_remove_partitions(inplace, remove, expected):\n original_index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={1: [\"part_1\", \"part_2\"], 2: [\"part_1\"], 3: [\"part_3\"]}\n )\n for perm in permutations(remove):\n new_index = original_index.remove_partitions(perm, inplace=inplace)\n expected_index = ExplicitSecondaryIndex(\n column=\"col\", index_dct=expected, dtype=pa.int64()\n )\n assert new_index == expected_index\n\n\ndef test_index_store_roundtrip_explicit_key(store):\n storage_key = \"dataset_uuid/some_index.parquet\"\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]},\n index_storage_key=storage_key,\n dtype=pa.int64(),\n )\n key1 = index1.store(store, \"dataset_uuid\")\n\n index2 = ExplicitSecondaryIndex(column=\"col\", index_storage_key=key1).load(store)\n assert index1 == index2\n key2 = index2.store(store, \"dataset_uuid\")\n\n index3 = ExplicitSecondaryIndex(column=\"col\", index_storage_key=key2).load(store)\n assert index1 == index3\n assert index2 == index3\n\n\n@pytest.mark.parametrize(\"col\", [\"col\", \"foo/bar\", \"foo:bar\"])\ndef test_index_store_roundtrip_implicit_key(store, col):\n index1 = ExplicitSecondaryIndex(\n column=col, index_dct={1: [\"part_1\", \"part_2\"], 3: [\"part_3\"]}, dtype=pa.int64()\n )\n key1 = index1.store(store, \"dataset_uuid\")\n index1.index_storage_key = key1\n\n index2 = ExplicitSecondaryIndex(column=col, index_storage_key=key1).load(store)\n assert index1 == index2\n key2 = index2.store(store, \"dataset_uuid\")\n\n index3 = ExplicitSecondaryIndex(column=col, index_storage_key=key2).load(store)\n assert index1 == index3\n assert index2 == index3\n\n\ndef test_index_as_flat_series():\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 2: [\"part_1\"]},\n dtype=pa.int64(),\n )\n ser = index1.as_flat_series()\n expected = pd.Series(\n [\"part_1\", \"part_2\", \"part_1\"],\n index=pd.Index([1, 1, 2], name=\"col\"),\n name=\"partition\",\n )\n assert_series_equal(ser, expected)\n\n ser_comp = index1.as_flat_series(compact=True)\n expected = pd.Series(\n [[\"part_1\", \"part_2\"], [\"part_1\"]],\n index=pd.Index([1, 2], name=\"col\"),\n name=\"partition\",\n )\n assert_series_equal(ser_comp, expected)\n\n\ndef test_index_as_flat_series_single_value():\n\n index1 = ExplicitSecondaryIndex(\n column=\"col\", index_dct={1: [\"part_1\", \"part_2\"]}, dtype=pa.int64()\n )\n ser = index1.as_flat_series()\n expected = pd.Series(\n [\"part_1\", \"part_2\"], index=pd.Index([1, 1], name=\"col\"), name=\"partition\"\n )\n assert_series_equal(ser, expected)\n\n ser_comp = index1.as_flat_series(compact=True)\n expected = pd.Series(\n [[\"part_1\", \"part_2\"]], index=pd.Index([1], name=\"col\"), name=\"partition\"\n )\n assert_series_equal(ser_comp, expected)\n\n\ndef test_index_as_flat_series_partitions_as_index():\n\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={1: [\"part_1\", \"part_2\"], 2: [\"part_1\"]},\n dtype=pa.int64(),\n )\n\n ser = index1.as_flat_series(partitions_as_index=True)\n expected = pd.Series(\n [1, 1, 2],\n index=pd.Index([\"part_1\", \"part_2\", \"part_1\"], name=\"partition\"),\n name=\"col\",\n )\n assert_series_equal(ser, expected)\n\n ser_comp = index1.as_flat_series(compact=True, partitions_as_index=True)\n expected = pd.Series(\n [[1, 2], [1]],\n index=pd.Index([\"part_1\", \"part_2\"], name=\"partition\"),\n name=\"col\",\n )\n assert_series_equal(ser_comp, expected)\n\n\ndef test_index_as_flat_series_highly_degenerated_sym():\n dim = 4\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={\n k: [\"part_{}\".format(i) for i in range(0, dim)] for k in range(0, dim)\n },\n dtype=pa.int64(),\n )\n ser = index1.as_flat_series()\n expected = pd.Series(\n [\"part_{}\".format(i) for i in range(0, dim)] * dim,\n index=pd.Index(\n np.array([[i] * dim for i in range(0, dim)]).ravel(), name=\"col\"\n ),\n name=\"partition\",\n )\n assert_series_equal(ser, expected)\n\n\ndef test_index_as_flat_series_highly_degenerated_asym():\n \"\"\"\n Ensure that the generation of the series is not bound by col numbers or nans in the matrix\n \"\"\"\n dim = 4\n ind_dct = {k: [\"part_{}\".format(i) for i in range(0, dim)] for k in range(0, dim)}\n ind_dct[0] = [\"part_1\"]\n ind_dct[2] = [\"part_2\", \"part_5\"]\n index1 = ExplicitSecondaryIndex(column=\"col\", index_dct=ind_dct, dtype=pa.int64())\n ser = index1.as_flat_series()\n partition = [\n \"part_1\",\n \"part_0\",\n \"part_1\",\n \"part_2\",\n \"part_3\",\n \"part_2\",\n \"part_5\",\n \"part_0\",\n \"part_1\",\n \"part_2\",\n \"part_3\",\n ]\n index_values = [0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3]\n expected = pd.Series(\n partition, index=pd.Index(index_values, name=\"col\", dtype=int), name=\"partition\"\n )\n assert_series_equal(ser, expected)\n\n ser_inv = index1.as_flat_series(partitions_as_index=True)\n expected_inv = pd.Series(\n index_values, index=pd.Index(partition, name=\"partition\"), name=\"col\"\n )\n assert_series_equal(ser_inv, expected_inv)\n\n\n@pytest.mark.parametrize(\n \"dtype, date_as_object\", [(None, True), (\"datetime64[ns]\", False)]\n)\ndef test_index_as_flat_series_date(dtype, date_as_object):\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={\n datetime.date(2017, 1, 2): [\"part_1\", \"part_2\"],\n datetime.date(2018, 2, 3): [\"part_1\"],\n },\n dtype=pa.date32(),\n )\n ser = index1.as_flat_series(date_as_object=date_as_object)\n ser = ser.sort_index()\n expected = pd.Series(\n [\"part_1\", \"part_2\", \"part_1\"],\n index=pd.Index(\n [\n datetime.date(2017, 1, 2),\n datetime.date(2017, 1, 2),\n datetime.date(2018, 2, 3),\n ],\n dtype=dtype,\n name=\"col\",\n ),\n name=\"partition\",\n )\n assert_series_equal(ser, expected)\n\n\n@pytest.mark.parametrize(\n \"dtype, timestamps\",\n [\n (pa.timestamp(\"ns\"), [pd.Timestamp(\"2017-01-01\"), pd.Timestamp(\"2017-01-02\")]),\n (\n pa.timestamp(\"ns\"),\n [\n pd.Timestamp(\"2017-01-01\", tzinfo=pytz.timezone(\"EST\")),\n pd.Timestamp(\"2017-01-02\", tzinfo=pytz.timezone(\"EST\")),\n ],\n ),\n ],\n)\ndef test_index_store_roundtrip_ts(store, dtype, timestamps):\n storage_key = \"dataset_uuid/some_index.parquet\"\n index1 = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct=dict(zip(timestamps, [[\"part_1\", \"part_2\"], [\"part_3\"]])),\n index_storage_key=storage_key,\n dtype=dtype,\n )\n key1 = index1.store(store, \"dataset_uuid\")\n\n index2 = ExplicitSecondaryIndex(column=\"col\", index_storage_key=key1).load(store)\n assert index1 == index2\n\n\n@pytest.mark.parametrize(\n \"dtype,expected\", [(pa.int8(), pa.int64()), (pa.uint8(), pa.uint64()), (None, None)]\n)\ndef test_index_normalize_dtype(dtype, expected):\n index = ExplicitSecondaryIndex(\n column=\"col\", dtype=dtype, index_storage_key=\"dataset_uuid/some_index.parquet\"\n )\n assert index.dtype == expected\n\n\ndef test_index_raises_nested_dtype():\n with pytest.raises(NotImplementedError) as exc:\n ExplicitSecondaryIndex(\n column=\"col\",\n dtype=pa.list_(pa.int8()),\n index_storage_key=\"dataset_uuid/some_index.parquet\",\n )\n assert str(exc.value) == \"Indices w/ nested types are not supported\"\n\n\ndef test_index_raises_null_dtype():\n with pytest.raises(NotImplementedError) as exc:\n ExplicitSecondaryIndex(\n column=\"col\",\n dtype=pa.null(),\n index_storage_key=\"dataset_uuid/some_index.parquet\",\n )\n assert str(exc.value) == \"Indices w/ null/NA type are not supported\"\n\n\n@pytest.mark.parametrize(\n \"dtype,value,expected\",\n [\n (pa.bool_(), True, True),\n (pa.bool_(), False, False),\n (pa.bool_(), 1, True),\n (pa.bool_(), 0, False),\n (pa.bool_(), \"True\", True),\n (pa.bool_(), \"False\", False),\n (pa.bool_(), \"true\", True),\n (pa.bool_(), \"false\", False),\n (pa.int64(), 1, 1),\n (pa.int64(), \"1\", 1),\n (pa.int64(), 1.0, 1),\n (pa.float64(), 1.1, 1.1),\n (pa.float64(), \"1.1\", 1.1),\n (pa.float64(), 1, 1.0),\n (pa.binary(), \"x\", b\"x\"),\n (pa.string(), \"x\", \"x\"),\n (pa.string(), \"ö\", \"ö\"),\n (pa.string(), 1, \"1\"),\n (pa.string(), \"ö\".encode(\"utf8\"), \"ö\"),\n (\n pa.timestamp(\"ns\"),\n pd.Timestamp(\"2018-01-01\"),\n pd.Timestamp(\"2018-01-01\").to_datetime64(),\n ),\n (\n pa.timestamp(\"ns\"),\n pd.Timestamp(\"2018-01-01\").to_datetime64(),\n pd.Timestamp(\"2018-01-01\").to_datetime64(),\n ),\n (pa.timestamp(\"ns\"), \"2018-01-01\", pd.Timestamp(\"2018-01-01\").to_datetime64()),\n (pa.date32(), \"2018-01-01\", datetime.date(2018, 1, 1)),\n (\n pa.timestamp(\"ns\", tz=pytz.timezone(\"Europe/Berlin\")),\n pd.Timestamp(\"2018-01-01\", tzinfo=pytz.timezone(\"Europe/Berlin\")),\n pd.Timestamp(\n \"2018-01-01\", tzinfo=pytz.timezone(\"Europe/Berlin\")\n ).to_datetime64(),\n ),\n (\n pa.timestamp(\"ns\", tz=pytz.timezone(\"Europe/Berlin\")),\n \"2018-01-01\", # Naive date, is interpreted as being UTC\n pd.Timestamp(\"2018-01-01\", tzinfo=pytz.timezone(\"UTC\")).to_datetime64(),\n ),\n ],\n)\ndef test_index_normalize_value(dtype, value, expected):\n index = ExplicitSecondaryIndex(\n column=\"col\", dtype=dtype, index_storage_key=\"dataset_uuid/some_index.parquet\"\n )\n actual = index.normalize_value(index.dtype, value)\n assert actual == expected\n assert type(actual) == type(expected)\n\n\ndef test_index_normalize_during_init():\n index = ExplicitSecondaryIndex(\n column=\"col\",\n dtype=pa.int8(),\n index_dct={\"1\": [\"a\", \"b\"], 1: [\"a\", \"c\"], 2.0: [\"d\"]},\n )\n expected = {1: [\"a\", \"b\", \"c\"], 2: [\"d\"]}\n assert index.index_dct == expected\n\n\n@pytest.mark.parametrize(\"collision\", [True, False])\ndef test_index_normalize_during_init_warn_collision(collision, caplog):\n index_dct = {1: [\"a\", \"c\"], 2.0: [\"d\"]}\n if collision:\n index_dct[\"1\"] = [\"a\", \"b\"]\n\n caplog.set_level(logging.DEBUG)\n ExplicitSecondaryIndex(column=\"col\", dtype=pa.int8(), index_dct=index_dct)\n\n warn = [\n t[2]\n for t in caplog.record_tuples\n if t[0] == \"kartothek.core.index\" and t[1] == logging.WARN\n ]\n\n if collision:\n assert any(\n msg.startswith(\n \"Value normalization for index column col resulted in 1 collision(s).\"\n )\n for msg in warn\n )\n else:\n assert not any(\n msg.startswith(\"Value normalization for index column\") for msg in warn\n )\n\n\ndef test_index_normalize_during_query():\n index = ExplicitSecondaryIndex(\n column=\"col\", dtype=pa.int64(), index_dct={1: [\"a\", \"b\", \"c\"], 2: [\"d\"]}\n )\n assert index.query(1) == [\"a\", \"b\", \"c\"]\n assert index.query(2) == [\"d\"]\n assert index.query(\"2\") == [\"d\"]\n assert index.query(1.0) == [\"a\", \"b\", \"c\"]\n\n\n@pytest.mark.parametrize(\n \"op, value, expected\",\n [\n (\"==\", 1, {\"b\", \"c\", \"e\"}),\n (\"<=\", 1, {\"a\", \"b\", \"c\", \"e\"}),\n (\">=\", 1, {\"b\", \"c\", \"e\", \"f\"}),\n (\"<\", 1, {\"a\", \"b\", \"c\"}),\n (\">\", 1, {\"f\"}),\n (\"in\", [0, 2], {\"a\", \"b\", \"c\", \"f\"}),\n ],\n)\n@given(index_data=get_numpy_array_strategy(unique=True, sort=True, allow_nan=False))\ndef test_eval_operators(index_data, op, value, expected):\n index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={\n index_data[0]: [\"a\", \"b\", \"c\"],\n index_data[1]: [\"b\", \"c\", \"e\"],\n index_data[2]: [\"f\"],\n },\n )\n assume(len(index.index_dct) == 3)\n result = index.eval_operator(op, index_data[value])\n\n assert result == expected\n\n\ndef test_eval_operators_type_safety():\n # gh66\n ind = IndexBase(column=\"col\", index_dct={1234: [\"part\"]}, dtype=pa.int64())\n with pytest.raises(\n TypeError, match=\"Unexpected type encountered. Expected i but got O.\"\n ):\n ind.eval_operator(\"==\", \"1234\")\n with pytest.raises(\n TypeError, match=\"Unexpected type encountered. Expected i but got f.\"\n ):\n ind.eval_operator(\"==\", 1234.0)\n\n assert ind.eval_operator(\"==\", 1234) == {\"part\"}\n\n\n@pytest.mark.parametrize(\"inplace\", [True, False])\ndef test_index_normalize_remove_values(inplace):\n original_index = ExplicitSecondaryIndex(\n column=\"col\", dtype=pa.int64(), index_dct={1: [\"a\", \"b\", \"c\"], 2: [\"d\"]}\n )\n\n new_index1 = original_index.copy().remove_values([1, 3], inplace=inplace)\n expected_index1 = ExplicitSecondaryIndex(\n column=\"col\", dtype=pa.int64(), index_dct={2: [\"d\"]}\n )\n assert new_index1 == expected_index1\n\n new_index2 = original_index.copy().remove_values([1.0, 3.0], inplace=inplace)\n expected_index2 = ExplicitSecondaryIndex(\n column=\"col\", dtype=pa.int64(), index_dct={2: [\"d\"]}\n )\n assert new_index2 == expected_index2\n\n new_index3 = original_index.copy().remove_values([\"1\", \"3\"], inplace=inplace)\n expected_index3 = ExplicitSecondaryIndex(\n column=\"col\", dtype=pa.int64(), index_dct={2: [\"d\"]}\n )\n assert new_index3 == expected_index3\n\n\ndef test_index_ts_inference(store):\n index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={\n pd.Timestamp(\"2017-01-01\"): [\"part_1\", \"part_2\"],\n pd.Timestamp(\"2017-01-02\"): [\"part_3\"],\n },\n )\n assert index.dtype == pa.timestamp(\"ns\")\n\n\ndef _dict_to_index(dct):\n new_dct = {}\n for col in dct:\n new_dct[col] = ExplicitSecondaryIndex(col, dct[col])\n return new_dct\n\n\n@pytest.mark.parametrize(\"obj_factory\", [dict, _dict_to_index])\ndef test_merge_indices(obj_factory):\n indices = [\n _dict_to_index({\"location\": {\"Loc1\": [\"label1\"], \"Loc2\": [\"label1\"]}}),\n _dict_to_index(\n {\n \"location\": {\"Loc3\": [\"label2\"], \"Loc2\": [\"label2\"]},\n \"product\": {\"Product1\": [\"label2\"], \"Product2\": [\"label2\"]},\n }\n ),\n _dict_to_index(\n {\"location\": {\"Loc4\": [\"label3\"]}, \"product\": {\"Product1\": [\"label3\"]}}\n ),\n ]\n result = merge_indices(indices)\n for key, value in result.items():\n if isinstance(value, ExplicitSecondaryIndex):\n result[key] = value.to_dict()\n for part_list in result[key].values():\n part_list.sort()\n\n expected = {\n \"location\": {\n \"Loc1\": [\"label1\"],\n \"Loc2\": [\"label1\", \"label2\"],\n \"Loc3\": [\"label2\"],\n \"Loc4\": [\"label3\"],\n },\n \"product\": {\"Product1\": [\"label2\", \"label3\"], \"Product2\": [\"label2\"]},\n }\n assert result == expected\n\n\ndef test_index_uint():\n index = ExplicitSecondaryIndex(\n column=\"col\",\n index_dct={\n 14671423800646041619: [\"part_1\", \"part_2\"],\n np.iinfo(np.uint64).max: [\"part_1\"],\n },\n )\n assert index.dtype == \"uint64\"\n\n\n@pytest.mark.parametrize(\n \"key\",\n [\n True, # pa.bool_()\n 1, # pa.int64()\n 1.1, # pa.float64()\n b\"x\", # pa.binary()\n \"ö\", # pa.string()\n pd.Timestamp(\"2018-01-01\").to_datetime64(), # pa.timestamp(\"ns\")\n pd.Timestamp(\n \"2018-01-01\", tzinfo=pytz.timezone(\"Europe/Berlin\")\n ).to_datetime64(), # pa.timestamp(\"ns\")\n datetime.date(2018, 1, 1), # pa.date32()\n ],\n)\ndef test_serialization(key):\n \"\"\"Check index remains consistent after serializing and de-serializing\"\"\"\n index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={key: [\"part_2\", \"part_4\", \"part_1\"]}\n )\n index2 = pickle.loads(pickle.dumps(index))\n\n assert index == index2\n\n\n@pytest.mark.parametrize(\n \"key\",\n [\n True, # pa.bool_()\n 1, # pa.int64()\n 1.1, # pa.float64()\n b\"x\", # pa.binary()\n \"ö\", # pa.string()\n pd.Timestamp(\"2018-01-01\").to_datetime64(), # pa.timestamp(\"ns\")\n pd.Timestamp(\n \"2018-01-01\", tzinfo=pytz.timezone(\"Europe/Berlin\")\n ).to_datetime64(), # pa.timestamp(\"ns\")\n datetime.datetime(\n 2018, 1, 1, 12, 30\n ), # pa.timestamp(\"us\") (initial) => pa.timestamp(\"ns\") (after loading)\n datetime.datetime(\n 2018, 1, 1, 12, 30, tzinfo=pytz.timezone(\"Europe/Berlin\")\n ), # pa.timestamp(\"ns\")\n datetime.date(2018, 1, 1), # pa.date32()\n ],\n)\ndef test_serialization_normalization(key):\n \"\"\"\n Check that index normalizes values consistently after serializing.\n\n This is helpful to ensure correct behavior for cases such as when\n key=`datetime.datetime(2018, 1, 1, 12, 30)`, as this would be parsed to\n `pa.timestamp(\"us\")` during index creation, but stored as `pa.timestamp(\"ns\")`.\n \"\"\"\n index = ExplicitSecondaryIndex(\n column=\"col\", index_dct={key: [\"part_2\", \"part_4\", \"part_1\"]}\n )\n index2 = pickle.loads(pickle.dumps(index))\n\n assert index.normalize_value(index.dtype, key) == index2.normalize_value(\n index2.dtype, key\n )\n\n\ndef test_serialization_no_indices(store):\n index = ExplicitSecondaryIndex(column=\"col\", index_dct={1: [\"part_1\"]})\n storage_key = index.store(store=store, dataset_uuid=\"uuid\")\n\n # Create index without `index_dct`\n index = ExplicitSecondaryIndex(column=\"col\", index_storage_key=storage_key)\n\n index2 = pickle.loads(pickle.dumps(index))\n\n assert index == index2\n"
] |
[
[
"pandas.Timestamp",
"pandas.testing.assert_series_equal",
"pandas.Index",
"numpy.iinfo"
]
] |
royJackman/HorsePythons
|
[
"b40170b21d65f007cc9e6847debd09cba6365c71"
] |
[
"crawler.py"
] |
[
"import argparse\nimport asyncio\nimport json\nimport pyppeteer\nimport re\nimport sys\nimport numpy as np\n\nfrom bs4 import BeautifulSoup as bs\nfrom tabulate import tabulate\n\nparser = argparse.ArgumentParser(description='Gather horse race data from offtrackbetting.com')\nparser.add_argument('-b', '--base-date', type=int, dest='base_date', help='Base date to start search for all enabled dates, YYYYMMDD format', default=20200522)\nparser.add_argument('-s', '--start-date', type=int, dest='start_date', help='Start date for data crawl window, YYYYMMDD format', default=0)\nparser.add_argument('-e', '--end-date', type=int, dest='end_date', help='End date for data crawl window, YYYYMMDD format', default=30000000)\nparser.add_argument('-o', '--outfile', type=str, dest='outfile', help='Name of the date output file', default='')\n\nargs = parser.parse_args()\nbase_date = args.base_date\nstart_date = args.start_date\nend_date = args.end_date\noutfile = args.outfile\n\nif start_date > end_date:\n print('Start date cannot come after end date')\n sys.exit()\n\nurl_string = 'https://www.offtrackbetting.com/results/73/remington-park-{yyyymmdd}.html'\ntrack = 'remington_park'\n\n# An asynchronous function for grabbing the web page and waiting for the \n# JavaScript to load the dynamic tables\nasync def get_page(url, selector):\n browser = await pyppeteer.launch()\n page = await browser.newPage()\n try:\n await page.goto(url)\n await page.waitForSelector(selector, timeout=10000)\n except pyppeteer.errors.TimeoutError:\n print('Could not find tables on current date')\n retval = await page.content()\n await browser.close()\n return retval\n\npage_data = asyncio.get_event_loop().run_until_complete(get_page(url_string.format(yyyymmdd = base_date), 'script'))\nhtml_string = bs(page_data, 'html.parser')\n\n# Search through the scripts to find the one which contains the previous race\n# dates from the given track\nscripts = html_string.find_all('script')\nregex = re.compile('var enableDays = (.*?);')\nfor script in scripts:\n array_check = re.search(regex, ' '.join(script.contents)) if len(script.contents) > 0 else None\n if array_check != None:\n enabled_days = json.loads(array_check.groups()[0])\n break\n\nif enabled_days == None:\n print('Could not find enabled days, quitting')\n sys.exit()\n\ndata = [['date', 'track', 'race', 'number', 'name', 'jockey', 'win', 'place', 'show']]\nenabled_days = [day for day in enabled_days if start_date <= day and day <= end_date]\n\nfor day in enabled_days:\n print('Starting day', day)\n page_data = asyncio.get_event_loop().run_until_complete(get_page(url_string.format(yyyymmdd = day), 'td.postposition'))\n\n html_string = bs(page_data, 'html.parser')\n races = html_string.find_all('div', id='finishers')\n\n # Loop through all races on the page, find the finishers table, parse the data,\n # and save to the data table\n for i in range(len(races)):\n finishers_rows = races[i].find('table').find_all('tr')\n for row in finishers_rows[1:]:\n row_data = row.find_all('td')\n if len(row_data) < 6:\n continue\n\n number = row_data[0].getText()\n name = row_data[1].getText()\n jockey = row_data[2].getText()\n win = row_data[3].getText().replace('$','')\n if win == '': win = '0.00'\n place = row_data[4].getText().replace('$', '')\n if place == '': place = '0.00'\n show = row_data[5].getText().replace('$', '')\n \n data.append([day, track, i, number, name, jockey, win, place, show])\n\n# Convert to numpy array and export\ndata = np.array(data)\nwith open(outfile if outfile != '' else 'data/' + track + ('_s' + str(start_date) if start_date > 19700101 else '') + ('_e' + str(end_date) if end_date < 29991231 else '') + '.npy', 'wb') as output:\n print('Written to', output.name)\n np.save(output, data)\n"
] |
[
[
"numpy.array",
"numpy.save"
]
] |
sarahyurick/cloud-ml-examples
|
[
"572c607ffeffae276f113b6dff7f76a9643e84b5"
] |
[
"aws/code/serve.py"
] |
[
"#\n# Copyright (c) 2019-2021, NVIDIA CORPORATION.\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\nimport os\nimport sys\nimport traceback\nimport joblib\nimport glob\nimport json\nimport time\n\nimport xgboost\nimport numpy\n\nimport flask\nfrom flask import Flask, Response\n\nimport logging\nfrom functools import lru_cache\n\ntry:\n \"\"\" check for GPU via library imports \"\"\"\n import cupy\n from cuml import ForestInference\n GPU_INFERENCE_FLAG = True\n\nexcept ImportError as gpu_import_error:\n GPU_INFERENCE_FLAG = False\n print(f'\\n!GPU import error: {gpu_import_error}\\n')\n\n# set to true to print incoming request headers and data\nDEBUG_FLAG = False\n\n\ndef serve(xgboost_threshold=0.5):\n \"\"\" Flask Inference Server for SageMaker hosting of RAPIDS Models \"\"\"\n app = Flask(__name__)\n logging.basicConfig(level=logging.DEBUG)\n\n if GPU_INFERENCE_FLAG:\n app.logger.info('GPU Model Serving Workflow')\n app.logger.info(f'> {cupy.cuda.runtime.getDeviceCount()}'\n f' GPUs detected \\n')\n else:\n app.logger.info('CPU Model Serving Workflow')\n app.logger.info(f'> {os.cpu_count()} CPUs detected \\n')\n\n @app.route(\"/ping\", methods=[\"GET\"])\n def ping():\n \"\"\" SageMaker required method, ping heartbeat \"\"\"\n return Response(response=\"\\n\", status=200)\n\n @lru_cache()\n def load_trained_model():\n \"\"\"\n Cached loading of trained [ XGBoost or RandomForest ] model into memory\n Note: Models selected via filename parsing, edit if necessary\n \"\"\"\n xgb_models = glob.glob('/opt/ml/model/*_xgb')\n rf_models = glob.glob('/opt/ml/model/*_rf')\n kmeans_models = glob.glob('/opt/ml/model/*_kmeans')\n app.logger.info(f'detected xgboost models : {xgb_models}')\n app.logger.info(f'detected randomforest models : {rf_models}')\n app.logger.info(f'detected kmeans models : {kmeans_models}\\n\\n')\n model_type = None\n\n start_time = time.perf_counter()\n\n if len(xgb_models):\n model_type = 'XGBoost'\n model_filename = xgb_models[0]\n if GPU_INFERENCE_FLAG:\n # FIL\n reloaded_model = ForestInference.load(model_filename)\n else:\n # native XGBoost\n reloaded_model = xgboost.Booster()\n reloaded_model.load_model(fname=model_filename)\n\n elif len(rf_models):\n model_type = 'RandomForest'\n model_filename = rf_models[0]\n reloaded_model = joblib.load(model_filename)\n \n elif len(kmeans_models):\n model_type = 'KMeans'\n model_filename = kmeans_models[0]\n reloaded_model = joblib.load(model_filename)\n else:\n raise Exception('! No trained models detected')\n\n exec_time = time.perf_counter() - start_time\n app.logger.info(f'> model {model_filename} '\n f'loaded in {exec_time:.5f} s \\n')\n\n return reloaded_model, model_type, model_filename\n\n @app.route(\"/invocations\", methods=[\"POST\"])\n def predict():\n \"\"\"\n Run CPU or GPU inference on input data,\n called everytime an incoming request arrives\n \"\"\"\n # parse user input\n try:\n if DEBUG_FLAG:\n app.logger.debug(flask.request.headers)\n app.logger.debug(flask.request.content_type)\n app.logger.debug(flask.request.get_data())\n\n string_data = json.loads(flask.request.get_data())\n query_data = numpy.array(string_data)\n\n except Exception:\n return Response(\n response=\"Unable to parse input data\"\n \"[ should be json/string encoded list of arrays ]\",\n status=415,\n mimetype='text/csv'\n )\n\n # cached [reloading] of trained model to process incoming requests\n reloaded_model, model_type, model_filename = load_trained_model()\n\n try:\n start_time = time.perf_counter()\n if model_type == 'XGBoost':\n app.logger.info('running inference using XGBoost model :'\n f'{model_filename}')\n\n if GPU_INFERENCE_FLAG:\n predictions = reloaded_model.predict(query_data)\n else:\n dm_deserialized_data = xgboost.DMatrix(query_data)\n predictions = reloaded_model.predict(dm_deserialized_data)\n\n predictions = (predictions > xgboost_threshold) * 1.0\n\n elif model_type == 'RandomForest':\n app.logger.info('running inference using RandomForest model :'\n f'{model_filename}')\n\n if 'gpu' in model_filename and not GPU_INFERENCE_FLAG:\n raise Exception('attempting to run CPU inference '\n 'on a GPU trained RandomForest model')\n\n predictions = reloaded_model.predict(\n query_data.astype('float32'))\n \n elif model_type == 'KMeans':\n app.logger.info('running inference using KMeans model :'\n f'{model_filename}')\n \n if 'gpu' in model_filename and not GPU_INFERENCE_FLAG: \n raise Exception('attempting to run CPU inference '\n 'on a GPU trained KMeans model')\n \n predictions = reloaded_model.predict(\n query_data.astype('float32'))\n\n app.logger.info(f'\\n predictions: {predictions} \\n')\n exec_time = time.perf_counter() - start_time\n app.logger.info(f' > inference finished in {exec_time:.5f} s \\n')\n\n # return predictions\n return Response(response=json.dumps(predictions.tolist()),\n status=200, mimetype='text/csv')\n\n # error during inference\n except Exception as inference_error:\n app.logger.error(inference_error)\n return Response(response=f\"Inference failure: {inference_error}\\n\",\n status=400, mimetype='text/csv')\n\n # initial [non-cached] reload of trained model\n reloaded_model, model_type, model_filename = load_trained_model()\n\n # trigger start of Flask app\n app.run(host=\"0.0.0.0\", port=8080)\n\n\nif __name__ == \"__main__\":\n\n try:\n serve()\n sys.exit(0) # success exit code\n\n except Exception:\n traceback.print_exc()\n sys.exit(-1) # failure exit code\n\n\"\"\"\nairline model inference test [ 3 non-late flights, and a one late flight ]\ncurl -X POST --header \"Content-Type: application/json\" --data '[[ 2019.0, 4.0, 12.0, 2.0, 3647.0, 20452.0, 30977.0, 33244.0, 1943.0, -9.0, 0.0, 75.0, 491.0 ], [0.6327389486117129, 0.4306956773589715, 0.269797132011095, 0.9802453595689266, 0.37114359481679515, 0.9916185580669782, 0.07909626511279289, 0.7329633329905694, 0.24776047025280235, 0.5692037733986525, 0.22905629196095134, 0.6247424302941754, 0.2589150304037847], [0.39624412725991653, 0.9227953615174843, 0.03561991722126401, 0.7718573109543159, 0.2700874862088877, 0.9410675866419298, 0.6185692299959633, 0.486955878112717, 0.18877072081876722, 0.8266565188148121, 0.7845597219675844, 0.6534800630725327, 0.97356320515559], [ 2018.0, 3.0, 9.0, 5.0, 2279.0, 20409.0, 30721.0, 31703.0, 733.0, 123.0, 1.0, 61.0, 200.0 ]]' http://0.0.0.0:8080/invocations\n\"\"\"\n"
] |
[
[
"numpy.array"
]
] |
colesbury/boost-histogram
|
[
"9e39e111cfd416fae6b2e8209157386163dd46ab"
] |
[
"tests/test_axis.py"
] |
[
"import abc\nimport copy\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose, assert_array_equal\nfrom pytest import approx\n\nimport boost_histogram as bh\n\n\n@pytest.mark.parametrize(\n \"axis,args,opt,kwargs\",\n [\n (bh.axis.Regular, (1, 2, 3), \"\", {}),\n (bh.axis.Regular, (1, 2, 3), \"u\", {}),\n (bh.axis.Regular, (1, 2, 3), \"o\", {}),\n (bh.axis.Regular, (1, 2, 3), \"uo\", {}),\n (bh.axis.Regular, (1, 2, 3), \"g\", {}),\n (bh.axis.Regular, (1, 2, 3), \"\", {\"circular\": True}),\n (bh.axis.Regular, (1, 2, 3), \"\", {\"transform\": bh.axis.transform.log}),\n (bh.axis.Regular, (1, 2, 3), \"\", {\"transform\": bh.axis.transform.sqrt}),\n (bh.axis.Regular, (1, 2, 3), \"\", {\"transform\": bh.axis.transform.Pow(1)}),\n (bh.axis.Variable, ((1, 2, 3),), \"\", {}),\n (bh.axis.Variable, ((1, 2, 3),), \"u\", {}),\n (bh.axis.Variable, ((1, 2, 3),), \"o\", {}),\n (bh.axis.Variable, ((1, 2, 3),), \"uo\", {}),\n (bh.axis.Variable, ((1, 2, 3),), \"g\", {}),\n (bh.axis.Variable, ((1, 2, 3),), \"\", {\"circular\": True}),\n (bh.axis.Integer, (1, 2), \"\", {}),\n (bh.axis.Integer, (1, 2), \"u\", {}),\n (bh.axis.Integer, (1, 2), \"o\", {}),\n (bh.axis.Integer, (1, 2), \"uo\", {}),\n (bh.axis.Integer, (1, 2), \"g\", {}),\n (bh.axis.Integer, (1, 2), \"\", {\"circular\": True}),\n (bh.axis.IntCategory, ((1, 2, 3),), \"\", {}),\n (bh.axis.IntCategory, ((1, 2, 3),), \"g\", {}),\n (bh.axis.IntCategory, ((),), \"g\", {}),\n (bh.axis.StrCategory, (tuple(\"ABC\"),), \"\", {}),\n (bh.axis.StrCategory, (tuple(\"ABC\"),), \"g\", {}),\n (bh.axis.StrCategory, ((),), \"g\", {}),\n ],\n)\ndef test_metadata(axis, args, opt, kwargs):\n for m in (\"foo\", 64, {\"one\": 1}):\n if \"u\" in opt:\n kwargs[\"underflow\"] = False\n if \"o\" in opt:\n kwargs[\"overflow\"] = False\n if \"g\" in opt:\n kwargs[\"growth\"] = True\n kwargs[\"metadata\"] = m\n\n assert axis(*args, **kwargs).metadata is m\n mcopy = copy.deepcopy(m)\n assert axis(*args, **kwargs).metadata == m\n assert axis(*args, **kwargs).metadata == mcopy\n assert axis(*args, **kwargs).metadata != \"bar\"\n assert axis(*args, **kwargs) == axis(*args, **kwargs)\n assert axis(*args, **kwargs) != axis(*args, metadata=\"bar\")\n\n del kwargs[\"metadata\"]\n\n ax = axis(*args, __dict__={\"metadata\": 3, \"other\": 2})\n assert ax.metadata == 3\n assert ax.other == 2\n\n del ax.__dict__\n assert ax.__dict__ == {}\n assert ax.metadata is None\n\n ax.__dict__ = {\"metadata\": 5}\n assert ax.__dict__ == {\"metadata\": 5}\n assert ax.metadata == 5\n\n # Python 2 did not allow mixing ** and kw\n new_kwargs = copy.copy(kwargs)\n new_kwargs[\"__dict__\"] = {\"something\": 2}\n new_kwargs[\"metadata\"] = 3\n with pytest.raises(KeyError):\n axis(*args, **new_kwargs)\n\n new_kwargs = copy.copy(kwargs)\n new_kwargs[\"__dict__\"] = {\"metadata\": 2}\n new_kwargs[\"metadata\"] = 3\n with pytest.raises(KeyError):\n axis(*args, **new_kwargs)\n\n\n# The point of this ABC is to force all the tests listed here to be implemented\n# for each axis type. Pytest instantiates these test classes for us, so missing\n# one really does fail the test.\nclass Axis(abc.ABC):\n @abc.abstractmethod\n def test_init(self):\n pass\n\n @abc.abstractmethod\n def test_traits(self):\n pass\n\n @abc.abstractmethod\n def test_equal(self):\n pass\n\n @abc.abstractmethod\n def test_len(self):\n pass\n\n @abc.abstractmethod\n def test_repr(self):\n pass\n\n @abc.abstractmethod\n def test_getitem(self):\n pass\n\n @abc.abstractmethod\n def test_iter(self):\n pass\n\n @abc.abstractmethod\n def test_index(self):\n pass\n\n @abc.abstractmethod\n def test_edges_centers_widths(self):\n pass\n\n\nclass TestRegular(Axis):\n def test_init(self):\n # Should not throw\n bh.axis.Regular(1, 1.0, 2.0)\n bh.axis.Regular(1, 1.0, 2.0, metadata=\"ra\")\n bh.axis.Regular(1, 1.0, 2.0, underflow=False)\n bh.axis.Regular(1, 1.0, 2.0, underflow=False, overflow=False, metadata=\"ra\")\n bh.axis.Regular(1, 1.0, 2.0, metadata=0)\n bh.axis.Regular(1, 1.0, 2.0, transform=bh.axis.transform.log)\n bh.axis.Regular(1, 1.0, 2.0, transform=bh.axis.transform.sqrt)\n bh.axis.Regular(1, 1.0, 2.0, transform=bh.axis.transform.Pow(1.5))\n\n with pytest.raises(TypeError):\n bh.axis.Regular()\n with pytest.raises(TypeError):\n bh.axis.Regular(overflow=False, underflow=False)\n with pytest.raises(TypeError):\n bh.axis.Regular(1)\n with pytest.raises(TypeError):\n bh.axis.Regular(1, 1.0)\n with pytest.raises(ValueError):\n bh.axis.Regular(0, 1.0, 2.0)\n with pytest.raises(TypeError):\n bh.axis.Regular(\"1\", 1.0, 2.0)\n with pytest.raises(Exception):\n bh.axis.Regular(-1, 1.0, 2.0)\n\n with pytest.raises(ValueError):\n bh.axis.Regular(1, 1.0, 1.0)\n\n with pytest.raises(TypeError):\n bh.axis.Regular(1, 1.0, 2.0, bad_keyword=\"ra\")\n with pytest.raises(AttributeError):\n bh.axis.Regular(1, 1.0, 2.0, transform=lambda x: 2)\n with pytest.raises(TypeError):\n bh.axis.Regular(1, 1.0, 2.0, transform=bh.axis.transform.Pow)\n # TODO: These errors could be better\n\n def test_traits(self):\n STD_TRAITS = dict(continuous=True, ordered=True)\n\n ax = bh.axis.Regular(1, 2, 3)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(underflow=True, overflow=True, **STD_TRAITS)\n\n ax = bh.axis.Regular(1, 2, 3, overflow=False)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(underflow=True, **STD_TRAITS)\n\n ax = bh.axis.Regular(1, 2, 3, underflow=False)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(overflow=True, **STD_TRAITS)\n\n ax = bh.axis.Regular(1, 2, 3, underflow=False, overflow=False)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(**STD_TRAITS)\n\n ax = bh.axis.Regular(1, 2, 3, growth=True)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(\n underflow=True, overflow=True, growth=True, **STD_TRAITS\n )\n\n def test_equal(self):\n a = bh.axis.Regular(4, 1.0, 2.0)\n assert a == bh.axis.Regular(4, 1.0, 2.0)\n assert a != bh.axis.Regular(3, 1.0, 2.0)\n assert a != bh.axis.Regular(4, 1.1, 2.0)\n assert a != bh.axis.Regular(4, 1.0, 2.1)\n assert a != object()\n assert not (a == object()) # __eq__ and __ne__ are separately implemented\n\n # metadata compare\n assert bh.axis.Regular(1, 2, 3, metadata=1) == bh.axis.Regular(\n 1, 2, 3, metadata=1\n )\n assert bh.axis.Regular(1, 2, 3, metadata=1) != bh.axis.Regular(\n 1, 2, 3, metadata=\"1\"\n )\n assert bh.axis.Regular(1, 2, 3, metadata=1) != bh.axis.Regular(\n 1, 2, 3, metadata=[1]\n )\n\n def test_len(self):\n a = bh.axis.Regular(4, 1.0, 2.0)\n assert len(a) == 4\n assert a.size == 4\n assert a.extent == 6\n\n def test_repr(self):\n ax = bh.axis.Regular(4, 1.1, 2.2)\n assert repr(ax) == \"Regular(4, 1.1, 2.2)\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, metadata=\"ra\")\n assert repr(ax) == \"Regular(4, 1.1, 2.2, metadata='ra')\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, underflow=False)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, underflow=False)\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, metadata=\"ra\", overflow=False)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, overflow=False, metadata='ra')\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, metadata=\"ra\", circular=True)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, circular=True, metadata='ra')\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, transform=bh.axis.transform.log)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, transform=log)\"\n # TODO: Add caching so that an extracted functional transform actually works\n\n ax = bh.axis.Regular(3, 1.1, 2.2, transform=bh.axis.transform.sqrt)\n assert repr(ax) == \"Regular(3, 1.1, 2.2, transform=sqrt)\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, transform=bh.axis.transform.Pow(0.5))\n assert repr(ax) == \"Regular(4, 1.1, 2.2, transform=pow(0.5))\"\n\n def test_getitem(self):\n a = bh.axis.Regular(2, 1.0, 2.0)\n ref = [1.0, 1.5, 2.0]\n for i in range(2):\n assert_allclose(a.bin(i), ref[i : i + 2])\n assert_allclose(a[i], ref[i : i + 2])\n\n assert a[-1] == a[1]\n with pytest.raises(IndexError):\n a[2]\n\n assert a.bin(-1)[0] == -np.inf\n assert a.bin(2)[1] == np.inf\n\n assert_allclose(a[bh.underflow], a.bin(-1))\n assert_allclose(a[bh.overflow], a.bin(2))\n\n with pytest.raises(IndexError):\n a.bin(-2)\n with pytest.raises(IndexError):\n a.bin(3)\n\n def test_iter(self):\n a = bh.axis.Regular(2, 1.0, 2.0)\n ref = [(1.0, 1.5), (1.5, 2.0)]\n assert_allclose(a, ref)\n\n def test_index(self):\n a = bh.axis.Regular(4, 1.0, 2.0)\n\n assert a.index(-1) == -1\n assert a.index(0.99) == -1\n assert a.index(1.0) == 0\n assert a.index(1.249) == 0\n assert a.index(1.250) == 1\n assert a.index(1.499) == 1\n assert a.index(1.500) == 2\n assert a.index(1.749) == 2\n assert a.index(1.750) == 3\n assert a.index(1.999) == 3\n assert a.index(2.000) == 4\n assert a.index(20) == 4\n\n def test_reversed_index(self):\n a = bh.axis.Regular(4, 2.0, 1.0)\n\n assert a.index(-1) == 4\n assert a.index(0.99) == 4\n assert a.index(1.0) == 4\n assert a.index(1.249) == 3\n assert a.index(1.250) == 3\n assert a.index(1.499) == 2\n assert a.index(1.500) == 2\n assert a.index(1.749) == 1\n assert a.index(1.750) == 1\n assert a.index(1.999) == 0\n assert a.index(2.000) == 0\n assert a.index(20) == -1\n\n def test_sqrt_transform(self):\n a = bh.axis.Regular(10, 0, 10, transform=bh.axis.transform.sqrt)\n # Edges: 0. , 0.1, 0.4, 0.9, 1.6, 2.5, 3.6, 4.9, 6.4, 8.1, 10.\n\n assert a.index(-100) == 10 # Always in overflow bin\n assert a.index(-1) == 10 # When transform is invalid\n assert a.index(0) == 0\n assert a.index(0.15) == 1\n assert a.index(0.5) == 2\n assert a.index(1) == 3\n assert a.index(1.7) == 4\n assert a.index(9) == 9\n assert a.index(11) == 10\n assert a.index(1000) == 10\n\n assert a.bin(0)[0] == approx(0)\n assert a.bin(1)[0] == approx(0.1)\n assert a.bin(1)[1] == approx(0.4)\n assert a.bin(2)[0] == approx(0.4)\n\n def test_log_transform(self):\n a = bh.axis.Regular(2, 1e0, 1e2, transform=bh.axis.transform.log)\n\n assert a.index(-1) == 2\n assert a.index(0.99) == -1\n assert a.index(1.001) == 0\n assert a.index(9.99) == 0\n assert a.index(10.01) == 1\n assert a.index(99.9) == 1\n assert a.index(100.01) == 2\n assert a.index(1000.1) == 2\n\n assert a.bin(0)[0] == approx(1e0)\n assert a.bin(1)[0] == approx(1e1)\n assert a.bin(1)[1] == approx(1e2)\n\n def test_pow_transform(self):\n a = bh.axis.Regular(2, 1.0, 9.0, transform=bh.axis.transform.Pow(0.5))\n\n assert a.index(-1) == 2\n assert a.index(0.99) == -1\n assert a.index(1.0) == 0\n assert a.index(3.99) == 0\n assert a.index(4.0) == 1\n assert a.index(8.99) == 1\n assert a.index(9) == 2\n assert a.index(1000) == 2\n\n assert a.bin(0)[0] == approx(1.0)\n assert a.bin(1)[0] == approx(4.0)\n assert a.bin(1)[1] == approx(9.0)\n\n def test_edges_centers_widths(self):\n a = bh.axis.Regular(2, 0, 1)\n assert_allclose(a.edges, [0, 0.5, 1])\n assert_allclose(a.centers, [0.25, 0.75])\n assert_allclose(a.widths, [0.5, 0.5])\n\n\nclass TestCircular(Axis):\n def test_init(self):\n # Should not throw\n bh.axis.Regular(1, 2, 3, circular=True)\n bh.axis.Regular(1, 2, 3, metadata=\"pa\", circular=True)\n\n with pytest.raises(TypeError):\n bh.axis.Regular(1, 2, 3, \"pa\", circular=True)\n\n with pytest.raises(TypeError):\n bh.axis.Regular(circular=True)\n with pytest.raises(TypeError):\n bh.axis.Regular(1, circular=True)\n with pytest.raises(TypeError):\n bh.axis.Regular(1, -1, circular=True)\n with pytest.raises(Exception):\n bh.axis.Regular(-1, circular=True)\n with pytest.raises(TypeError):\n bh.axis.Regular(1, 1.0, metadata=1, circular=True)\n with pytest.raises(TypeError):\n bh.axis.Regular(\"1\", circular=True)\n\n def test_traits(self):\n ax = bh.axis.Regular(1, 2, 3, circular=True)\n assert isinstance(ax, bh.axis.Regular)\n assert ax.traits == bh.axis.Traits(\n overflow=True, circular=True, continuous=True, ordered=True\n )\n\n def test_equal(self):\n a = bh.axis.Regular(4, 0.0, 1.0, circular=True)\n assert a == bh.axis.Regular(4, 0, 1, circular=True)\n assert a != bh.axis.Regular(2, 0, 1, circular=True)\n assert isinstance(a, bh.axis.Regular)\n\n def test_len(self):\n assert len(bh.axis.Regular(4, 0.0, 1.0, circular=True)) == 4\n assert bh.axis.Regular(4, 0.0, 1.0, circular=True).size == 4\n assert bh.axis.Regular(4, 0.0, 1.0, circular=True).extent == 5\n\n def test_repr(self):\n ax = bh.axis.Regular(4, 1.1, 2.2, circular=True)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, circular=True)\"\n\n ax = bh.axis.Regular(4, 1.1, 2.2, metadata=\"hi\", circular=True)\n assert repr(ax) == \"Regular(4, 1.1, 2.2, circular=True, metadata='hi')\"\n\n def test_getitem(self):\n a = bh.axis.Regular(2, 1, 1 + np.pi * 2, circular=True)\n ref = [1.0, 1.0 + np.pi, 1.0 + 2.0 * np.pi]\n for i in range(2):\n assert_allclose(a.bin(i), ref[i : i + 2])\n assert_allclose(a[i], ref[i : i + 2])\n\n assert a[-1] == a[1]\n with pytest.raises(IndexError):\n a[2]\n\n with pytest.raises(IndexError):\n a[bh.underflow]\n\n assert_allclose(a[bh.overflow], a.bin(2))\n\n assert a.bin(2)[0] == approx(1 + 2 * np.pi)\n assert a.bin(2)[1] == approx(1 + 3 * np.pi)\n\n with pytest.raises(IndexError):\n a.bin(-1) # no underflow\n with pytest.raises(IndexError):\n a.bin(3)\n\n def test_iter(self):\n a = bh.axis.Regular(2, 1, 2, circular=True)\n ref = [(1, 1.5), (1.5, 2)]\n assert_allclose(a, ref)\n\n def test_index(self):\n a = bh.axis.Regular(4, 1, 1 + np.pi * 2, circular=True)\n d = 0.5 * np.pi\n assert a.index(0.99 - 4 * d) == 3\n assert a.index(0.99 - 3 * d) == 0\n assert a.index(0.99 - 2 * d) == 1\n assert a.index(0.99 - d) == 2\n assert a.index(0.99) == 3\n assert a.index(1.0) == 0\n assert a.index(1.01) == 0\n assert a.index(0.99 + d) == 0\n assert a.index(1.0 + d) == 1\n assert a.index(1.0 + 2 * d) == 2\n assert a.index(1.0 + 3 * d) == 3\n assert a.index(1.0 + 4 * d) == 0\n assert a.index(1.0 + 5 * d) == 1\n\n def test_edges_centers_widths(self):\n a = bh.axis.Regular(2, 0, 1, circular=True)\n assert_allclose(a.edges, [0, 0.5, 1])\n assert_allclose(a.centers, [0.25, 0.75])\n assert_allclose(a.widths, [0.5, 0.5])\n\n\nclass TestVariable(Axis):\n def test_init(self):\n # should not raise\n bh.axis.Variable([0, 1])\n bh.axis.Variable((0, 1, 2, 3, 4))\n bh.axis.Variable([0, 1], metadata=\"va\")\n with pytest.raises(TypeError):\n bh.axis.Variable()\n with pytest.raises(ValueError):\n bh.axis.Variable([1])\n with pytest.raises(TypeError):\n bh.axis.Variable(1)\n with pytest.raises(ValueError):\n bh.axis.Variable([1, -1])\n with pytest.raises(ValueError):\n bh.axis.Variable([1, 1])\n with pytest.raises(TypeError):\n bh.axis.Variable([\"1\", 2])\n with pytest.raises(TypeError):\n bh.axis.Variable([0.0, 1.0, 2.0], bad_keyword=\"ra\")\n\n def test_traits(self):\n STD_TRAITS = dict(continuous=True, ordered=True)\n\n ax = bh.axis.Variable([1, 2, 3])\n assert isinstance(ax, bh.axis.Variable)\n assert ax.traits == bh.axis.Traits(underflow=True, overflow=True, **STD_TRAITS)\n\n ax = bh.axis.Variable([1, 2, 3], overflow=False)\n assert isinstance(ax, bh.axis.Variable)\n assert ax.traits == bh.axis.Traits(underflow=True, **STD_TRAITS)\n\n ax = bh.axis.Variable([1, 2, 3], underflow=False)\n assert isinstance(ax, bh.axis.Variable)\n assert ax.traits == bh.axis.Traits(overflow=True, **STD_TRAITS)\n\n ax = bh.axis.Variable([1, 2, 3], underflow=False, overflow=False)\n assert isinstance(ax, bh.axis.Variable)\n assert ax.traits == bh.axis.Traits(**STD_TRAITS)\n\n def test_equal(self):\n a = bh.axis.Variable([-0.1, 0.2, 0.3])\n assert a == bh.axis.Variable((-0.1, 0.2, 0.3))\n assert a != bh.axis.Variable([0, 0.2, 0.3])\n assert a != bh.axis.Variable([-0.1, 0.1, 0.3])\n assert a != bh.axis.Variable([-0.1, 0.1])\n\n def test_len(self):\n a = bh.axis.Variable([-0.1, 0.2, 0.3])\n assert len(a) == 2\n assert a.size == 2\n assert a.extent == 4\n\n def test_repr(self):\n a = bh.axis.Variable([-0.1, 0.2])\n assert repr(a) == \"Variable([-0.1, 0.2])\"\n\n a = bh.axis.Variable([-0.1, 0.2], metadata=\"hi\")\n assert repr(a) == \"Variable([-0.1, 0.2], metadata='hi')\"\n\n def test_getitem(self):\n ref = [-0.1, 0.2, 0.3]\n a = bh.axis.Variable(ref)\n\n for i in range(2):\n assert_allclose(a.bin(i), ref[i : i + 2])\n assert_allclose(a[i], ref[i : i + 2])\n\n assert a[-1] == a[1]\n with pytest.raises(IndexError):\n a[2]\n\n assert_allclose(a[bh.underflow], a.bin(-1))\n assert_allclose(a[bh.overflow], a.bin(2))\n\n assert a.bin(-1)[0] == -np.inf\n assert a.bin(-1)[1] == ref[0]\n\n assert a.bin(2)[0] == ref[2]\n assert a.bin(2)[1] == np.inf\n\n with pytest.raises(IndexError):\n a.bin(-2)\n with pytest.raises(IndexError):\n a.bin(3)\n\n def test_iter(self):\n ref = [-0.1, 0.2, 0.3]\n a = bh.axis.Variable(ref)\n for i, bin in enumerate(a):\n assert_array_equal(bin, ref[i : i + 2])\n\n def test_index(self):\n a = bh.axis.Variable([-0.1, 0.2, 0.3])\n assert a.index(-10.0) == -1\n assert a.index(-0.11) == -1\n assert a.index(-0.1) == 0\n assert a.index(0.0) == 0\n assert a.index(0.19) == 0\n assert a.index(0.2) == 1\n assert a.index(0.21) == 1\n assert a.index(0.29) == 1\n assert a.index(0.3) == 2\n assert a.index(0.31) == 2\n assert a.index(10) == 2\n\n def test_edges_centers_widths(self):\n a = bh.axis.Variable([0, 1, 3])\n assert_allclose(a.edges, [0, 1, 3])\n assert_allclose(a.centers, [0.5, 2])\n assert_allclose(a.widths, [1, 2])\n\n\nclass TestInteger:\n def test_init(self):\n bh.axis.Integer(-1, 2)\n bh.axis.Integer(-1, 2, metadata=\"foo\")\n bh.axis.Integer(-1, 2, underflow=False)\n bh.axis.Integer(-1, 2, underflow=False, overflow=False)\n bh.axis.Integer(-1, 2, growth=True)\n\n with pytest.raises(TypeError):\n bh.axis.Integer()\n with pytest.raises(TypeError):\n bh.axis.Integer(1)\n with pytest.raises(TypeError):\n bh.axis.Integer(\"1\", 2)\n with pytest.raises(ValueError):\n bh.axis.Integer(2, -1)\n with pytest.raises(TypeError):\n bh.axis.Integer(-1, 2, \"foo\")\n with pytest.raises(TypeError):\n bh.axis.Integer(20, 30, 40)\n\n def test_traits(self):\n STD_TRAITS = dict(ordered=True)\n\n ax = bh.axis.Integer(1, 3)\n assert isinstance(ax, bh.axis.Integer)\n assert ax.traits == bh.axis.Traits(underflow=True, overflow=True, **STD_TRAITS)\n\n # See https://github.com/boostorg/histogram/issues/305\n ax = bh.axis.Integer(1, 3, overflow=False)\n assert isinstance(ax, bh.axis.Integer)\n assert ax.traits == bh.axis.Traits(underflow=True, **STD_TRAITS)\n\n # See https://github.com/boostorg/histogram/issues/305\n ax = bh.axis.Integer(1, 3, underflow=False)\n assert isinstance(ax, bh.axis.Integer)\n assert ax.traits == bh.axis.Traits(overflow=True, **STD_TRAITS)\n\n ax = bh.axis.Integer(1, 3, underflow=False, overflow=False)\n assert isinstance(ax, bh.axis.Integer)\n assert ax.traits == bh.axis.Traits(**STD_TRAITS)\n\n ax = bh.axis.Integer(1, 3, growth=True)\n assert isinstance(ax, bh.axis.Integer)\n assert ax.traits == bh.axis.Traits(growth=True, **STD_TRAITS)\n\n def test_equal(self):\n assert bh.axis.Integer(-1, 2) == bh.axis.Integer(-1, 2)\n assert bh.axis.Integer(-1, 2) != bh.axis.Integer(-1, 2, metadata=\"Other\")\n assert bh.axis.Integer(-1, 2, underflow=True) != bh.axis.Integer(\n -1, 2, underflow=False\n )\n\n def test_len(self, underflow, overflow):\n a = bh.axis.Integer(-1, 3, underflow=underflow, overflow=overflow)\n assert len(a) == 4\n assert a.size == 4\n assert a.extent == 4 + underflow + overflow\n\n def test_repr(self):\n a = bh.axis.Integer(-1, 1)\n assert repr(a) == \"Integer(-1, 1)\"\n\n a = bh.axis.Integer(-1, 1, metadata=\"hi\")\n assert repr(a) == \"Integer(-1, 1, metadata='hi')\"\n\n a = bh.axis.Integer(-1, 1, metadata=2)\n assert repr(a) == \"Integer(-1, 1, metadata=...)\"\n\n a = bh.axis.Integer(-1, 1, underflow=False)\n assert repr(a) == \"Integer(-1, 1, underflow=False)\"\n\n a = bh.axis.Integer(-1, 1, overflow=False)\n assert repr(a) == \"Integer(-1, 1, overflow=False)\"\n\n a = bh.axis.Integer(-1, 1, growth=True)\n assert repr(a) == \"Integer(-1, 1, growth=True)\"\n\n def test_label(self):\n a = bh.axis.Integer(-1, 2, metadata=\"foo\")\n assert a.metadata == \"foo\"\n a.metadata = \"bar\"\n assert a.metadata == \"bar\"\n\n def test_getitem(self):\n a = bh.axis.Integer(-1, 3)\n ref = [-1, 0, 1, 2]\n for i, r in enumerate(ref):\n assert a.bin(i) == r\n assert a[i] == r\n assert a.bin(-1) == -2\n assert a.bin(4) == 3\n\n assert_allclose(a[bh.underflow], a.bin(-1))\n assert_allclose(a[bh.overflow], a.bin(4))\n\n def test_iter(self):\n a = bh.axis.Integer(-1, 3)\n ref = (-1, 0, 1, 2)\n assert_array_equal(a, ref)\n\n def test_index(self):\n a = bh.axis.Integer(-1, 3)\n assert a.index(-3) == -1\n assert a.index(-2) == -1\n assert a.index(-1) == 0\n assert a.index(0) == 1\n assert a.index(1) == 2\n assert a.index(2) == 3\n assert a.index(3) == 4\n assert a.index(4) == 4\n\n def test_edges_centers_widths(self):\n a = bh.axis.Integer(1, 3)\n assert_allclose(a.edges, [1, 2, 3])\n assert_allclose(a.centers, [1.5, 2.5])\n assert_allclose(a.widths, [1, 1])\n\n\nclass TestCategory(Axis):\n def test_init(self):\n # should not raise\n bh.axis.IntCategory([1, 2])\n bh.axis.IntCategory({1, 2})\n bh.axis.IntCategory((1, 2), metadata=\"foo\")\n bh.axis.StrCategory([\"A\", \"B\"])\n bh.axis.StrCategory({\"A\", \"B\"})\n bh.axis.StrCategory(\"AB\")\n bh.axis.StrCategory(\"AB\", metadata=\"foo\")\n\n with pytest.raises(TypeError):\n bh.axis.IntCategory([\"A\", \"B\"])\n with pytest.raises(TypeError):\n bh.axis.StrCategory([1, 2])\n\n with pytest.raises(TypeError):\n bh.axis.IntCategory([1, 2], \"foo\")\n with pytest.raises(TypeError):\n bh.axis.StrCategory(\"AB\", \"foo\")\n\n with pytest.raises(TypeError):\n bh.axis.StrCategory()\n with pytest.raises(TypeError):\n bh.axis.IntCategory()\n with pytest.raises(TypeError):\n bh.axis.StrCategory([1, \"2\"])\n with pytest.raises(TypeError):\n bh.axis.IntCategory([1, \"2\"])\n with pytest.raises(TypeError):\n bh.axis.IntCategory([1, 2, 3], underflow=True)\n\n def test_traits(self):\n ax = bh.axis.IntCategory([1, 2, 3])\n assert isinstance(ax, bh.axis.IntCategory)\n assert ax.traits == bh.axis.Traits(overflow=True)\n\n ax = bh.axis.IntCategory([1, 2, 3], growth=True)\n assert isinstance(ax, bh.axis.IntCategory)\n assert ax.traits == bh.axis.Traits(growth=True)\n\n ax = bh.axis.StrCategory([\"1\", \"2\", \"3\"])\n assert isinstance(ax, bh.axis.StrCategory)\n assert ax.traits == bh.axis.Traits(overflow=True)\n\n ax = bh.axis.StrCategory([\"1\", \"2\", \"3\"], growth=True)\n assert isinstance(ax, bh.axis.StrCategory)\n assert ax.traits == bh.axis.Traits(growth=True)\n\n def test_equal(self):\n assert bh.axis.IntCategory([1, 2, 3]) == bh.axis.IntCategory([1, 2, 3])\n assert bh.axis.IntCategory([1, 2, 3]) != bh.axis.IntCategory([1, 3, 2])\n assert bh.axis.StrCategory([\"A\", \"B\"]) == bh.axis.StrCategory(\"AB\")\n assert bh.axis.StrCategory([\"A\", \"B\"]) != bh.axis.StrCategory(\"BA\")\n\n @pytest.mark.parametrize(\"ref\", ([1, 2, 3], \"ABC\"))\n def test_len(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n a = Cat(ref, growth=growth)\n assert len(a) == 3\n assert a.size == 3\n assert a.extent == 3 if growth else 4\n\n def test_repr(self):\n ax = bh.axis.IntCategory([1, 2, 3])\n assert repr(ax) == \"IntCategory([1, 2, 3])\"\n\n ax = bh.axis.IntCategory([1, 2, 3], metadata=\"foo\")\n assert repr(ax) == \"IntCategory([1, 2, 3], metadata='foo')\"\n\n ax = bh.axis.StrCategory(\"ABC\", metadata=\"foo\")\n assert repr(ax) == \"StrCategory(['A', 'B', 'C'], metadata='foo')\"\n\n @pytest.mark.parametrize(\"ref\", ([1, 2, 3], \"ABC\"))\n def test_getitem(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n\n a = Cat(ref, growth=growth)\n\n for i in range(3):\n assert a.bin(i) == ref[i]\n assert a[i] == ref[i]\n\n assert a[-1] == a[2]\n with pytest.raises(IndexError):\n a[3]\n\n with pytest.raises(IndexError):\n a.bin(-1)\n\n if growth:\n with pytest.raises(IndexError):\n a.bin(3)\n else:\n assert a.bin(3) is None\n\n @pytest.mark.parametrize(\"ref\", ([1, 2, 3], (\"A\", \"B\", \"C\")))\n def test_iter(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n a = Cat(ref, growth=growth)\n assert_array_equal(a, ref)\n\n @pytest.mark.parametrize(\n \"ref\", ([1, 2, 3, 4], (\"A\", \"B\", \"C\", \"D\")), ids=(\"int\", \"str\")\n )\n def test_index(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n a = Cat(ref, growth=growth)\n for i, r in enumerate(ref):\n assert a.index(r) == i\n assert_array_equal(a.index(ref), [0, 1, 2, 3])\n assert_array_equal(a.index(np.reshape(ref, (2, 2))), [[0, 1], [2, 3]])\n\n if isinstance(ref[0], str):\n with pytest.raises(KeyError):\n a.index(\"E\")\n else:\n with pytest.raises(KeyError):\n a.index(5)\n with pytest.raises(KeyError):\n a.index(-2)\n\n @pytest.mark.parametrize(\"ref\", ([1, 2, 3], (\"A\", \"B\", \"C\")))\n def test_value(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n a = Cat(ref, growth=growth)\n for i, r in enumerate(ref):\n assert a.value(i) == r\n assert_array_equal(a.value(range(3)), ref)\n assert a.value(3) is None\n assert_array_equal(a.value((0, 3)), [ref[0], None])\n assert_array_equal(\n a.value(np.array((0, 1, 2, 3))), [ref[0], ref[1], ref[2], None]\n )\n # may be added in the future\n with pytest.raises(ValueError):\n a.value([[2], [2]])\n\n @pytest.mark.parametrize(\"ref\", ([1, 2, 3], \"ABC\"))\n def test_edges_centers_widths(self, ref, growth):\n Cat = bh.axis.StrCategory if isinstance(ref[0], str) else bh.axis.IntCategory\n a = Cat(ref, growth=growth)\n assert_allclose(a.edges, [0, 1, 2, 3])\n assert_allclose(a.centers, [0.5, 1.5, 2.5])\n assert_allclose(a.widths, [1, 1, 1])\n\n\nclass TestBoolean:\n def test_init(self):\n bh.axis.Boolean()\n bh.axis.Boolean(metadata=\"foo\")\n\n with pytest.raises(TypeError):\n bh.axis.Boolean(1)\n\n def test_traits(self):\n ax = bh.axis.Boolean()\n assert isinstance(ax, bh.axis.Boolean)\n\n assert ax.traits == bh.axis.Traits(ordered=True)\n\n def test_equal(self):\n assert bh.axis.Boolean() == bh.axis.Boolean()\n assert bh.axis.Boolean(metadata=\"hi\") == bh.axis.Boolean(metadata=\"hi\")\n assert bh.axis.Boolean(metadata=\"hi\") != bh.axis.Boolean()\n assert bh.axis.Boolean(metadata=\"hi\") != bh.axis.Boolean(metadata=\"ho\")\n\n def test_len(self):\n a = bh.axis.Boolean()\n assert len(a) == 2\n assert a.size == 2\n assert a.extent == 2\n\n def test_repr(self):\n a = bh.axis.Boolean()\n assert repr(a) == \"Boolean()\"\n\n a = bh.axis.Boolean(metadata=\"hi\")\n assert repr(a) == \"Boolean(metadata='hi')\"\n\n def test_label(self):\n a = bh.axis.Boolean(metadata=\"foo\")\n assert a.metadata == \"foo\"\n a.metadata = \"bar\"\n assert a.metadata == \"bar\"\n\n def test_getitem(self):\n a = bh.axis.Boolean()\n ref = [False, True]\n for i, r in enumerate(ref):\n assert a.bin(i) == r\n assert a[i] == r\n assert a.bin(0) == 0\n assert a.bin(1) == 1\n\n def test_iter(self):\n a = bh.axis.Boolean()\n ref = (False, True)\n assert_array_equal(a, ref)\n\n def test_index(self):\n a = bh.axis.Boolean()\n assert a.index(False) == 0\n assert a.index(True) == 1\n\n def test_edges_centers_widths(self):\n a = bh.axis.Boolean()\n assert_allclose(a.edges, [0.0, 1.0, 2.0])\n assert_allclose(a.centers, [0.5, 1.5])\n assert_allclose(a.widths, [1, 1])\n"
] |
[
[
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.reshape",
"numpy.testing.assert_allclose"
]
] |
RaghuSpaceRajan/bsuite-mdpp-merge
|
[
"4f3cfd7dd943ae525e19dab315212a4290edd85f"
] |
[
"bsuite/environments/bandit.py"
] |
[
"# python3\n# pylint: disable=g-bad-file-header\n# Copyright 2019 DeepMind Technologies Limited. 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\"\"\"Simple diagnostic bandit environment.\n\nObservation is a single pixel of 0 - this is an independent arm bandit problem!\nRewards are [0, 0.1, .. 1] assigned randomly to 11 arms and deterministic\n\"\"\"\n\nfrom bsuite.environments import base\nfrom bsuite.experiments.bandit import sweep\n\nimport dm_env\nfrom dm_env import specs\nimport numpy as np\n\n\nclass SimpleBandit(base.Environment):\n \"\"\"SimpleBandit environment.\"\"\"\n\n def __init__(self, seed=None):\n \"\"\"Builds a simple bandit environment.\n\n Args:\n seed: Optional integer. Seed for numpy's random number generator (RNG).\n \"\"\"\n super(SimpleBandit, self).__init__()\n self._rng = np.random.RandomState(seed)\n\n self._n_actions = 11\n action_mask = self._rng.choice(\n range(self._n_actions), size=self._n_actions, replace=False)\n self._rewards = np.linspace(0, 1, self._n_actions)[action_mask]\n\n self._total_regret = 0.\n self._optimal_return = 1.\n self.bsuite_num_episodes = sweep.NUM_EPISODES\n\n def _get_observation(self):\n return np.ones(shape=(1, 1), dtype=np.float32)\n\n def _reset(self) -> dm_env.TimeStep:\n observation = self._get_observation()\n return dm_env.restart(observation)\n\n def _step(self, action: int) -> dm_env.TimeStep:\n reward = self._rewards[action]\n self._total_regret += self._optimal_return - reward\n observation = self._get_observation()\n return dm_env.termination(reward=reward, observation=observation)\n\n def observation_spec(self):\n return specs.Array(shape=(1, 1), dtype=np.float32)\n\n def action_spec(self):\n return specs.DiscreteArray(self._n_actions, name='action')\n\n def bsuite_info(self):\n return dict(total_regret=self._total_regret)\n"
] |
[
[
"numpy.random.RandomState",
"numpy.linspace",
"numpy.ones"
]
] |
asappresearch/rationale-alignment
|
[
"8d2bf06ba4c121863833094d5d4896bf34a9a73e",
"8d2bf06ba4c121863833094d5d4896bf34a9a73e"
] |
[
"classify/metric/loss/ce.py",
"similarity/models/alignment.py"
] |
[
"from typing import Dict, List, Tuple, Optional\n\nimport torch\nimport torch.nn.functional as F\n\nfrom classify.metric.abstract import AlignmentMetric\nfrom classify.metric.abstract import Metric\n\n\nclass CrossEntropyLoss(Metric):\n \"\"\"Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu).\n\n For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin|\n i.e. sum over all positive/negative pairs\n \"\"\"\n\n def __init__(\n self,\n weight: Optional[torch.Tensor] = None,\n ignore_index: Optional[int] = None,\n reduction: str = \"mean\",\n ) -> None:\n \"\"\"Initialize the MultiLabelNLLLoss.\n\n Parameters\n ----------\n weight : Optional[torch.Tensor]\n A manual rescaling weight given to each class.\n If given, has to be a Tensor of size N, where N is the\n number of classes.\n ignore_index : Optional[int], optional\n Specifies a target value that is ignored and does not\n contribute to the input gradient. When size_average is\n True, the loss is averaged over non-ignored targets.\n reduction : str, optional\n Specifies the reduction to apply to the output:\n 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied,\n 'mean': the output will be averaged\n 'sum': the output will be summed.\n\n \"\"\"\n super(CrossEntropyLoss, self).__init__()\n self.weight = weight\n self.ignore_index = ignore_index\n self.reduction = reduction\n\n def compute(\n self, logits: torch.Tensor, targets: torch.Tensor, step: int = 4\n ) -> torch.Tensor:\n \"\"\"Computes the Negative log likelihood loss for multilabel.\n\n Parameters\n ----------\n pred: torch.Tensor\n input logits of shape (B x N)\n target: torch.LontTensor\n target tensor of shape (B x N)\n\n Returns\n -------\n loss: torch.float\n Multi label negative log likelihood loss, of shape (B)\n\n \"\"\"\n targets = [t for target in targets for t in target[\"targets\"]]\n targets = torch.stack(targets)\n if self.ignore_index is not None:\n targets[:, self.ignore_index] = 0\n\n if self.weight is None:\n self.weight = torch.ones(logits.size(1)).to(logits)\n\n loss = F.cross_entropy(\n logits, targets\n ) # , weight=self.weight, ignore_index=self.ignore_index, reduction=self.reduction)\n return loss\n",
"from functools import partial\nimport math\nfrom typing import Any, Iterator, List, Optional, Tuple\n\nfrom sinkhorn import batch_sinkhorn, construct_cost_and_marginals\nfrom sru import SRU\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom utils.parsing import Arguments\nfrom utils.utils import compute_cost, prod, unpad_tensors\nfrom similarity.models.attention import load_attention_layer\nfrom similarity.models.encoder import Embedder\n\n\nclass AlignmentModel(nn.Module):\n def __init__(\n self,\n args: Arguments,\n text_field,\n domain: Optional[str] = None,\n device: torch.device = torch.device(\"cpu\"),\n ):\n \"\"\"Constructs an AlignmentModel.\"\"\"\n super(AlignmentModel, self).__init__()\n\n # Save values\n self.args = args\n self.device = device\n self.embedder = Embedder(args=args, text_field=text_field, device=device)\n\n if self.args.alignment == \"attention\":\n self.atten = load_attention_layer(self.args, self.embedder.output_size)\n\n self.output_size = self.embedder.output_size\n # Move to device\n self.to(self.device)\n\n def forward(\n self,\n data: torch.LongTensor, # batch_size x seq_len\n scope: List[Tuple[torch.LongTensor, torch.LongTensor]],\n targets: List[torch.LongTensor],\n threshold: float = 0,\n encoded: torch.Tensor = None,\n ) -> Tuple[List[Tuple[torch.FloatTensor, torch.FloatTensor]], List[Any]]:\n \"\"\"\n Aligns document pairs.\n\n :param data: Sentences represented as LongTensors of word indices.\n :param scope: A list of tuples of row_indices and column_indices indexing into data\n to extract the appropriate sentences for each document pair.\n :param targets: A list of targets for each document pair.\n :return: A tuple consisting of a list of (cost, alignment) tuples and a list of targets.\n \"\"\"\n if encoded is None:\n encoded, encoded_seq = self.embedder(data)\n # if self.word_to_word:\n # encoded = encodede_seq\n\n # Alignment\n costs, alignments = [], []\n n_list, m_list = [], []\n for row_indices, column_indices in scope:\n # Select sentence vectors using indices\n row_vecs, column_vecs = (\n torch.index_select(encoded, 0, row_indices),\n torch.index_select(encoded, 0, column_indices),\n ) # (n/m)x 2*hidden_size\n\n # Get sizes\n n, m = len(row_vecs), len(column_vecs)\n n_list.append(n)\n m_list.append(m)\n\n # Average sentence embeddings\n if self.args.alignment == \"average\":\n row_vecs = row_vecs.mean(dim=0, keepdim=True)\n column_vecs = column_vecs.mean(dim=0, keepdim=True)\n\n # Compute cost\n cost = compute_cost(cost_fn=self.args.cost_fn, x1=row_vecs, x2=column_vecs)\n\n # Alignment-specific computation\n if self.args.alignment == \"attention\":\n cost, alignment = self.atten(\n row_vecs, column_vecs, cost / self.args.attention_temp, threshold\n )\n alignments.append(alignment)\n\n # Add cost\n costs.append(cost)\n\n # Hack alignment matrix for models that don't do alignment\n if self.args.alignment not in [\"attention\", \"sinkhorn\"]:\n alignments.append(\n torch.ones_like(cost) / prod(cost.shape)\n ) # use alignment to compute average cost\n\n # Alignment via sinkhorn\n if self.args.alignment == \"sinkhorn\":\n # Add dummy node and get marginals\n costs, a_list, b_list = zip(\n *[\n construct_cost_and_marginals(\n C=cost,\n one_to_k=self.args.one_to_k,\n split_dummy=self.args.split_dummy,\n max_num_aligned=self.args.max_num_aligned,\n optional_alignment=self.args.optional_alignment,\n )\n for cost in costs\n ]\n )\n costs, a_list, b_list = list(costs), list(a_list), list(b_list)\n\n # Prepare sinkhorn function\n batch_sinkhorn_func = partial(\n batch_sinkhorn,\n a_list=a_list,\n b_list=b_list,\n epsilon=self.args.epsilon,\n unbalanced_lambda=self.args.unbalanced_lambda,\n )\n\n # Run sinkhorn\n alignments = batch_sinkhorn_func(C_list=costs)\n\n # Remove dummy nodes\n shapes = list(zip(n_list, m_list))\n alignments = unpad_tensors(alignments, shapes)\n\n costs = unpad_tensors(costs, shapes)\n\n # Re-normalize alignment probabilities to one\n if (\n self.args.alignment in [\"attention\", \"sinkhorn\"]\n and not self.args.optional_alignment\n ):\n alignments = [\n alignment\n / alignment.sum(dim=-1, keepdim=True).sum(dim=-2, keepdim=True)\n for alignment in alignments\n ]\n\n # Combine costs and alignments into preds\n preds = list(zip(costs, alignments))\n\n return preds, targets\n\n def forward_with_sentences(\n self,\n data: torch.LongTensor,\n scope: List[Tuple[torch.LongTensor, torch.LongTensor]],\n targets: List[torch.LongTensor],\n threshold: float = 0,\n ) -> Tuple[\n List[Tuple[torch.LongTensor, torch.LongTensor]],\n List[Tuple[torch.FloatTensor, torch.FloatTensor]],\n List[Any],\n ]:\n \"\"\"Makes predictions and returns input sentences, predictions, and targets.\"\"\"\n sentences = [\n (\n torch.index_select(data, 0, simple_indices),\n torch.index_select(data, 0, normal_indices),\n )\n for simple_indices, normal_indices in scope\n ]\n preds, targets = self.forward(data, scope, targets, threshold)\n\n return sentences, preds, targets\n\n def num_parameters(self, trainable: bool = False) -> int:\n \"\"\"Gets the number of parameters in the model.\n Returns\n ----------\n int\n number of model params\n \"\"\"\n if trainable:\n model_params = list(self.trainable_params)\n else:\n model_params = list(self.parameters())\n\n return sum(len(x.view(-1)) for x in model_params)\n\n @property\n def trainable_params(self) -> Iterator[nn.Parameter]:\n \"\"\"Get all the parameters with `requires_grad=True`.\n Returns\n -------\n Iterator[nn.Parameter]\n Iterator over the parameters\n \"\"\"\n return filter(lambda p: p.requires_grad, self.parameters())\n\n @property\n def gradient_norm(self) -> float:\n \"\"\"Compute the average gradient norm.\n\n Returns\n -------\n float\n The current average gradient norm\n\n \"\"\"\n # Only compute over parameters that are being trained\n parameters = filter(\n lambda p: p.requires_grad and p.grad is not None, self.parameters()\n )\n norm = math.sqrt(sum(param.grad.norm(p=2).item() ** 2 for param in parameters))\n\n return norm\n\n @property\n def parameter_norm(self) -> float:\n \"\"\"Compute the average parameter norm.\n\n Returns\n -------\n float\n The current average parameter norm\n\n \"\"\"\n # Only compute over parameters that are being trained\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n norm = math.sqrt(sum(param.norm(p=2).item() ** 2 for param in parameters))\n\n return norm\n"
] |
[
[
"torch.stack",
"torch.nn.functional.cross_entropy"
],
[
"torch.device",
"torch.index_select",
"torch.ones_like"
]
] |
ElchinValiyev/GameAI
|
[
"bae8fcdeeb9b1362179ec0d9d9e12a64d68f0a5e"
] |
[
"Project_3/bayesian_imitation_learning/kmeans.py"
] |
[
"import numpy as np\nimport random\n\n\ndef distance(a, b):\n sum_square = 0\n for i in range(len(a)):\n sum_square += (a[i] - b[i]) ** 2\n return np.sqrt(sum_square)\n\n\ndef e_step(centers, datapoints):\n clusters = np.zeros((len(datapoints)), dtype=np.int64)\n\n for i in range(len(datapoints)):\n dist = [distance(datapoints[i], k) for k in centers]\n min_index, = np.where(dist == np.min(dist))\n clusters[i] = min_index[0]\n return clusters\n\n\ndef m_step(clusters, datapoints, centers):\n sum = np.zeros(centers.shape)\n counters = np.bincount(clusters)\n for j in range(len(centers)):\n for i in range(len(clusters)):\n if (clusters[i] == j):\n sum[j] = sum[j] + datapoints[i]\n centers[j] = sum[j] / counters[j]\n return centers\n\n\ndef kmeans(k, datapoints):\n centers = np.array(random.sample(datapoints, k))\n clusters = np.zeros((len(datapoints)))\n assert len(centers) == k\n old_centers = np.zeros(np.shape(centers))\n while not((old_centers == centers).all()):\n old_centers = centers\n clusters = e_step(centers, datapoints)\n centers = m_step(clusters, datapoints, centers)\n return clusters, centers\n"
] |
[
[
"numpy.sqrt",
"numpy.min",
"numpy.shape",
"numpy.bincount",
"numpy.zeros"
]
] |
chengsoonong/crowdastro
|
[
"ce14432c36de0574b73d813304365b74446a61f8"
] |
[
"crowdastro/active_learning/test.py"
] |
[
"\"\"\"Tests active learning agents with pool-based binary classification.\n\nMatthew Alger\nThe Australian National University\n2016\n\"\"\"\n\nimport multiprocessing\nimport multiprocessing.pool\n\nimport matplotlib.pyplot as plt\nimport numpy\nimport sklearn.cross_validation\nimport sklearn.datasets\nimport sklearn.ensemble\nimport sklearn.linear_model\nimport sklearn.metrics\n\nfrom .uncertainty_sampler import ConfidenceUncertaintySampler\nfrom .random_sampler import RandomSampler\nfrom .qbc_sampler import QBCSampler\n\n\ndef run_tests():\n xs, groundtruth = sklearn.datasets.make_classification(\n n_samples=400, n_features=10, n_informative=5, n_redundant=2,\n n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=None,\n flip_y=0.0, class_sep=0.9, hypercube=True, shift=0.0, scale=1.0,\n shuffle=True, random_state=None)\n\n xs_train, xs_test, groundtruth_train, ts_test = (\n sklearn.cross_validation.train_test_split(xs, groundtruth,\n test_size=0.2))\n\n\n init_percentage = 0.50 # Start with 50% of all labels.\n mask = numpy.random.binomial(1, 1 - init_percentage,\n size=groundtruth_train.shape)\n known_labels = numpy.ma.masked_array(groundtruth_train, mask=mask)\n assert xs_train.shape[0] == known_labels.shape[0]\n\n u_sampler = ConfidenceUncertaintySampler(xs_train, known_labels.copy(),\n sklearn.ensemble.RandomForestClassifier, {'random_state': 0})\n r_sampler = RandomSampler(xs_train, known_labels.copy(),\n sklearn.ensemble.RandomForestClassifier, {'random_state': 0})\n q_sampler = QBCSampler(xs_train, known_labels.copy(),\n sklearn.ensemble.RandomForestClassifier)\n\n def test_sampler(sampler):\n scores = []\n for i in range(400):\n index = sampler.sample_index()\n label = groundtruth_train[index]\n sampler.add_label(index, label)\n scores.append(sampler.score(xs_test, ts_test))\n return scores\n\n u_scores, r_scores, q_scores = map(\n test_sampler, [u_sampler, r_sampler, q_sampler])\n\n return u_scores, r_scores, q_scores\n\n\nif __name__ == '__main__':\n with multiprocessing.pool.Pool(processes=8) as pool:\n all_scores = [pool.apply_async(run_tests, ()) for i in range(1)]\n all_scores = numpy.array([r.get() for r in all_scores])\n\n mean_scores = numpy.mean(all_scores, axis=0)\n u_scores, r_scores, q_scores = mean_scores\n\n# u_scores = numpy.mean(all_u_scores, axis=0)\n# r_scores = numpy.mean(all_r_scores, axis=0)\n# q_scores = numpy.mean(all_q_scores, axis=0)\n\n plt.plot(u_scores)\n plt.plot(r_scores)\n plt.plot(q_scores)\n plt.legend(['uncertainty', 'random', 'qbc'])\n plt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"numpy.mean",
"numpy.ma.masked_array",
"numpy.random.binomial",
"matplotlib.pyplot.show"
]
] |
wellcometrust/WellcomeML
|
[
"f7f5427f6dfdc6e5ee1342764263c6411e0f9bdf"
] |
[
"wellcomeml/ml/bert_semantic_equivalence.py"
] |
[
"from collections import defaultdict\nfrom datetime import datetime\nimport math\nimport os\n\nfrom transformers import BertConfig, BertTokenizer, \\\n TFBertForSequenceClassification\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.exceptions import NotFittedError\n\nfrom wellcomeml.ml.keras_utils import CategoricalMetrics # , MetricMiniBatchHistory\nfrom wellcomeml.logger import LOGGING_LEVEL, build_logger\nfrom wellcomeml.utils import throw_extra_import_message\n\ntry:\n import tensorflow as tf\nexcept ImportError as e:\n throw_extra_import_message(error=e, required_module='tensorflow', extra='tensorflow')\n\n\nclass SemanticEquivalenceClassifier(BaseEstimator, TransformerMixin):\n \"\"\"\n Class to fine-tune BERT-type models for semantic equivalence, for example\n paraphrase, textual similarity and other NLU tasks\n \"\"\"\n\n def __init__(\n self,\n pretrained=\"bert\",\n batch_size=32,\n eval_batch_size=32 * 2,\n learning_rate=3e-5,\n test_size=0.2,\n max_length=128,\n random_seed=42,\n buffer_size=100,\n logging_level=LOGGING_LEVEL,\n tensorflow_log_path=\"logs\",\n verbose=1 # follows Keras verbose for now\n ):\n \"\"\"\n\n Args:\n pretrained(str): 'bert' or 'scibert'\n batch_size(int): The batch size for training\n eval_batch_size(int): The evaluation batch size\n learning_rate(float): Learning rate (usually between 0.1 and 1e-5)\n test_size(float): Proportion of data used for testing (default 0.2)\n max_length: Maximum length of text in characters.\n Zero pads every text smaller than this number and cuts out\n any text bigger than that number\n random_seed: A seed used for shuffling the dataset upon training\n buffer_size: A buffer size that will be used when shuffling the dataset\n tensorflow_log_path: Path to store tensorboard logs\n verbose: 0,1,2. Verbose level for keras fit\n \"\"\"\n self.logger = build_logger(logging_level, __name__)\n self.pretrained = pretrained\n self.batch_size = batch_size\n self.eval_batch_size = eval_batch_size\n self.learning_rate = learning_rate\n self.test_size = test_size\n self.max_length = max_length\n self.random_seed = random_seed\n self.buffer_size = buffer_size\n self.tensorboard_log_path = tensorflow_log_path\n self.verbose = verbose\n\n # Defines attributes that will be initialised later\n self.config = None\n self.tokenizer = None\n self.model = None\n self.train_dataset = None\n self.valid_dataset = None\n self.train_steps = None\n self.valid_steps = None\n self.strategy = None\n\n self.history = defaultdict(list)\n\n # Bert models have a tensorflow checkopoint, otherwise,\n # we need to load the pytorch versions with the parameter `from_pt=True`\n\n def initialise_models(self):\n if self.pretrained == \"bert\":\n model_name = \"bert-base-cased\"\n from_pt = False\n elif self.pretrained == \"scibert\":\n model_name = \"allenai/scibert_scivocab_cased\"\n from_pt = True\n\n self.config = BertConfig.from_pretrained(model_name, num_labels=2)\n self.tokenizer = BertTokenizer.from_pretrained(model_name)\n self.model = TFBertForSequenceClassification.from_pretrained(\n model_name, config=self.config, from_pt=from_pt\n )\n return self.model\n\n def _prep_dataset_generator(self, X, y=None, shuffle=False, repeat=False, batch_size=32):\n features = [\"input_ids\", \"attention_mask\", \"token_type_ids\"]\n\n if y is None:\n input_element_types = {feature: tf.int32 for feature in features}\n input_element_tensors = (\n {feature: tf.TensorShape([None]) for feature in features}\n )\n\n else:\n input_element_types = ({feature: tf.int32 for feature in features}, tf.int64)\n input_element_tensors = (\n {feature: tf.TensorShape([None]) for feature in features},\n tf.TensorShape([]),\n )\n\n self.logger.info(\"Tokenising texts.\")\n batch_encoding = self.tokenizer.batch_encode_plus(\n X, max_length=self.max_length, add_special_tokens=True,\n )\n self.logger.info(\"Configuring dataset generators.\")\n\n def gen_train():\n for i in range(len(X)):\n features_dict = {\n k: pad(batch_encoding[k][i], self.max_length)\n for k in batch_encoding\n }\n if y is None:\n yield features_dict\n else:\n yield (features_dict, int(y[i]))\n\n dataset = tf.data.Dataset.from_generator(\n gen_train, input_element_types, input_element_tensors,\n )\n\n if shuffle:\n dataset = dataset.shuffle(self.buffer_size, seed=self.random_seed)\n\n dataset = dataset.batch(batch_size)\n if repeat:\n dataset = dataset.repeat(-1)\n\n return dataset\n\n def _compile_model(self, metrics=[]):\n opt = tf.keras.optimizers.Adam(learning_rate=self.learning_rate,\n epsilon=1e-08)\n\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\n precision = CategoricalMetrics(metric=\"precision\")\n recall = CategoricalMetrics(metric=\"recall\")\n f1_score = CategoricalMetrics(metric=\"f1_score\")\n accuracy = tf.keras.metrics.SparseCategoricalAccuracy(\"accuracy\")\n\n metrics = [accuracy, precision, recall, f1_score] + metrics\n\n self.model.compile(optimizer=opt, loss=loss, metrics=metrics)\n\n def _get_distributed_strategy(self):\n if len(tf.config.list_physical_devices(\"GPU\")) > 1:\n strategy = tf.distribute.MirroredStrategy()\n else:\n strategy = tf.distribute.get_strategy()\n return strategy\n\n def fit(self, X, y, random_state=None, epochs=3, metrics=[], **kwargs):\n \"\"\"\n Fits a sentence similarity model\n\n Args:\n X: List of 2-uples: [('Sentence 1', 'Sentence 2'), ....]\n y: list of 0 (not similar) and 1s (similar)\n random_state: a random state for the train_test_split\n epochs: number_of epochs\n\n Returns:\n A fitted model\n\n \"\"\"\n # Initialises/downloads model if not trained before.\n # If trained, fits extra epochs without the transformations\n try:\n check_is_fitted(self)\n except NotFittedError:\n self.strategy = self._get_distributed_strategy()\n with self.strategy.scope():\n self.initialise_models()\n\n # Train/val split\n X_train, X_valid, y_train, y_valid = train_test_split(\n X, y, test_size=self.test_size, random_state=random_state\n )\n\n # Generates tensorflow dataset\n\n self.train_dataset = self._prep_dataset_generator(X_train, y_train,\n shuffle=True,\n repeat=True,\n batch_size=self.batch_size)\n self.valid_dataset = self._prep_dataset_generator(X_valid, y_valid,\n batch_size=self.eval_batch_size)\n\n with self.strategy.scope():\n self._compile_model()\n\n self.train_steps = math.ceil(len(X_train)/self.batch_size)\n self.valid_steps = math.ceil(len(X_valid)/self.eval_batch_size)\n finally:\n callback_objs = [\n # Issue #187\n # MetricMiniBatchHistory()\n ]\n if self.tensorboard_log_path:\n datetime_str = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n tensorboard = tf.keras.callbacks.TensorBoard(\n log_dir=f\"{self.tensorboard_log_path}/scalar/{datetime_str}\"\n )\n callback_objs.append(tensorboard)\n self.logger.info(\"Fitting model\")\n history = self.model.fit(\n self.train_dataset,\n epochs=epochs,\n steps_per_epoch=self.train_steps,\n validation_steps=self.valid_steps,\n validation_data=self.valid_dataset,\n callbacks=callback_objs,\n verbose=self.verbose,\n **kwargs\n )\n\n # Accumulates history of metrics from different partial fits\n for metric, values in history.history.items():\n self.history[metric] += values\n\n self.trained_ = True\n\n return self\n\n def predict_proba(self, X):\n \"\"\"\n Calculates scores for model prediction\n\n Args:\n X: List of 2-uples: [('Sentence 1', 'Sentence 2'), ....]\n\n Returns:\n An array of shape len(X) x 2 with scores for classes 0 and 1\n\n \"\"\"\n # I didn't quite get to the bottom of this error, but with mirrored strategy predicting\n # I need to predict \"manually\" by calling the model.\n # Any progress on this can be tracked on #241\n\n if isinstance(self.strategy, tf.distribute.MirroredStrategy):\n predictions = []\n for batch in self._prep_dataset_generator(X):\n predictions += [self.model(batch).logits]\n\n predictions = tf.concat(predictions, axis=0)\n else:\n predictions = self.model.predict(self._prep_dataset_generator(X)).logits\n\n return tf.nn.softmax(predictions).numpy()\n\n def predict(self, X):\n \"\"\"\n Calculates the predicted class (0 - for negative and 1 for positive)\n for X.\n\n Args:\n X: List of 2-uples: [('Sentence 1', 'Sentence 2'), ....]\n\n Returns:\n An array of 0s and 1s\n\n \"\"\"\n return self.predict_proba(X).argmax(axis=1)\n\n def save(self, path):\n \"\"\"Saves model to path\"\"\"\n os.makedirs(path, exist_ok=True)\n self.model.save_pretrained(path)\n\n def load(self, path):\n \"\"\"Loads model from path\"\"\"\n self.strategy = self._get_distributed_strategy()\n\n with self.strategy.scope():\n self.initialise_models()\n self.model = TFBertForSequenceClassification.from_pretrained(path)\n self.trained_ = True\n\n\nclass SemanticEquivalenceMetaClassifier(SemanticEquivalenceClassifier):\n \"\"\"\n Class to fine tune Semantic Classifier, allowing the possibility of\n adding metadata to the classification. Extends\n SemanticEquivalenceClassifier, and extends modules for data prep\n and model initialisation. Fit, predict, predict_proba remain intact\n \"\"\"\n\n def __init__(self, n_numerical_features, dropout_rate=0,\n batch_norm=False, **kwargs):\n \"\"\"\n Initialises SemanticEquivalenceMetaClassifier, with n_numerical_features\n\n Args:\n n_numerical_features(int): Number of features of the model which\n are not text\n dropout_rate(float): Dropout rate after concatenating features\n (default = 0, i.e. no dropout)\n batch_norm(bool): Whether to apply batch normalisation after the\n last dense layer\n **kwargs: Any kwarg to `SemanticEquivalenceClassifier`\n \"\"\"\n super().__init__(**kwargs)\n self.n_numerical_features = n_numerical_features\n self.batch_norm = batch_norm\n self.dropout_rate = dropout_rate\n self.model = None\n\n def _separate_features(self, X):\n X_text = [x[:2] for x in X]\n X_numerical = [x[2: 2 + self.n_numerical_features] for x in X]\n\n return X_text, X_numerical\n\n def initialise_models(self):\n \"\"\"Extends/overrides super class initialisation of model\"\"\"\n super_model = super().initialise_models()\n\n # Define text input features\n text_features = [\"input_ids\", \"attention_mask\", \"token_type_ids\"]\n input_text_tensors = [\n tf.keras.layers.Input(\n name=feature_name, shape=tf.TensorShape([None]), dtype=tf.int32\n )\n for feature_name in text_features\n ]\n\n input_numerical_data_tensor = [\n tf.keras.layers.Input(\n name=\"numerical_metadata\",\n shape=tf.TensorShape([self.n_numerical_features]),\n dtype=tf.float32,\n )\n ]\n # Calls the CLS layer of Bert\n x = super_model.bert(input_text_tensors)[1]\n\n # Drop out layer to the Bert features if rate > 0\n x = (tf.keras.layers.Dropout(self.dropout_rate)(x)\n if self.dropout_rate > 0 else x)\n\n # Concatenates with numerical features\n x = tf.keras.layers.concatenate(\n [x, input_numerical_data_tensor[0]], name=\"concatenate\"\n )\n\n # Batch norm to the concatenated layer if self.batch_norm=True\n x = (tf.keras.layers.BatchNormalization(name=\"batch_norm\")(x)\n if self.batch_norm else x)\n\n # Dense layer that will be used for softmax prediction later\n x = tf.keras.layers.Dense(2, name=\"dense_layer\")(x)\n\n self.model = tf.keras.Model(input_text_tensors +\n input_numerical_data_tensor, x)\n\n def _prep_dataset_generator(self, X, y=None, shuffle=False, repeat=False, batch_size=32):\n \"\"\"Overrides/extends the super class data preparation\"\"\"\n text_features = [\"input_ids\", \"attention_mask\", \"token_type_ids\"]\n X_text, X_numerical = self._separate_features(X)\n\n batch_encoding_text = self.tokenizer.batch_encode_plus(\n X_text, max_length=self.max_length, add_special_tokens=True,\n )\n\n if y is None:\n input_element_types = (\n {\n **{feature: tf.int32 for feature in text_features},\n **{\"numerical_metadata\": tf.float32},\n }\n )\n input_element_tensors = (\n {\n **{feature: tf.TensorShape([None]) for feature in text_features},\n **{\"numerical_metadata\": tf.TensorShape([self.n_numerical_features])},\n }\n )\n else:\n input_element_types = (\n {\n **{feature: tf.int32 for feature in text_features},\n **{\"numerical_metadata\": tf.float32},\n },\n tf.int64,\n )\n input_element_tensors = (\n {\n **{feature: tf.TensorShape([None]) for feature in text_features},\n **{\"numerical_metadata\": tf.TensorShape([self.n_numerical_features])},\n },\n tf.TensorShape([]),\n )\n\n def gen_train():\n for i in range(len(X)):\n features_dict = {\n k: pad(batch_encoding_text[k][i], self.max_length)\n for k in batch_encoding_text\n }\n features_dict[\"numerical_metadata\"] = X_numerical[i]\n\n if y is None:\n yield features_dict\n else:\n yield (features_dict, int(y[i]))\n\n dataset = tf.data.Dataset.from_generator(\n gen_train, input_element_types, input_element_tensors,\n )\n\n if shuffle:\n dataset = dataset.shuffle(self.buffer_size, seed=self.random_seed)\n\n dataset = dataset.batch(batch_size)\n if repeat:\n dataset = dataset.repeat(-1)\n\n return dataset\n\n def fit(self, X, y, **kwargs):\n \"\"\"\n Fits semantic classifier\n\n Args:\n X(list of t-uples): Assumes that each element x of X has length\n 2+n_numerical_features, the first two components are texts and\n remaining components are numerical features (e.g.)\n y: list of 0 (not similar) and 1s (similar)\n random_state: a random state for the train_test_split\n epochs: number_of epochs\n\n Returns:\n Array of probabilities, of shape len(X) x 2\n\n \"\"\"\n return super().fit(X, y, **kwargs)\n\n def predict_proba(self, X):\n \"\"\"\n Calculates scores for metadata semantic classifier.\n\n Args:\n X(list of t-uples): Assumes that each element x of X has length\n 2+n_numerical_features, the first two components are texts and\n remaining components are numerical features (e.g.)\n\n Returns:\n Numpy array of probabilities, of shape len(X) x 2\n\n \"\"\"\n predictions = self.model.predict(self._prep_dataset_generator(X))\n\n return tf.nn.softmax(predictions).numpy()\n\n def predict(self, X):\n \"\"\"\n Calculates scores for metadata semantic classifier.\n\n Args:\n X(list of t-uples): Assumes that each element x of X has length\n 2+n_numerical_features, the first two components are texts and\n remaining components are numerical features (e.g.)\n\n Returns:\n Array of predictions of length len(X)\n\n \"\"\"\n return super().predict(X)\n\n def save(self, path):\n \"\"\"Saves meta model to path\"\"\"\n self.model.save(path)\n\n def load(self, path):\n \"\"\"Loads metamodel from path\"\"\"\n strategy = self._get_distributed_strategy()\n with strategy.scope():\n self.initialise_models()\n self.model = tf.keras.models.load_model(path)\n self.trained_ = True\n\n\ndef pad(x, pad_len):\n \"\"\"Old versions of transformers do not pad by default\"\"\"\n return x + [0] * (pad_len - len(x))\n"
] |
[
[
"tensorflow.keras.models.load_model",
"sklearn.utils.validation.check_is_fitted",
"tensorflow.concat",
"tensorflow.config.list_physical_devices",
"tensorflow.data.Dataset.from_generator",
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.TensorShape",
"tensorflow.keras.layers.Dense",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.Model",
"tensorflow.distribute.get_strategy",
"tensorflow.nn.softmax",
"tensorflow.keras.metrics.SparseCategoricalAccuracy",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Dropout",
"tensorflow.distribute.MirroredStrategy"
]
] |
oscillating-gate/eurorack
|
[
"35bf03aa35b01a7a4a9b0a0ca2898677cd3a9f6a"
] |
[
"streams/resources/waveforms.py"
] |
[
"#!/usr/bin/python2.5\n#\n# Copyright 2014 Olivier Gillet.\n#\n# Author: Olivier Gillet (ol.gillet@gmail.com)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# \n# See http://creativecommons.org/licenses/MIT/ for more information.\n#\n# -----------------------------------------------------------------------------\n#\n# Lookup table definitions.\n\nimport numpy\n\n\"\"\"----------------------------------------------------------------------------\nVactrol saturation waveshaper\n----------------------------------------------------------------------------\"\"\"\n\nWAVESHAPER_SIZE = 1024\n\nx = numpy.arange(0, WAVESHAPER_SIZE + 1) / float(WAVESHAPER_SIZE)\nx = numpy.exp(-10 * numpy.exp(-13 * x))\n# Add a slight slope\nx += 0.1 * (x ** 0.05)\nx = x - x.min()\nx /= x.max()\nwaveforms = [('gompertz', 32767.0 * x)]\n\n\n\"\"\"----------------------------------------------------------------------------\nLinear to dB, for display\n----------------------------------------------------------------------------\"\"\"\n\ndb = numpy.arange(0, 257)\ndb[0] = 1\ndb[db > 255] = 255\ndb = numpy.log2(db / 16.0) * 32768 / 4\nwaveforms += [('db', db)]\n"
] |
[
[
"numpy.arange",
"numpy.exp",
"numpy.log2"
]
] |
AWehrhahn/exoplanet_transit_snr
|
[
"f1bdaddb89e1c8b819651bcd2d80ed95d2a1fc0f",
"f1bdaddb89e1c8b819651bcd2d80ed95d2a1fc0f"
] |
[
"exoplanet_transit_snr/petitradtrans.py",
"examples/plot_samples.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom typing import Tuple\nfrom unittest import runner\n\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.units import Quantity\n\ntry:\n # Importing petitRADTRANS takes forever...\n import petitRADTRANS as prt\n from petitRADTRANS import nat_cst as nc\n\nexcept (ImportError, IOError):\n prt = None\n print(\n \"petitRadtrans could not be imported, \"\n \"please fix that if you want to use it for model spectra\"\n )\n\n\nclass petitRADTRANS:\n def __init__(\n self,\n wmin,\n wmax,\n line_species=(\"H2O\", \"CO\", \"CH4\", \"CO2\"),\n rayleigh_species=(\"H2\", \"He\"),\n continuum_species=(\"H2-H2\", \"H2-He\"),\n mass_fractions={\n \"H2\": 0.74,\n \"He\": 0.24,\n \"H2O\": 1e-3,\n \"CO\": 1e-2,\n \"CO2\": 1e-5,\n \"CH4\": 1e-6,\n },\n ):\n if prt is None:\n raise RuntimeError(\"petitRadtrans could not be imported\")\n\n # Initialize atmosphere\n # including the elements in the atmosphere\n wmin = wmin.to_value(\"um\")\n wmax = wmax.to_value(\"um\")\n self.atmosphere = prt.Radtrans(\n line_species=line_species,\n rayleigh_species=rayleigh_species,\n continuum_opacities=continuum_species,\n wlen_bords_micron=[wmin, wmax],\n mode=\"lbl\",\n )\n\n # Pressure in bar\n # has to be equispaced in log\n self.pressures = np.logspace(-6, 0, 100)\n self.atmosphere.setup_opa_structure(self.pressures)\n\n # Define mass fractions\n self.mass_fractions = {}\n for elem, frac in mass_fractions.items():\n self.mass_fractions[elem] = frac * np.ones_like(self.pressures)\n\n # TODO: should this be changed depending on the molecules?\n self.mmw = 2.33 * np.ones_like(self.pressures)\n\n # Parameters for the TP profile\n self.kappa_IR = 0.01 # opacity in the IR\n self.gamma = 0.4 # ratio between the opacity in the optical and the IR\n\n self.r_pl = None\n self.gravity = None\n self.p0 = None\n self.T_int = None\n self.T_equ = None\n self.temperature = None\n\n def init_temp_press_profile(self, star, planet):\n # Define planet parameters\n # Planet radius\n self.r_pl = planet.radius.to_value(\"cm\")\n self.r_star = star.radius.to_value(\"cm\")\n # surface gravity\n self.gravity = planet.surface_gravity.to_value(\"cm/s**2\")\n # reference pressure (for the surface gravity and radius)\n # TODO: ????\n self.p0 = planet.atm_surface_pressure.to_value(\"bar\")\n\n # Define temperature pressure profile\n self.T_int = 200.0 # Internal temperature\n self.T_equ = planet.equilibrium_temperature(star.teff, star.radius).to_value(\n \"K\"\n )\n self.temperature = nc.guillot_global(\n self.pressures,\n self.kappa_IR,\n self.gamma,\n self.gravity,\n self.T_int,\n self.T_equ,\n )\n\n def run(self) -> Tuple[Quantity, np.ndarray]:\n if self.temperature is None:\n raise RuntimeError(\"Initialize the Temperature-Pressure Profile first\")\n\n # Calculate transmission spectrum\n self.atmosphere.calc_transm(\n self.temperature,\n self.mass_fractions,\n self.gravity,\n self.mmw,\n R_pl=self.r_pl,\n P0_bar=self.p0,\n )\n\n # Wavelength in um\n wave = nc.c / self.atmosphere.freq / 1e-4\n wave = wave << u.um\n\n # Normalized transmission spectrum\n # Step 1: transmission radius in units of the stellar radius\n flux = self.atmosphere.transm_rad / self.r_star\n # flux -= flux.min()\n # flux /= flux.max()\n # Step 2: Get the \"area\" that is covered by the planet\n flux = 1 - flux ** 2\n\n return wave, flux\n",
"# -*- coding: utf-8 -*-\nimport corner\nimport emcee\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy import units as u\nfrom exoorbit.orbit import Orbit\n\nfrom exoplanet_transit_snr.stellardb import StellarDb\n\nstar, planet = \"WASP-107\", \"b\"\ndatasets = {50: \"WASP-107b_SNR50\", 100: \"WASP-107b_SNR100\", 200: \"WASP-107b_SNR200\"}\n\n# Load the nominal data for this star and planet from simbad/nasa exoplanet archive\nsdb = StellarDb()\nstar = sdb.get(star)\nplanet = star.planets[planet]\norbit = Orbit(star, planet)\nrv = orbit.radial_velocity_semiamplitude_planet()\n\nsnr = 200\nnsysrem = 5\nfname = f\"MCMC_{star.name}_{planet.name}_SNR{snr}_sysrem{nsysrem}.h5\"\n# fname = \"mcmc_samples.npy\"\n\nndim = 10\nnwalkers = 32\nlabels = [\"a\", \"v_sys\", \"mass\", \"radius\", \"sma\", \"per\", \"inc\", \"ecc\", \"w\", \"t0\"]\ntruths = np.array(\n [\n 1,\n star.radial_velocity.to_value(u.km / u.s),\n planet.mass.to_value(u.M_jup),\n planet.radius.to_value(u.R_jup),\n planet.sma.to_value(u.AU),\n planet.period.to_value(u.day),\n planet.inc.to_value(u.deg),\n planet.ecc.to_value(u.one),\n planet.omega.to_value(u.deg),\n planet.t0.mjd,\n ]\n)\n\nsampler = emcee.backends.HDFBackend(fname)\nsamples = sampler.get_chain()\n# samples = np.load(fname)\n\ntau = emcee.autocorr.integrated_time(samples, quiet=True)\n# tau = sampler.get_autocorr_time()\nburnin = int(2 * np.max(tau))\nthin = int(0.5 * np.min(tau))\n\n\n# Print results\nfig, axes = plt.subplots(ndim, figsize=(10, 7), sharex=True)\nfor i in range(ndim):\n ax = axes[i]\n ax.plot(samples[:, :, i], \"k\", alpha=0.3)\n ax.set_xlim(0, len(samples))\n ax.set_ylabel(labels[i])\n ax.yaxis.set_label_coords(-0.1, 0.5)\naxes[-1].set_xlabel(\"step number\")\nplt.show()\n\n# sampler.get_chain(discard=2000, flat=True)\n# ranges=[(1.0, 1.015), (-150, 150), (0, 1), (0, 2), (0, 5), (0, 10), (70, 110), (0, 1), (40, 160), 0.99]\nranges = [0.9] * len(labels)\nflat_samples = samples[burnin::thin].reshape((-1, ndim))\nfig = corner.corner(flat_samples, labels=labels, truths=truths, range=ranges)\nplt.show()\n\nfor i in range(ndim):\n low, mid, upp = np.percentile(flat_samples[:, i], [16, 50, 84], axis=0)\n sigma = (upp - low) / 2\n print(f\"{labels[i]}: {mid:.5g} + {upp-mid:.5g} - {mid-low:.5g} ; {truths[i]:.5g}\")\n\n# a: 1.0065 + 0.00016413 - 0.00014236 ; 1\n# v_sys: 12.922 + 31.738 - 30.919 ; 13.74\n# mass: 4.1251 + 4.2402 - 3.6097 ; 0.096\n# per: 12.947 + 20.586 - 7.4242 ; 5.7215\n# inc: 91.563 + 41.107 - 65.425 ; 89.56\n# ecc: 0.49631 + 0.32373 - 0.37054 ; 0.06\n# w: 96.66 + 29.538 - 38.358 ; 90\n# t0: 57578 + 61.426 - 164.84 ; 57584\n"
] |
[
[
"numpy.logspace",
"numpy.ones_like"
],
[
"numpy.min",
"matplotlib.pyplot.subplots",
"numpy.percentile",
"numpy.max",
"matplotlib.pyplot.show"
]
] |
awakenting/master-thesis
|
[
"d612c3b240b2d7325cac6fbf9c85c3d81250b558"
] |
[
"code/figure_scripts/figure_3_15_expm_fit_posteriors.py"
] |
[
"import os\nimport numpy as np\n\nimport matplotlib as mpl\n\nmpl.use(\"pgf\")\ngeneral_fontsize = 20\ncuston_pgf_rcparams = {\n 'font.family': 'serif',\n 'font.serif': 'cm',\n 'font.size': general_fontsize,\n 'xtick.labelsize': general_fontsize,\n 'ytick.labelsize': general_fontsize,\n 'axes.labelsize': general_fontsize,\n 'axes.titlesize': general_fontsize,\n 'legend.fontsize': general_fontsize - 2,\n 'legend.borderaxespad': 0.5,\n 'legend.borderpad': 0.4,\n 'legend.columnspacing': 2.0,\n 'legend.edgecolor': '0.8',\n 'legend.facecolor': 'inherit',\n 'legend.fancybox': True,\n 'legend.framealpha': 0.8,\n 'legend.frameon': True,\n 'legend.handleheight': 0.7,\n 'legend.handlelength': 2.0,\n 'legend.handletextpad': 0.8,\n 'legend.labelspacing': 0.5,\n 'legend.loc': 'best',\n 'legend.markerscale': 1.0,\n 'legend.numpoints': 1,\n 'legend.scatterpoints': 1,\n 'legend.shadow': False,\n 'text.usetex': True # use inline math for ticks\n}\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nfrom delfi.utils import viz\n\nfigure_path = './figures/results/'\nif not os.path.exists(figure_path):\n os.makedirs(figure_path)\n\nsns.set()\nsns.set_palette('colorblind')\nsns_colors = sns.color_palette()\nmpl.rcParams.update(custon_pgf_rcparams)\n\nexpm_fit_df = pd.read_hdf('./data/generated/fitting_expm_data.hdf5', key='fitting_results')\n\nexpfit_posterior = expm_fit_df['posterior_object'][0]\n\nlims = np.array([[0, 5],[0, 5], [0, 5], [5, 10]])\nfig, axes = viz.plot_pdf(expfit_posterior.xs[0], lims=lims, labels_params=['rho_null', 'rho_null_std', 'noise_std', 'rho_scale'],\n figsize=(12,12), ticks=True, col1=sns_colors[1], col2=sns_colors[0])\naxes[0, 0].set_xlabel(r'$\\mu_{\\rho_{0}}$')\naxes[1, 1].set_xlabel(r'$\\sigma_{\\rho_{0}}$')\naxes[2, 2].set_xlabel(r'$\\sigma_{m}$')\naxes[3, 3].set_xlabel(r'$c_{\\rho}$')\n\nfor ax in [axes[0, 0], axes[1, 1], axes[2, 2]]:\n ax.set_xticks(np.arange(6))\n ax.set_xticklabels(np.arange(6))\n\naxes[3, 3].set_xticks(np.arange(5, 11))\naxes[3, 3].set_xticklabels(np.arange(5, 11))\n\n\n#plt.show()\nplt.savefig(os.path.join(figure_path, 'figure_expm_fit_posterior.pdf'), bbox_inches='tight')\n"
] |
[
[
"pandas.read_hdf",
"numpy.arange",
"matplotlib.use",
"matplotlib.rcParams.update",
"numpy.array"
]
] |
skelton-group/FitLib
|
[
"84481cbcdae2bf0575e162717866b4035187d57a"
] |
[
"FitLib/Fitter.py"
] |
[
"# FitLib/Fitter.py\n\n\n# ----------------\n# Module Docstring\n# ----------------\n\n\"\"\" Main Fitter class. \"\"\"\n\n\n# -------\n# Imports\n# -------\n\nimport math\n\nimport numpy as np\n\nfrom scipy.optimize import minimize\n\nfrom FitLib.Function import Function\n\n\n# ------------\n# Fitter Class\n# ------------\n\nclass Fitter:\n \"\"\" Main class for fitting datasets. \"\"\"\n \n # -----------\n # Constructor\n # -----------\n \n def __init__(self, data_set_or_data_sets, func_or_func_set, fit_range = None):\n \"\"\"\n Constructor.\n \n Args:\n data_set_or_data_sets -- (x, y) tuple or iterable of (x, y) tuples containing data sets to be fitted\n func_or_func_set -- Function object or iterable of Function objects to be fitted against each data set\n fit_range -- (x_min, x_max) range over which to fit data sets (default: None)\n \n Notes:\n To fit a data set against multiple functions, combine them into a CompositeFunction object first.\n \"\"\"\n \n # Check and convert data to NumPy arrays.\n \n assert data_set_or_data_sets is not None\n \n shape = np.shape(data_set_or_data_sets)\n \n if len(shape) == 2:\n # Assume data_or_data_sets is a single data set.\n \n data_set_or_data_sets = [data_set_or_data_sets]\n \n data_sets = []\n \n for x, y in data_set_or_data_sets:\n x = np.asarray(x, dtype = np.float64)\n y = np.asarray(y, dtype = np.float64)\n \n n_x, = x.shape\n n_y, = y.shape\n \n assert n_x > 0 and n_x == n_y\n \n data_sets.append((x, y))\n \n self._data_sets = data_sets\n \n # Check and store fitting functions.\n \n func_set = None\n \n if isinstance(func_or_func_set, Function):\n # Single function -> wrap in a list.\n \n func_set = [func_or_func_set]\n else:\n # Assume func_or_func_sets is an iterable of Function objects.\n \n func_set = [func for func in func_or_func_set]\n \n for func in func_set:\n assert isinstance(func, Function)\n \n self._func_set = func_set \n \n # Check and store fit range, if supplied.\n \n self._fit_range = None\n \n if fit_range is not None:\n self.FitRange = fit_range\n \n # Field to hold fit result.\n \n self._fit_res = None\n\n # ---------------\n # Private Methods\n # ---------------\n\n def _GetFitParamsList(self):\n \"\"\" Build a flat list of unique Parameter objects to be fitted across all functions. \"\"\"\n \n params_list = []\n \n for func in self._func_set:\n for param in func.GetParamsList(fit_only = True):\n # Collect a list of unique Parameter objects to be fitted.\n # This allows for some Functions to transparently share Parameter objects.\n \n if param not in params_list:\n params_list.append(param)\n \n return params_list\n \n def _FitFunction(self, param_vals):\n \"\"\" Update parameters across all functions to be fitted and return root-mean-square error averaged over datasets. \"\"\"\n \n # Update fit function parameters and return the root-mean-square (RMS) error averaged over data sets.\n \n params = self._GetFitParamsList()\n \n assert len(params) == len(param_vals)\n \n for param, val in zip(params, param_vals):\n param.Value = val\n \n return np.mean(\n self.EvaluateFitError(strip_dims = False)\n )\n\n # ----------\n # Properties\n # ----------\n\n @property\n def FitRange(self):\n \"\"\" Get the range of x values used for fitting: an (x_min, x_max) tuple of None. \"\"\"\n \n return self._fit_range\n \n @FitRange.setter\n def FitRange(self, fit_range):\n \"\"\" Set the range of x values used for fitting: either a set of (x_min, x_max) values or None. \"\"\"\n \n if fit_range is not None:\n # Convert to a tuple of (x_min, x_max) values.\n \n x_min, x_max = fit_range\n \n fit_range = (\n float(x_min), float(x_max)\n )\n \n self._fit_range = fit_range\n \n @property\n def FitResult(self):\n \"\"\" Get the fit result returned by scipy.optimize.minimize(). \"\"\"\n \n return self._fit_res\n \n # --------------\n # Public Methods\n # --------------\n \n def Fit(self, **kwargs):\n \"\"\"\n Fit data and return root-mean-square (RMS) error averaged over data sets.\n \n Notes:\n Keyword arguments are passed directly to the scipy.optimize.minimize() function.\n \"\"\"\n \n params = self._GetFitParamsList()\n \n fit_p_init, fit_p_bounds = [], []\n \n for param in params:\n fit_p_init.append(param.Value)\n fit_p_bounds.append(param.Bounds)\n \n fit_res = minimize(self._FitFunction, fit_p_init, bounds = fit_p_bounds, **kwargs)\n \n self._fit_res = fit_res\n \n return fit_res.fun\n \n def EvaluateFit(self, strip_dims = True):\n \"\"\"\n Evaluate current fit(s) and return a list of (x, y, y_fit) tuples for each data set.\n \n Args:\n strip_dims -- if True (default), return a single (x, y, y_fit) tuple rather than a list if a single data set is being fitted\n \"\"\"\n \n fit_eval = []\n \n for (x, y), func in zip(self._data_sets, self._func_set):\n # If a fit range has been set, adjust the data if required.\n \n if self._fit_range is not None:\n x_min, x_max = self._fit_range\n \n mask = np.logical_and(\n x >= x_min, x <= x_max\n )\n \n assert mask.sum() > 0\n \n x, y = x[mask], y[mask]\n \n y_fit = func.Evaluate(x)\n \n fit_eval.append((x, y, y_fit))\n \n # If strip_dims is set and only a single data set is being fit, return a single (x, y, y_fit) tuple.\n \n if strip_dims and len(fit_eval) == 1:\n return fit_eval[0]\n else:\n return fit_eval\n \n def EvaluateFitError(self, strip_dims = True):\n \"\"\"\n Calculate the root-mean-square (RMS) error for the current fit(s).\n \n Args:\n strip_dims -- if True (default), return a single RMS value rather than a list if a single data set is being fitted\n \"\"\"\n \n rms_errors = []\n \n for _, y, y_fit in self.EvaluateFit(strip_dims = False):\n rms_errors.append(\n math.sqrt(np.mean((y - y_fit) ** 2))\n )\n \n # If strip_dims is set and only a single data set is being fit, return a single error value.\n \n if strip_dims and len(rms_errors) == 1:\n return rms_errors[0]\n else:\n return rms_errors\n \n def EvaluateNew(self, x, strip_dims = True):\n \"\"\"\n Evaluate current fit(s) on a new set of x values.\n\n Args:\n strip_dims -- if True (default), return a single NumPy array rather than a list if a single data set is being fitted\n\n Notes:\n This method ignores the fitting range, if specified.\n \"\"\"\n \n # Evaluate current fits with supplied x values.\n \n fit_eval = [\n func.Evaluate(x) for func in self._func_set\n ]\n \n # If strip_dims is set and only a single data set is being fit, return a single NumPy array.\n \n if strip_dims and len(fit_eval) == 1:\n return fit_eval[0]\n else: \n return fit_eval\n \n def GetParamsList(self, strip_dims = True):\n \"\"\"\n Collect a set of parameter lists for each function being fitted.\n\n Args:\n strip_dims -- if True (default), return a single list of parameters if a single data set is being fitted\n \"\"\"\n \n params_list = [\n func.GetParamsList() for func in self._func_set\n ]\n \n # If strip_dims is set and only a single data set is being fit, return a single list of parameters.\n \n if strip_dims and len(params_list) == 1:\n return params_list[0]\n else:\n return params_list\n"
] |
[
[
"numpy.asarray",
"scipy.optimize.minimize",
"numpy.shape",
"numpy.mean",
"numpy.logical_and"
]
] |
pablohawz/tfg-Scan-Paint-clone
|
[
"056cd50d9e4274620cf085a41ed9d326e16dd47b"
] |
[
"app/__main__.py"
] |
[
"# This Python file uses the following encoding: utf-8\nfrom app.package.views.Calibrate_view import CalibrateView\nfrom app.package.controllers.Calibrate_controller import CalibrateController\nfrom app.package.models.Calibrate_model import CalibrateModel\nimport sys\nimport matplotlib\n\nfrom PySide2.QtWidgets import QApplication\nfrom PySide2 import QtCore\n\nfrom .package.models.NewProjectModel import NewProjectModel\nfrom .package.models.DataAcquisitionModel import DataAcquisitionModel\nfrom .package.models.DisplayResultsModel import DisplayResultsModel\n\nfrom .package.controllers.Navigator import Navigator\nfrom .package.controllers.NewProjectController import NewProjectController\nfrom .package.controllers.DataAcquisitionController import (\n DataAcquisitionController)\nfrom .package.controllers.DisplayResultsController import (\n DisplayResultsController)\n\nfrom .package.views.MainWindow import MainWindow\nfrom .package.views.NewProjectView import NewProjectView\nfrom .package.views.DataAcquisitionView import DataAcquisitionView\nfrom .package.views.DisplayResultsView import DisplayResultsView\n\n\nclass App(QApplication):\n\n # Diccionario que mapea nombres con Vistas\n views = {}\n\n @staticmethod\n def log(msg: str) -> None:\n print(f'[App] {msg}')\n\n def __init__(self, args):\n super(App, self).__init__(args)\n\n self.navigator = Navigator()\n self.navigator.navigator.connect(self.change_view)\n\n # MODELS\n self.new_project_model = NewProjectModel()\n self.data_acquisition_model = DataAcquisitionModel()\n self.display_results_model = DisplayResultsModel()\n self.calibrate_model = CalibrateModel()\n\n # CONTROLLERS\n self.new_project_controller = NewProjectController(\n self.new_project_model, self.navigator)\n self.data_acquisition_controller = DataAcquisitionController(\n self.data_acquisition_model, self.navigator)\n self.display_results_controller = DisplayResultsController(\n self.display_results_model, self.navigator)\n self.calibrate_controller = CalibrateController(\n self.calibrate_model, self.navigator)\n\n # VIEWS\n self.main_view = MainWindow(None, self.navigator)\n self.new_project_view = NewProjectView(\n self.new_project_model, self.new_project_controller)\n self.data_acquisition_view = DataAcquisitionView(\n self.data_acquisition_model, self.data_acquisition_controller)\n self.display_results_view = DisplayResultsView(\n self.display_results_model, self.display_results_controller)\n self.calibrate_view = CalibrateView(\n self.calibrate_model, self.calibrate_controller)\n\n self.views['main_view'] = self.main_view\n self.views['new_project'] = self.new_project_view\n self.views['data_acquisition'] = self.data_acquisition_view\n self.views['display_results'] = self.display_results_view\n self.views['calibrate'] = self.calibrate_view\n\n self.change_view('new_project')\n\n @QtCore.Slot(str)\n def change_view(self, name_view, closeOthers=True):\n self.log(f'Navigating to {name_view}')\n _view = self.views.get(name_view)\n\n if _view is None:\n raise Exception(f'{name_view} is not part of Views dictionary.')\n\n if closeOthers:\n self.log('closing other views...')\n for view in self.views:\n if view != name_view:\n self.views.get(view).close()\n\n _view.open()\n\n\nsys._excepthook = sys.excepthook\n\n\ndef exception_hook(exctype, value, traceback):\n print(exctype, value, traceback)\n sys._excepthook(exctype, value, traceback)\n sys.exit(1)\n\n\nsys.excepthook = exception_hook\n\n\ndef main():\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)\n app = App([])\n sys.exit(app.exec_())\n\n\nmatplotlib.use('tkagg')\n\nif __name__ == \"__main__\":\n main()\n\n# if __name__ == \"__main__\":\n# import cProfile\n\n# cProfile.run('main()', 'output.dat')\n\n# import pstats\n# from pstats import SortKey\n\n# with open(\"output_time.dat\", \"w\") as f:\n# p = pstats.Stats(\"output.dat\", stream=f)\n# p.sort_stats(\"time\").print_stats()\n\n# with open(\"output_calls.dat\", \"w\") as f:\n# p = pstats.Stats(\"output.dat\", stream=f)\n# p.sort_stats(\"calls\").print_stats()\n"
] |
[
[
"matplotlib.use"
]
] |
leimao/Rotated_Rectangle_Crop_OpenCV
|
[
"716ed23fda7d9034b80ce9b1927c612c914ff74d"
] |
[
"rotated_rect_crop.py"
] |
[
"# Image Preprocessing Utilities\n# Lei Mao\n# University of Chicago\n# 3/1/2018\n\nimport cv2\nimport numpy as np\n\n\ndef inside_rect(rect, num_cols, num_rows):\n # Determine if the four corners of the rectangle are inside the rectangle with width and height\n # rect tuple\n # center (x,y), (width, height), angle of rotation (to the row)\n # center The rectangle mass center.\n # center tuple (x, y): x is regarding to the width (number of columns) of the image, y is regarding to the height (number of rows) of the image.\n # size Width and height of the rectangle.\n # angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.\n # Return:\n # True: if the rotated sub rectangle is side the up-right rectange\n # False: else\n\n rect_center = rect[0]\n rect_center_x = rect_center[0]\n rect_center_y = rect_center[1]\n\n rect_width, rect_height = rect[1]\n\n rect_angle = rect[2]\n\n if (rect_center_x < 0) or (rect_center_x > num_cols):\n return False\n if (rect_center_y < 0) or (rect_center_y > num_rows):\n return False\n\n # https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html\n box = cv2.boxPoints(rect)\n\n x_max = int(np.max(box[:,0]))\n x_min = int(np.min(box[:,0]))\n y_max = int(np.max(box[:,1]))\n y_min = int(np.min(box[:,1]))\n\n if (x_max <= num_cols) and (x_min >= 0) and (y_max <= num_rows) and (y_min >= 0):\n return True\n else:\n return False\n\n\ndef rect_bbx(rect):\n # Rectangle bounding box for rotated rectangle\n # Example: \n # rotated rectangle: height 4, width 4, center (10, 10), angle 45 degree\n # bounding box for this rotated rectangle, height 4*sqrt(2), width 4*sqrt(2), center (10, 10), angle 0 degree\n\n box = cv2.boxPoints(rect)\n\n x_max = int(np.max(box[:,0]))\n x_min = int(np.min(box[:,0]))\n y_max = int(np.max(box[:,1]))\n y_min = int(np.min(box[:,1]))\n\n # Top-left\n # (x_min, y_min)\n # Top-right\n # (x_min, y_max)\n # Bottom-left\n # (x_max, y_min)\n # Bottom-right\n # (x_max, y_max)\n # Width\n # y_max - y_min\n # Height\n # x_max - x_min\n # Center\n # (x_min + x_max) // 2, (y_min + y_max) // 2\n\n center = (int((x_min + x_max) // 2), int((y_min + y_max) // 2))\n width = int(x_max - x_min)\n height = int(y_max - y_min)\n angle = 0\n\n return (center, (width, height), angle)\n\n\ndef image_rotate_without_crop(mat, angle):\n # https://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c\n # angle in degrees\n\n height, width = mat.shape[:2]\n image_center = (width/2, height/2)\n\n rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1)\n\n abs_cos = abs(rotation_mat[0,0])\n abs_sin = abs(rotation_mat[0,1])\n\n bound_w = int(height * abs_sin + width * abs_cos)\n bound_h = int(height * abs_cos + width * abs_sin)\n\n rotation_mat[0, 2] += bound_w/2 - image_center[0]\n rotation_mat[1, 2] += bound_h/2 - image_center[1]\n\n rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))\n\n return rotated_mat\n\ndef crop_rectangle(image, rect):\n # rect has to be upright\n\n num_rows = image.shape[0]\n num_cols = image.shape[1]\n\n if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):\n print(\"Proposed rectangle is not fully in the image.\")\n return None\n\n rect_center = rect[0]\n rect_center_x = rect_center[0]\n rect_center_y = rect_center[1]\n rect_width = rect[1][0]\n rect_height = rect[1][1]\n\n\n return image[rect_center_y-rect_height//2:rect_center_y+rect_height-rect_height//2, rect_center_x-rect_width//2:rect_center_x+rect_width-rect_width//2]\n\n\n\n\n\n\ndef crop_rotated_rectangle(image, rect):\n # Crop a rotated rectangle from a image\n\n num_rows = image.shape[0]\n num_cols = image.shape[1]\n\n if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):\n print(\"Proposed rectangle is not fully in the image.\")\n return None\n\n rotated_angle = rect[2]\n\n rect_bbx_upright = rect_bbx(rect = rect)\n rect_bbx_upright_image = crop_rectangle(image = image, rect = rect_bbx_upright)\n\n rotated_rect_bbx_upright_image = image_rotate_without_crop(mat = rect_bbx_upright_image, angle = rotated_angle)\n\n rect_width = rect[1][0]\n rect_height = rect[1][1]\n\n crop_center = (rotated_rect_bbx_upright_image.shape[1]//2, rotated_rect_bbx_upright_image.shape[0]//2)\n\n return rotated_rect_bbx_upright_image[crop_center[1]-rect_height//2 : crop_center[1]+(rect_height-rect_height//2), crop_center[0]-rect_width//2 : crop_center[0]+(rect_width-rect_width//2)]\n\n\n\ndef crop_rotated_rectangle_test():\n # Test function for crop_rotated_rectangle(image, rect)\n\n import matplotlib.pylab as plt\n from matplotlib import gridspec\n import numpy as np\n\n # Better to test in Jupyter Notebook\n\n img = cv2.imread('demo/pokemon.png')\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n #img = np.ones((1000, 1000), dtype=np.uint8)\n #img = cv2.line(img,(400,400),(511,511),2,120)\n #img = cv2.line(img,(300,300),(700,500),2,120)\n\n img_rows = img.shape[0]\n img_cols = img.shape[1]\n \n # Generate random rect\n \n while True:\n center = (np.random.randint(low = 1, high = img_cols), np.random.randint(low = 0, high = img_rows))\n width = np.random.randint(low = 1, high = img_cols)\n height = np.random.randint(low = 1, high = img_rows)\n angle = np.random.randint(low = 0, high = 360)\n rect = (center, (width, height), angle)\n if inside_rect(rect = rect, num_cols = img_cols, num_rows = img_rows):\n break\n \n #print(rect)\n\n box = cv2.boxPoints(rect).astype(np.int0)\n cv2.drawContours(img,[box],0,(255,0,0),3)\n cv2.arrowedLine(img, center, ((box[1][0]+box[2][0])//2,(box[1][1]+box[2][1])//2), (255,0,0), 3, tipLength = 0.2)\n\n image_cropped = crop_rotated_rectangle(image = img, rect = rect)\n '''\n plt.figure()\n plt.subplot(1,2,1)\n plt.imshow(img)\n plt.subplot(1,2,2)\n plt.imshow(image_cropped)\n plt.show()\n '''\n \n # plot it\n fig = plt.figure(figsize=(8, 6)) \n gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) \n ax0 = plt.subplot(gs[0])\n ax0.imshow(img)\n ax1 = plt.subplot(gs[1])\n ax1.imshow(image_cropped)\n\n plt.tight_layout()\n plt.savefig('demo.png', dpi=300, bbox_inches='tight')\n \n plt.show()\n \n return\n\n\nif __name__ == '__main__':\n\n crop_rotated_rectangle_test()\n\n\n"
] |
[
[
"matplotlib.pylab.tight_layout",
"matplotlib.pylab.show",
"numpy.min",
"matplotlib.pylab.subplot",
"numpy.max",
"matplotlib.pylab.figure",
"matplotlib.gridspec.GridSpec",
"matplotlib.pylab.savefig",
"numpy.random.randint"
]
] |
MattiaMolon/pytorch-YOLOv4
|
[
"552ddcad714785785c7153dc790b0ea27c53302c"
] |
[
"dataset.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2020/05/06 21:09\n@Author : Tianxiaomo\n@File : dataset.py\n@Noice :\n@Modificattion :\n @Author :\n @Time :\n @Detail :\n\n\"\"\"\nimport os\nimport random\nimport sys\nfrom typing import Tuple\n\nimport cv2\nimport numpy as np\nfrom numpy.lib.financial import ipmt\nimport pandas as pd\n\nimport torch\nfrom torch.utils.data.dataset import Dataset\nfrom easydict import EasyDict as edict\nimport matplotlib.pyplot as plt\n\n\ndef rand_uniform_strong(min, max):\n if min > max:\n swap = min\n min = max\n max = swap\n return random.random() * (max - min) + min\n\n\ndef rand_scale(s):\n scale = rand_uniform_strong(1, s)\n if random.randint(0, 1) % 2:\n return scale\n return 1.0 / scale\n\n\ndef rand_precalc_random(min, max, random_part):\n if max < min:\n swap = min\n min = max\n max = swap\n return (random_part * (max - min)) + min\n\n\ndef fill_truth_detection(bboxes, num_boxes, classes, flip, dx, dy, sx, sy, net_w, net_h):\n if bboxes.shape[0] == 0:\n return bboxes, 10000\n np.random.shuffle(bboxes)\n bboxes[:, 0] -= dx\n bboxes[:, 2] -= dx\n bboxes[:, 1] -= dy\n bboxes[:, 3] -= dy\n\n bboxes[:, 0] = np.clip(bboxes[:, 0], 0, sx)\n bboxes[:, 2] = np.clip(bboxes[:, 2], 0, sx)\n\n bboxes[:, 1] = np.clip(bboxes[:, 1], 0, sy)\n bboxes[:, 3] = np.clip(bboxes[:, 3], 0, sy)\n\n out_box = list(\n np.where(\n ((bboxes[:, 1] == sy) & (bboxes[:, 3] == sy))\n | ((bboxes[:, 0] == sx) & (bboxes[:, 2] == sx))\n | ((bboxes[:, 1] == 0) & (bboxes[:, 3] == 0))\n | ((bboxes[:, 0] == 0) & (bboxes[:, 2] == 0))\n )[0]\n )\n list_box = list(range(bboxes.shape[0]))\n for i in out_box:\n list_box.remove(i)\n bboxes = bboxes[list_box]\n\n if bboxes.shape[0] == 0:\n return bboxes, 10000\n\n bboxes = bboxes[np.where((bboxes[:, 4] < classes) & (bboxes[:, 4] >= 0))[0]]\n\n if bboxes.shape[0] > num_boxes:\n bboxes = bboxes[:num_boxes]\n\n min_w_h = np.array([bboxes[:, 2] - bboxes[:, 0], bboxes[:, 3] - bboxes[:, 1]]).min()\n\n bboxes[:, 0] *= net_w / sx\n bboxes[:, 2] *= net_w / sx\n bboxes[:, 1] *= net_h / sy\n bboxes[:, 3] *= net_h / sy\n\n if flip:\n temp = net_w - bboxes[:, 0]\n bboxes[:, 0] = net_w - bboxes[:, 2]\n bboxes[:, 2] = temp\n\n return bboxes, min_w_h\n\n\ndef rect_intersection(a, b):\n minx = max(a[0], b[0])\n miny = max(a[1], b[1])\n\n maxx = min(a[2], b[2])\n maxy = min(a[3], b[3])\n return [minx, miny, maxx, maxy]\n\n\ndef image_data_augmentation(\n mat, w, h, pleft, ptop, swidth, sheight, flip, dhue, dsat, dexp, gaussian_noise, blur, truth\n):\n try:\n img = mat\n oh, ow, _ = img.shape\n pleft, ptop, swidth, sheight = int(pleft), int(ptop), int(swidth), int(sheight)\n # crop\n src_rect = [pleft, ptop, swidth + pleft, sheight + ptop] # x1,y1,x2,y2\n img_rect = [0, 0, ow, oh]\n new_src_rect = rect_intersection(src_rect, img_rect) # 交集\n\n dst_rect = [\n max(0, -pleft),\n max(0, -ptop),\n max(0, -pleft) + new_src_rect[2] - new_src_rect[0],\n max(0, -ptop) + new_src_rect[3] - new_src_rect[1],\n ]\n # cv2.Mat sized\n\n if (\n src_rect[0] == 0\n and src_rect[1] == 0\n and src_rect[2] == img.shape[0]\n and src_rect[3] == img.shape[1]\n ):\n sized = cv2.resize(img, (w, h), cv2.INTER_LINEAR)\n else:\n cropped = np.zeros([sheight, swidth, 3])\n cropped[\n :,\n :,\n ] = np.mean(img, axis=(0, 1))\n\n cropped[dst_rect[1] : dst_rect[3], dst_rect[0] : dst_rect[2]] = img[\n new_src_rect[1] : new_src_rect[3], new_src_rect[0] : new_src_rect[2]\n ]\n\n # resize\n sized = cv2.resize(cropped, (w, h), cv2.INTER_LINEAR)\n\n # flip\n if flip:\n # cv2.Mat cropped\n sized = cv2.flip(sized, 1) # 0 - x-axis, 1 - y-axis, -1 - both axes (x & y)\n\n # HSV augmentation\n # cv2.COLOR_BGR2HSV, cv2.COLOR_RGB2HSV, cv2.COLOR_HSV2BGR, cv2.COLOR_HSV2RGB\n if dsat != 1 or dexp != 1 or dhue != 0:\n if img.shape[2] >= 3:\n hsv_src = cv2.cvtColor(sized.astype(np.float32), cv2.COLOR_RGB2HSV) # RGB to HSV\n hsv = cv2.split(hsv_src)\n hsv[1] *= dsat\n hsv[2] *= dexp\n hsv[0] += 179 * dhue\n hsv_src = cv2.merge(hsv)\n sized = np.clip(\n cv2.cvtColor(hsv_src, cv2.COLOR_HSV2RGB), 0, 255\n ) # HSV to RGB (the same as previous)\n else:\n sized *= dexp\n\n if blur:\n if blur == 1:\n dst = cv2.GaussianBlur(sized, (17, 17), 0)\n # cv2.bilateralFilter(sized, dst, 17, 75, 75)\n else:\n ksize = (blur / 2) * 2 + 1\n dst = cv2.GaussianBlur(sized, (ksize, ksize), 0)\n\n if blur == 1:\n img_rect = [0, 0, sized.cols, sized.rows]\n for b in truth:\n left = (b.x - b.w / 2.0) * sized.shape[1]\n width = b.w * sized.shape[1]\n top = (b.y - b.h / 2.0) * sized.shape[0]\n height = b.h * sized.shape[0]\n roi(left, top, width, height)\n roi = roi & img_rect\n dst[roi[0] : roi[0] + roi[2], roi[1] : roi[1] + roi[3]] = sized[\n roi[0] : roi[0] + roi[2], roi[1] : roi[1] + roi[3]\n ]\n\n sized = dst\n\n if gaussian_noise:\n noise = np.array(sized.shape)\n gaussian_noise = min(gaussian_noise, 127)\n gaussian_noise = max(gaussian_noise, 0)\n cv2.randn(noise, 0, gaussian_noise) # mean and variance\n sized = sized + noise\n except:\n print(\"OpenCV can't augment image: \" + str(w) + \" x \" + str(h))\n sized = mat\n\n return sized\n\n\ndef filter_truth(bboxes, dx, dy, sx, sy, xd, yd):\n bboxes[:, 0] -= dx\n bboxes[:, 2] -= dx\n bboxes[:, 1] -= dy\n bboxes[:, 3] -= dy\n\n bboxes[:, 0] = np.clip(bboxes[:, 0], 0, sx)\n bboxes[:, 2] = np.clip(bboxes[:, 2], 0, sx)\n\n bboxes[:, 1] = np.clip(bboxes[:, 1], 0, sy)\n bboxes[:, 3] = np.clip(bboxes[:, 3], 0, sy)\n\n out_box = list(\n np.where(\n ((bboxes[:, 1] == sy) & (bboxes[:, 3] == sy))\n | ((bboxes[:, 0] == sx) & (bboxes[:, 2] == sx))\n | ((bboxes[:, 1] == 0) & (bboxes[:, 3] == 0))\n | ((bboxes[:, 0] == 0) & (bboxes[:, 2] == 0))\n )[0]\n )\n list_box = list(range(bboxes.shape[0]))\n for i in out_box:\n list_box.remove(i)\n bboxes = bboxes[list_box]\n\n bboxes[:, 0] += xd\n bboxes[:, 2] += xd\n bboxes[:, 1] += yd\n bboxes[:, 3] += yd\n\n return bboxes\n\n\ndef blend_truth_mosaic(\n out_img, img, bboxes, w, h, cut_x, cut_y, i_mixup, left_shift, right_shift, top_shift, bot_shift\n):\n left_shift = min(left_shift, w - cut_x)\n top_shift = min(top_shift, h - cut_y)\n right_shift = min(right_shift, cut_x)\n bot_shift = min(bot_shift, cut_y)\n\n if i_mixup == 0:\n bboxes = filter_truth(bboxes, left_shift, top_shift, cut_x, cut_y, 0, 0)\n out_img[:cut_y, :cut_x] = img[top_shift : top_shift + cut_y, left_shift : left_shift + cut_x]\n if i_mixup == 1:\n bboxes = filter_truth(bboxes, cut_x - right_shift, top_shift, w - cut_x, cut_y, cut_x, 0)\n out_img[:cut_y, cut_x:] = img[top_shift : top_shift + cut_y, cut_x - right_shift : w - right_shift]\n if i_mixup == 2:\n bboxes = filter_truth(bboxes, left_shift, cut_y - bot_shift, cut_x, h - cut_y, 0, cut_y)\n out_img[cut_y:, :cut_x] = img[cut_y - bot_shift : h - bot_shift, left_shift : left_shift + cut_x]\n if i_mixup == 3:\n bboxes = filter_truth(\n bboxes, cut_x - right_shift, cut_y - bot_shift, w - cut_x, h - cut_y, cut_x, cut_y\n )\n out_img[cut_y:, cut_x:] = img[\n cut_y - bot_shift : h - bot_shift, cut_x - right_shift : w - right_shift\n ]\n\n return out_img, bboxes\n\n\ndef draw_box(img, bboxes):\n for b in bboxes:\n img = cv2.rectangle(img, (b[0], b[1]), (b[2], b[3]), (0, 255, 0), 2)\n return img\n\n\nclass Yolo_dataset(Dataset):\n def __init__(self, lable_path, cfg, train=True):\n super(Yolo_dataset, self).__init__()\n if cfg.mixup == 2:\n print(\"cutmix=1 - isn't supported for Detector\")\n raise\n elif cfg.mixup == 2 and cfg.letter_box:\n print(\"Combination: letter_box=1 & mosaic=1 - isn't supported, use only 1 of these parameters\")\n raise\n\n self.cfg = cfg\n self.train = train\n\n truth = {}\n f = open(lable_path, \"r\", encoding=\"utf-8\")\n for line in f.readlines():\n data = line.split(\" \")\n truth[data[0]] = []\n for i in data[1:]:\n truth[data[0]].append([int(float(j)) for j in i.split(\",\")])\n\n self.truth = truth\n self.imgs = list(self.truth.keys())\n\n def __len__(self):\n return len(self.truth.keys())\n\n def __getitem__(self, index):\n if not self.train:\n return self._get_val_item(index)\n img_path = self.imgs[index]\n bboxes = np.array(self.truth.get(img_path), dtype=np.float)\n img_path = os.path.join(self.cfg.dataset_dir, img_path)\n use_mixup = self.cfg.mixup\n if random.randint(0, 1):\n use_mixup = 0\n\n if use_mixup == 3:\n min_offset = 0.2\n cut_x = random.randint(int(self.cfg.w * min_offset), int(self.cfg.w * (1 - min_offset)))\n cut_y = random.randint(int(self.cfg.h * min_offset), int(self.cfg.h * (1 - min_offset)))\n\n r1, r2, r3, r4, r_scale = 0, 0, 0, 0, 0\n dhue, dsat, dexp, flip, blur = 0, 0, 0, 0, 0\n gaussian_noise = 0\n\n out_img = np.zeros([self.cfg.h, self.cfg.w, 3])\n out_bboxes = []\n\n for i in range(use_mixup + 1):\n if i != 0:\n img_path = random.choice(list(self.truth.keys()))\n bboxes = np.array(self.truth.get(img_path), dtype=np.float)\n img_path = os.path.join(self.cfg.dataset_dir, img_path)\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if img is None:\n continue\n oh, ow, oc = img.shape\n dh, dw, dc = np.array(np.array([oh, ow, oc]) * self.cfg.jitter, dtype=np.int)\n\n dhue = rand_uniform_strong(-self.cfg.hue, self.cfg.hue)\n dsat = rand_scale(self.cfg.saturation)\n dexp = rand_scale(self.cfg.exposure)\n\n pleft = random.randint(-dw, dw)\n pright = random.randint(-dw, dw)\n ptop = random.randint(-dh, dh)\n pbot = random.randint(-dh, dh)\n\n flip = random.randint(0, 1) if self.cfg.flip else 0\n\n if self.cfg.blur:\n tmp_blur = random.randint(0, 2) # 0 - disable, 1 - blur background, 2 - blur the whole image\n if tmp_blur == 0:\n blur = 0\n elif tmp_blur == 1:\n blur = 1\n else:\n blur = self.cfg.blur\n\n if self.cfg.gaussian and random.randint(0, 1):\n gaussian_noise = self.cfg.gaussian\n else:\n gaussian_noise = 0\n\n if self.cfg.letter_box:\n img_ar = ow / oh\n net_ar = self.cfg.w / self.cfg.h\n result_ar = img_ar / net_ar\n # print(\" ow = %d, oh = %d, w = %d, h = %d, img_ar = %f, net_ar = %f, result_ar = %f \\n\", ow, oh, w, h, img_ar, net_ar, result_ar);\n if result_ar > 1: # sheight - should be increased\n oh_tmp = ow / net_ar\n delta_h = (oh_tmp - oh) / 2\n ptop = ptop - delta_h\n pbot = pbot - delta_h\n # print(\" result_ar = %f, oh_tmp = %f, delta_h = %d, ptop = %f, pbot = %f \\n\", result_ar, oh_tmp, delta_h, ptop, pbot);\n else: # swidth - should be increased\n ow_tmp = oh * net_ar\n delta_w = (ow_tmp - ow) / 2\n pleft = pleft - delta_w\n pright = pright - delta_w\n # printf(\" result_ar = %f, ow_tmp = %f, delta_w = %d, pleft = %f, pright = %f \\n\", result_ar, ow_tmp, delta_w, pleft, pright);\n\n swidth = ow - pleft - pright\n sheight = oh - ptop - pbot\n\n truth, min_w_h = fill_truth_detection(\n bboxes,\n self.cfg.boxes,\n self.cfg.classes,\n flip,\n pleft,\n ptop,\n swidth,\n sheight,\n self.cfg.w,\n self.cfg.h,\n )\n if (min_w_h / 8) < blur and blur > 1: # disable blur if one of the objects is too small\n blur = min_w_h / 8\n\n ai = image_data_augmentation(\n img,\n self.cfg.w,\n self.cfg.h,\n pleft,\n ptop,\n swidth,\n sheight,\n flip,\n dhue,\n dsat,\n dexp,\n gaussian_noise,\n blur,\n truth,\n )\n\n if use_mixup == 0:\n out_img = ai\n out_bboxes = truth\n if use_mixup == 1:\n if i == 0:\n old_img = ai.copy()\n old_truth = truth.copy()\n elif i == 1:\n out_img = cv2.addWeighted(ai, 0.5, old_img, 0.5)\n out_bboxes = np.concatenate([old_truth, truth], axis=0)\n elif use_mixup == 3:\n if flip:\n tmp = pleft\n pleft = pright\n pright = tmp\n\n left_shift = int(min(cut_x, max(0, (-int(pleft) * self.cfg.w / swidth))))\n top_shift = int(min(cut_y, max(0, (-int(ptop) * self.cfg.h / sheight))))\n\n right_shift = int(min((self.cfg.w - cut_x), max(0, (-int(pright) * self.cfg.w / swidth))))\n bot_shift = int(min(self.cfg.h - cut_y, max(0, (-int(pbot) * self.cfg.h / sheight))))\n\n out_img, out_bbox = blend_truth_mosaic(\n out_img,\n ai,\n truth.copy(),\n self.cfg.w,\n self.cfg.h,\n cut_x,\n cut_y,\n i,\n left_shift,\n right_shift,\n top_shift,\n bot_shift,\n )\n out_bboxes.append(out_bbox)\n # print(img_path)\n if use_mixup == 3:\n out_bboxes = np.concatenate(out_bboxes, axis=0)\n out_bboxes1 = np.zeros([self.cfg.boxes, 5])\n out_bboxes1[: min(out_bboxes.shape[0], self.cfg.boxes)] = out_bboxes[\n : min(out_bboxes.shape[0], self.cfg.boxes)\n ]\n return out_img, out_bboxes1\n\n def _get_val_item(self, index):\n \"\"\"\"\"\"\n img_path = self.imgs[index]\n bboxes_with_cls_id = np.array(self.truth.get(img_path), dtype=np.float)\n img = cv2.imread(os.path.join(self.cfg.dataset_dir, img_path))\n # img_height, img_width = img.shape[:2]\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # img = cv2.resize(img, (self.cfg.w, self.cfg.h))\n # img = torch.from_numpy(img.transpose(2, 0, 1)).float().div(255.0).unsqueeze(0)\n num_objs = len(bboxes_with_cls_id)\n target = {}\n # boxes to coco format\n boxes = bboxes_with_cls_id[..., :4]\n boxes[..., 2:] = boxes[..., 2:] - boxes[..., :2] # box width, box height\n target[\"boxes\"] = torch.as_tensor(boxes, dtype=torch.float32)\n target[\"labels\"] = torch.as_tensor(bboxes_with_cls_id[..., -1].flatten(), dtype=torch.int64)\n target[\"image_id\"] = torch.tensor([get_image_id(img_path)])\n target[\"area\"] = (target[\"boxes\"][:, 3]) * (target[\"boxes\"][:, 2])\n target[\"iscrowd\"] = torch.zeros((num_objs,), dtype=torch.int64)\n return img, target\n\n\nclass Yolo_BEV_dataset(Dataset):\n \"\"\"BEV pytorch dataset to load KITTI\"\"\"\n\n def __init__(self, config: edict, split: str = \"train\") -> None:\n \"\"\"\n Args:\n config (edict): Easy directory configuration file\n split (str): Split to load. Can be [\"train\", \"test\", \"val\"]. Default = train.\n \"\"\"\n super(Yolo_BEV_dataset, self).__init__()\n self.cfg = config\n self.split = split\n\n # read images paths\n self.img_paths = []\n with open(os.path.join(self.cfg.dataset_dir, f\"{split}_split.txt\"), \"r\") as f:\n for line in f:\n self.img_paths.append(line.strip())\n\n # read labels\n column_types = {\n \"ID\": str,\n \"alpha\": float,\n \"3D_d\": float,\n \"3D_l\": float,\n \"3D_w\": float,\n \"cos\": float,\n \"sin\": float,\n \"type\": str,\n }\n self.labels = pd.read_csv(\n os.path.join(self.cfg.dataset_dir, f\"{split}_split.csv\"), dtype=column_types\n )\n\n # extra params\n self.fov = 82 # KITTI fov [TODO: need to adapt to new datasets]\n self.base_width = 864\n self.base_height = 135\n self.canvas = np.zeros(shape=(self.cfg.height, self.cfg.width, self.cfg.channels), dtype=np.float)\n self.mapping = {}\n with open(self.cfg.names_path, \"r\") as f:\n for i, line in enumerate(f):\n self.mapping[line] = float(i)\n\n def __len__(self) -> int:\n \"\"\"Number of elements in dataset\n\n Returns:\n int: Number of elements in dataset\n \"\"\"\n return len(self.img_paths)\n\n def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Get single item from dataset\n\n Args:\n idx (int): Sample index\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: img tensor and labels. Returns\n labels == [[-1,...,-1,\"None\"]] if no label is present for an img.\n \"\"\"\n ############# read image\n img = cv2.imread(self.img_paths[idx])\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float)\n img /= 255.0\n\n # rescale image to input size and position it to canvas center\n new_w = int(self.base_width * (self.fov / 360.0))\n new_w = new_w if new_w % 2 == 0 else new_w - 1\n new_h = int((img.shape[0] / img.shape[1]) * new_w)\n new_h = new_h if new_h % 2 == 0 else new_h - 1\n img = cv2.resize(img, (new_w, new_h))\n\n # define padding borders\n tb_border = (self.canvas.shape[0] - new_h) // 2 # top/bottom border\n lr_border = (self.canvas.shape[1] - new_w) // 2 # left/right border\n\n # fit image into canvas\n canvas = self.canvas.copy()\n canvas[tb_border : canvas.shape[0] - tb_border, lr_border : canvas.shape[1] - lr_border, :] = img\n img = canvas\n\n ############## read labels\n label_id = self.img_paths[idx].split(\"/\")[-1].split(\".\")[0]\n matches = self.labels[self.labels[\"ID\"] == label_id]\n\n # check if img has labels\n if matches.empty:\n labels = np.array([-1.0 for _ in range(7)])\n else:\n matches = matches.loc[:, matches.columns != \"ID\"]\n matches = matches.replace({\"cls\": self.mapping})\n labels = matches.to_numpy().astype(np.float)\n\n return img, labels\n\n\ndef get_image_id(filename: str) -> int:\n \"\"\"\n Convert a string to a integer.\n Make sure that the images and the `image_id`s are in one-one correspondence.\n There are already `image_id`s in annotations of the COCO dataset,\n in which case this function is unnecessary.\n For creating one's own `get_image_id` function, one can refer to\n https://github.com/google/automl/blob/master/efficientdet/dataset/create_pascal_tfrecord.py#L86\n or refer to the following code (where the filenames are like 'level1_123.jpg')\n >>> lv, no = os.path.splitext(os.path.basename(filename))[0].split(\"_\")\n >>> lv = lv.replace(\"level\", \"\")\n >>> no = f\"{int(no):04d}\"\n >>> return int(lv+no)\n \"\"\"\n raise NotImplementedError(\"Create your own 'get_image_id' function\")\n lv, no = os.path.splitext(os.path.basename(filename))[0].split(\"_\")\n lv = lv.replace(\"level\", \"\")\n no = f\"{int(no):04d}\"\n return int(lv + no)\n\n\nif __name__ == \"__main__\":\n from cfg import Cfg\n import matplotlib.pyplot as plt\n\n random.seed(2020)\n np.random.seed(2020)\n Cfg.dataset_dir = \"/mnt/e/Dataset\"\n dataset = Yolo_dataset(Cfg.train_label, Cfg)\n for i in range(100):\n out_img, out_bboxes = dataset.__getitem__(i)\n a = draw_box(out_img.copy(), out_bboxes.astype(np.int32))\n plt.imshow(a.astype(np.int32))\n plt.show()\n"
] |
[
[
"numpy.random.seed",
"numpy.clip",
"torch.zeros",
"numpy.random.shuffle",
"numpy.concatenate",
"numpy.mean",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.where",
"torch.as_tensor"
]
] |
ganguli-lab/projecting-manifolds
|
[
"05a0ca8c87e2f38e51f2f392a13ee670588c5fc7"
] |
[
"rand_mfld_proj/mfld/gauss_mfld_plot.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 28 13:46:16 2016\n\n@author: Subhy\n\nPlot distance, principal angles between tangent spaces and curvature as a\nfunction of position on a Gaussian random surface in a high dimensional space\n\nFunctions\n=========\nmake_fig_ax\n Make figure and axes objects\nplot_data\n Plot all graphs for one of distance, angle, curvature\ndefault_options\n dicts and tuples of default options for plots\nload_and_plot\n load data and plot figures\nload_and_plot_and_save\n load data, plot figures and save pdfs\n\"\"\"\nfrom typing import Sequence, Mapping, Any, Tuple\nimport numpy as np\nfrom numpy import ndarray as array\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nOptions = Mapping[str, Any]\nOptionSet = Mapping[str, Options]\nLabels = Sequence[str]\nAxes = mpl.axes.Axes\nFigure = mpl.figure.Figure\n\n# =============================================================================\n# plotting\n# =============================================================================\n\n\ndef make_fig_ax(siz: Sequence[float],\n num_ax: int) -> (Figure, Sequence[Axes]):\n \"\"\"\n Make figure and axes objects\n\n Returns\n -------\n fig, ax\n figure object, axes object\n\n Parameters\n ----------\n siz\n (width, height) in inches\n num_ax\n number of axes in figure\n \"\"\"\n fig = plt.figure(figsize=siz)\n gspecs = plt.GridSpec(1, num_ax, width_ratios=[1] * num_ax)\n ax = []\n for gsi in range(num_ax):\n ax.append(fig.add_subplot(gspecs[0, gsi]))\n return fig, ax\n\n\ndef common_colorbar(imh: mpl.collections.QuadMesh,\n axh: Axes,\n labtext: str,\n labopt: Options):\n \"\"\"\n Add colorbar to collection of axes\n\n Parameters\n ----------\n imh\n pcolormesh object for heatmap with color info\n axh\n axes object to place colorbar on\n labtext\n string for colorbar label\n labopt\n options for colorbar label text\n \"\"\"\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n divider = make_axes_locatable(axh)\n cax = divider.append_axes(\"right\", \"10%\", pad=\"20%\")\n cbh = plt.colorbar(imh, cax=cax)\n cbh.set_label(labtext, **labopt)\n\n\ndef common_clim(imh: Sequence[mpl.collections.QuadMesh],\n cmin: float = 0.0): # set all clims equal\n \"\"\"\n Make the clim for each image in list imh the same\n\n Parameters\n ----------\n imh\n list of pcolormesh objects with heatmaps\n cmin\n lower end of clim\n \"\"\"\n cmax = 1.0 * cmin\n for im in imh:\n cl = im.get_clim()\n cmax = np.maximum(cmax, cl[1])\n\n for im in imh:\n im.set_clim((cmin, cmax))\n\n\ndef make_heatmaps(axh: Sequence[Axes],\n x: array, y: array,\n dataa: Sequence[array],\n xylabl: Labels,\n cblabl: Labels,\n titl: Labels,\n opts: OptionSet,\n layer: Tuple[int, ...] = (),\n lpad: int = 27,\n sample: int = 1): # make set of heat maps\n \"\"\"\n Make set of heat maps\n\n Parameters\n ----------\n axh\n list of axes objects\n x,y\n ndarray of sigma^a positions\n dataa\n list of ndarrays of heatmap data\n xylabl\n list of strings: [x-axis label, y-axis label]\n cblabl\n list of strings for colorbar label [name, formula] of quantity\n titl\n list of strings for heatmap titles\n opts\n dictionary of options\n\n opts['im']\n options for pcolormesh for heatmaps\n opts['asp']\n aspect ratio of pcolormesh for heatmaps\n opts['tx']\n text options for x,y-axis label and title\n opts['cb']\n text options for colorbar label\n lpad\n padding for colorbar label\n sample\n plot every sample'th point\n \"\"\"\n if 'prop' in opts['lg'] and 'size' in opts['lg']['prop']:\n labelsize = opts['lg']['prop']['size']\n\n layer += (slice(None, None, sample),) * 2\n\n imh = []\n for ax, dat, tit in zip(axh, dataa, titl):\n ax.tick_params(axis='both', which='major',\n labelsize=labelsize)\n cmp = ()\n if dat.ndim > len(layer):\n cmp = (0,)\n imh.append(ax.pcolormesh(x[::sample], y[::sample], dat[layer + cmp].T,\n **opts['im']))\n imh[-1].set_edgecolor('face')\n ax.set_xlabel(xylabl[0], **opts['tx'])\n ax.set_ylabel(xylabl[1], labelpad=-8, **opts['tx'])\n ax.set_title(tit, **opts['tx'])\n ax.set_aspect(opts['asp'])\n\n opts['cb']['labelpad'] = lpad\n common_clim(imh)\n# common_colorbar(imh[0], axh[0], cblabl[0] + ', ' + cblabl[1], opts['cb'])\n common_colorbar(imh[0], axh[0], cblabl[1], opts['cb'])\n\n\ndef make_scatter(ax: Axes,\n x: array,\n y: array,\n ldata: Sequence[array],\n titles: Labels,\n opts: OptionSet,\n sample: int = 4): # Make scatter plot\n \"\"\"\n Make scatter plot of comparison of theory & expt\n\n Parameters\n ----------\n ax\n axes objectt\n x\n ndarray of rho values\n y\n list of ndarrays of simulation values\n ldata\n tuple of ndarrays, (x,y) of values for theory line on scatter plot\n titles\n list of strings [name, formula(e)] of quantity(ies)\n opts\n dictionary of options\n\n opts['tx']\n text options for x,y-axis label and title\n opts['lg']\n options for legend\n \"\"\"\n if 'prop' in opts['lg'] and 'size' in opts['lg']['prop']:\n ax.tick_params(axis='both', which='major',\n labelsize=opts['lg']['prop']['size'])\n\n leg = ['Theory', 'Simulation', 'Sim mid']\n# if len(y) == 2:\n# # projection\n# ln = ax.plot(x.ravel()[::sample], y[0].ravel()[::sample], 'g.',\n# x.ravel()[::sample], y[1].ravel()[::sample], 'b.')\n# lt = ax.plot(ldata[0], ldata[1], 'r', linewidth=2.0)\n# ax.legend(lt + ln, leg, **opts['lg'], loc='lower left')\n# ax.set_ylabel(titles[1], **opts['tx'])\n# else:\n if ldata[1].ndim == 2:\n # angle\n xx = np.stack((x,) * (y[0].shape[-1]-1), axis=-1)\n ln = ax.plot(x.ravel()[::sample], y[..., 0].ravel()[::sample],\n 'g.',\n xx.ravel()[::sample], y[..., 1:].ravel()[::sample],\n 'b.')\n lt = ax.plot(ldata[0], ldata[1][:, 0], 'r-',\n ldata[0], ldata[1][:, 1], 'r--', linewidth=2.0)\n leg2 = [lg[:1] + ': ' + ti for lg in leg for ti in titles[1:]]\n ax.legend(lt + ln, leg2, **opts['lg'], loc='lower right')\n ax.set_ylabel(titles[0], **opts['tx'])\n else:\n # distance\n ln = ax.plot(x.ravel()[::sample], y.ravel()[::sample], 'g.')\n lt = ax.plot(ldata[0], ldata[1], 'r-', linewidth=2.0)\n ax.legend(lt + ln, leg, **opts['lg'], loc='lower right')\n ax.set_ylabel(titles[1], **opts['tx'])\n\n# ax.set_title(titles[0] + ', '+ titles[1], **opts['tx'])\n# ax.set_title(titles[1], **opts['tx'])\n ax.set_xlabel(r'$\\rho$', labelpad=-3, **opts['tx'])\n ax.set_xscale('log')\n ax.set_xlim((0.1, x.max()))\n ax.set_ylim((0., 1.1 * max(ldata[1].max(), y.max())))\n ax.grid(b=True)\n\n\ndef make_hist(ax: Axes,\n thry: float,\n numl: array,\n num_bins: int,\n xlabl: Labels,\n titl: str,\n opts: OptionSet): # Make histogram\n \"\"\"\n Make histogram\n\n Parameters\n ----------\n ax\n axes object\n thry\n theoretical value\n numl\n list of ndarrays with simulation values\n num_bins\n number of bins\n xlabl\n list of strings [name, formula] of quantity\n titl\n string for title\n opts\n dictionary of options\n\n opts['tx']\n text options for x,y-axis label and title\n opts['lg']\n options for legend\n \"\"\"\n if 'prop' in opts['lg'] and 'size' in opts['lg']['prop']:\n ax.tick_params(axis='both', which='major',\n labelsize=opts['lg']['prop']['size'])\n\n ax.hist(numl.ravel(), bins=num_bins, normed=True)\n ax.set_xlim(left=0.0, right=numl.max())\n max_n = ax.get_ylim()[1]\n ln = ax.plot(np.array([thry, thry]), np.array([0, max_n]), 'r-')\n\n# ax.set_xlabel(xlabl[0] + ', ' + xlabl[1], **opts['tx'])\n ax.set_xlabel(xlabl[1], labelpad=-1, **opts['tx'])\n ax.set_ylabel('Relative frequency', **opts['tx'])\n ax.set_title(titl, **opts['tx'])\n ln[0].set_linewidth(2.0)\n ax.legend(ln, ['Theory'], **opts['lg'], loc='upper left')\n ln[0].set_data(np.array([[thry, thry], [0.0, ax.get_ylim()[1]]]))\n\n\ndef plot_data(ax: Axes,\n x: array,\n y: array,\n rho: array,\n cdata: Sequence[array],\n ldata: Sequence[array],\n titles: Labels,\n xylabl: Labels,\n cblab: Labels,\n opts: OptionSet,\n layer: Tuple[int, ...] = (),\n lpad: int = 27,\n num_bins: int = 10,\n sample: Sequence[int] = (1, 1)): # plot data set\n \"\"\"\n Plot data for one type of quantity\n\n Parameters\n ----------\n ax\n list of axes objects\n x,y\n ndarray of sigma^a positions\n rho\n ndarray of rho as a function of position\n ldata\n tuple of ndarrays, (x,y) of values for theory line on scatter plot\n cdata\n list of ndarrays of heatmap data\n titles\n list of strings for heatmap titles\n xylabl\n list of strings: [x-axis label, y-axis label]\n cblab\n list of strings for colorbar label [name, formula] of quantity\n opts\n dictionary of options\n\n opts['im']\n options for pcolormesh for heatmaps\n opts['asp']\n aspect ratio of pcolormesh for heatmaps\n opts['tx']\n text options for x,y-axis label and title\n opts['cb']\n text options for colorbar label\n opts['lg']\n options for legends\n lpad\n padding for colorbar label\n sample\n plot every sample'th point, tuple of ints, (2,)\n \"\"\"\n make_heatmaps(ax[:len(titles)], x, y, cdata[:len(titles)],\n xylabl, cblab, titles, opts, layer, lpad, sample[0])\n if ldata is not None:\n make_scatter(ax[-1], rho, cdata[1], ldata, cblab, opts,\n 10 * sample[1])\n else:\n make_hist(ax[-1], cdata[0].ravel()[0], cdata[1],\n num_bins, cblab, '', opts)\n\n\n# =============================================================================\n# options\n# =============================================================================\n\n\ndef default_options() -> (OptionSet,\n Mapping[str, Labels],\n Sequence[int],\n Sequence[int]):\n \"\"\"\n Default options for plotting data\n\n Returns\n -------\n opts = dict of dicts of options for plots\n\n opts['im']\n options for pcolormesh for heatmaps\n opts['asp']\n aspect ratio of pcolormesh for heatmaps\n opts['tx']\n text options for x,y-axis label and title\n opts['cb']\n text options for colorbar label\n opts['lg']\n options for legends\n labels\n dict of strings for titles, axis labels and legends\n\n labels['xy']\n list of strings: [x-axis label, y-axis label]\n labels['xyc']\n list of strings: [x-axis label, y-axis label]\n others:\n list of strings [name, formula(e)] of quantity(ies)\n labels['d']\n list of strings for distance\n labels['a']\n list of strings for angles\n labels['p']\n list of strings for projections\n labels['c']\n list of strings for curvature\n lpads\n tuple of padding lengths of colorbars for [distance, sine, curvature]\n samp\n plot every samp'th point, tuple of ints, (2,)\n \"\"\"\n mpl.rcParams['pdf.fonttype'] = 42\n mpl.rcParams['text.usetex'] = True\n# mpl.rcParams['text.latex.unicode'] = True\n mpl.rcParams['font.family'] = r'serif'\n\n# myim = {'origin':'lower', 'cmap':plt.get_cmap('viridis'),\n# 'extent':(x[0], -x[0], y[0], -y[0])}\n imopts = {'cmap': plt.get_cmap('viridis')}\n imaspect = 1. # 0.8 * intrinsic_range[1] / intrinsic_range[0]\n txtopts = {'size': 'xx-large', 'family': 'serif'}\n lgprops = {'prop': {'size': 'x-large', 'family': 'serif'}, 'numpoints': 1,\n 'handlelength': 1, 'frameon': False, 'framealpha': 0.}\n cbtext = {'rotation': 270, 'labelpad': 27, **txtopts}\n lpads = (27, 20, 20, 20)\n sample = (4, 4)\n\n xylab = [r'$\\Delta\\sigma^1/\\lambda^1$', r'$\\Delta\\sigma^2/\\lambda^1$']\n xyclab = [r'$\\sigma^1/\\lambda^1$', r'$\\sigma^2/\\lambda^1$']\n# xylab = [r'Position difference, $\\delta\\sigma^1/\\lambda_1$',\n# r'Position difference, $\\delta\\sigma^2/\\lambda_1$']\n# xyclab = [r'Position, $\\sigma^1/\\lambda_1$',\n# r'Position, $\\sigma^2/\\lambda_1$']\n dlab = ['Euclidean distance',\n r'$\\Vert\\phi(\\sigma)-\\phi(\\sigma^\\prime)\\Vert/\\ell$']\n alab = [r'$\\sin\\theta_{a}$',\n r'$\\sin\\theta_{\\mathrm{max}}$',\n r'$\\sin\\theta_{\\mathrm{min}}$']\n plab = [r'$\\cos\\theta_{\\mathcal{S}}$',\n r'$\\cos\\theta_{\\mathcal{S}}$']\n clab = ['Curvature', r'$\\kappa\\ell$']\n\n opts = {'tx': txtopts, 'cb': cbtext, 'lg': lgprops, 'im': imopts,\n 'asp': imaspect}\n labels = {'xy': xylab, 'xyc': xyclab, 'd': dlab, 'a': alab, 'p': plab,\n 'c': clab}\n\n return opts, labels, lpads, sample\n\n\n# =============================================================================\n# running code\n# =============================================================================\n\n\ndef load_and_plot(filename: str,\n opts: Mapping[str, Labels],\n labels: Mapping[str, Labels],\n lpads: Sequence[int],\n samp: Sequence[int] = (1, 1)) -> (Figure, Figure,\n Figure, Figure):\n \"\"\"\n Load data from ``.npz`` file and plot\n\n Parameters\n ----------\n filenamee\n name of ``.npz`` file, w/o extension, for data\n opts = dict of dicts of options for plots\n\n opts['im']\n options for pcolormesh for heatmaps\n opts['asp']\n aspect ratio of pcolormesh for heatmaps\n opts['tx']\n text options for x,y-axis label and title\n opts['cb']\n text options for colorbar label\n opts['lg']\n options for legends\n labels\n dict of strings for titles, axis labels and legends\n\n labels['xy']\n list of strings: [x-axis label, y-axis label]\n labels['xyc']\n list of strings: [x-axis label, y-axis label]\n others:\n list of strings [name, formula(e)] of quantity(ies)\n labels['d']\n list of strings for distance\n labels['a']\n list of strings for angles\n labels['p']\n list of strings for projections\n labels['c']\n list of strings for curvature\n lpads\n tuple of padding lengths of colorbars for [distance, sine, curvature]\n samp\n plot every samp'th point, tuple of ints, (2,)\n\n Returns\n -------\n figs\n tuple of figure objects for (distance, angle, projection, curvature)\n \"\"\"\n\n d = np.load(filename + '.npz')\n xx = d['x']\n xc = [np.append(x, -x[0]) for x in xx]\n\n if len(xc) < 2:\n return\n\n fig_d, ax_d = make_fig_ax((12.9, 3), 3)\n fig_a, ax_a = make_fig_ax((12.9, 3), 3)\n fig_p, ax_p = make_fig_ax((12.9, 3), 3)\n# fig_p, ax_p = make_fig_ax((17.2, 3), 4)\n fig_c, ax_c = make_fig_ax((12.9, 3), 3)\n\n layer = tuple(len(x) // 2 for x in xx[:-2])\n cdata = [[d['thr_dis'], d['num_dis']]]\n ldata = [[d['rhol'], d['thr_disl']]]\n cdata.append([d['thr_sin'], d['num_sin']])\n ldata.append([d['rhol'], d['thr_sinl']])\n cdata.append([d['thr_pro'], d['num_pro']])\n ldata.append([d['rhol'], d['thr_prol']])\n cdata.append([d['thr_cur'], d['num_cur']])\n ldata.append(None)\n\n axs = [ax_d, ax_a, ax_p, ax_c]\n labs = [['Theory', 'Simulation', 'Sim mid']] * 3\n labs.append(['Theory', 'Simulation 1', 'Simulation 2'])\n xykeys = ['xy'] * 3 + ['xyc']\n keys = ['d', 'a', 'p', 'c']\n\n for ax, cdat, ldat, lab, lpad, xyk, k in zip(axs, cdata, ldata, labs,\n lpads, xykeys, keys):\n plot_data(ax, xc[-2], xc[-1], d['rho'], cdat, ldat, lab,\n labels[xyk], labels[k], opts, layer, lpad, sample=samp)\n\n d.close()\n\n return fig_d, fig_a, fig_p, fig_c\n\n\ndef load_plot_and_save(filename: str,\n opts: Mapping[str, Labels],\n labels: Mapping[str, Labels],\n lpads: Sequence[int],\n fignames: Labels,\n figpath: str,\n samp: Sequence[int] = (1, 1)): # load data and plot\n \"\"\"\n Load data from ``.npz`` file, plot and save as ``.pdf`` files\n\n Parameters\n ----------\n filenamee\n name of ``.npz`` file, w/o extension, for data\n opts = dict of dicts of options for plots\n\n opts['im']\n options for pcolormesh for heatmaps\n opts['asp']\n aspect ratio of pcolormesh for heatmaps\n opts['tx']\n text options for x,y-axis label and title\n opts['cb']\n text options for colorbar label\n opts['lg']\n options for legends\n labels\n dict of strings for titles, axis labels and legends\n\n labels['xy']\n list of strings: [x-axis label, y-axis label]\n labels['xyc']\n list of strings: [x-axis label, y-axis label]\n others:\n list of strings [name, formula(e)] of quantity(ies)\n labels['d']\n list of strings for distance\n labels['a']\n list of strings for angles\n labels['p']\n list of strings for projections\n labels['c']\n list of strings for curvature\n lpads\n tuple of padding lengths of colorbars for [distance, sine, curvature]\n fignames\n list of ``.pdf`` file names, w/o extensions or paths\n figpath\n path to folder for ``.pdf`` files, ending with '/'\n samp\n plot every samp'th point, tuple of ints, (2,)\n \"\"\"\n\n figs = load_and_plot(filename, opts, labels, lpads, samp)\n\n for fig, figname in zip(figs, fignames):\n fig.savefig(figpath + figname + '.pdf', bbox_inches='tight')\n\n# =============================================================================\n# test code\n# =============================================================================\n\n\nif __name__ == \"__main__\":\n print('Run from outside package.')\n"
] |
[
[
"numpy.maximum",
"numpy.load",
"matplotlib.pyplot.get_cmap",
"numpy.stack",
"matplotlib.pyplot.colorbar",
"numpy.append",
"matplotlib.pyplot.GridSpec",
"numpy.array",
"matplotlib.pyplot.figure"
]
] |
ananth-repos/machine-learning
|
[
"a510dcf81fab9137c33f568e73d65262667b3973"
] |
[
"1.Linear Regression/1.Code - Using Theory/1.2D - Regression.py"
] |
[
"# This code shows how a linear regression analysis can be applied to a 2-dimensional data\n# Implementation here is based on the theory described in the jupyter notebook.\n\n# Code Flow:\n # 1. Import all relevant libraries.\n # 2. Generate sample data & save it as a csv file (Stored as a csv file just to use pandas).\n # 3. Load the dataset using pandas (X - inputs/feature, Y - output/target).\n # 4. Plot the generated data understand the trend.\n # 5. Calculate weights (parameters - a & b) using the equation from the theory lecture.\n # 6. Calculate Yhat from the weights above. Yhat = a*X + b.\n # 7. Calculate R-squared using the equation from the theory lecture to validate the model.\n \n# 1.Imports:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\n\n# 2.Generate sample data:\nN = 100\nw = np.array([2, 3])\nwith open('data_2d.csv', 'w') as f:\n X = np.random.uniform(low=0, high=100, size=(N,2))\n Y = np.dot(X, w) + 1 + np.random.normal(scale=5, size=N)\n for i in range(N):\n f.write(\"%s,%s,%s\\n\" % (X[i,0], X[i,1], Y[i]))\n \n# 3.Load the data:\ndf = pd.read_csv('data_2d.csv',header = None)\ndf['ones'] = np.ones(len(X))\nX = df[[0,1,'ones']].as_matrix()\nY = df[2].values\n\n# 4.Plot the data:\nfig = plt.figure(1)\nax = fig.add_subplot(111, projection='3d')\nax.scatter(X[:,0], X[:,1], Y)\nplt.xlabel('X1')\nplt.ylabel('X2')\nplt.show()\n\n# 5.Model: Y = a*X + B\n# Apply the equations from the jupyter notebook to calculate a & b:\n# Denominator is same for both a & b\nw = np.linalg.solve(np.dot(X.T,X),np.dot(X.T,Y))\n\n# 6.Predict Y:\nYhat = np.dot(X,w)\n\n# 7.R-squared:\nd1 = Y - Yhat\nd2 = Y - Y.mean()\nr2 = 1 - d1.dot(d1)/d2.dot(d2)\n\nprint('the r-squared is {}'.format(r2))\n"
] |
[
[
"numpy.dot",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.random.uniform",
"numpy.random.normal",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
JonasRSV/Friday
|
[
"f959eff95ba7b11525f97099c8f5ea0e325face7"
] |
[
"mm/models/shared/augmentations/background.py"
] |
[
"\"\"\"Download sounds from https://www.soundsnap.com/.\"\"\"\nimport numpy as np\nimport pathlib\nimport sox\n\n\nfrom models.shared.augmentations.core import Augmentation\n\n\nclass Background(Augmentation):\n\n def __init__(self,\n background_noises: pathlib.Path,\n sample_rate: int,\n min_voice_factor: float,\n max_voice_factor: float):\n\n if not background_noises.is_dir():\n raise Exception(f\"{background_noises} is not a valid directory\")\n\n self.normalization = 2 ** 15\n self.sample_rate = sample_rate\n self.min_voice_factor = min_voice_factor\n self.max_voice_factor = max_voice_factor\n\n self.noises, self.density = [], []\n\n transformer = sox.Transformer()\n transformer.set_output_format(rate=sample_rate, channels=1)\n for file in background_noises.glob(\"*.mp3\"):\n print(f\"Loading background noise {file}\")\n resampled_audio = transformer.build_array(\n input_filepath=str(file), sample_rate_in=sample_rate)\n\n self.noises.append(resampled_audio)\n self.density.append(len(resampled_audio))\n\n self.density = np.array(self.density)\n self.density = self.density / self.density.sum()\n\n self.clips = np.arange(len(self.noises))\n\n def apply(self, audio: np.ndarray, sample_rate: int):\n audio = np.array(audio)\n if self.sample_rate != sample_rate:\n raise Exception(f\"Background noise mismatching sample rate {sample_rate} != {self.sample_rate}\")\n\n voice_factor = np.random.uniform(self.min_voice_factor, self.max_voice_factor)\n clip = self.noises[np.random.choice(self.clips, p=self.density)]\n\n if len(clip) > len(audio):\n start_clip = int(np.random.uniform(0, len(clip) - len(audio)))\n audio = audio * voice_factor + clip[start_clip: start_clip + len(audio)] * (1 - voice_factor)\n else:\n start_audio = int(np.random.uniform(0, len(audio) - len(clip)))\n audio[start_audio: start_audio + len(clip)] = \\\n audio[start_audio: start_audio + len(clip)] * voice_factor + clip * (1 - voice_factor)\n\n return audio\n\n\n"
] |
[
[
"numpy.random.uniform",
"numpy.array",
"numpy.random.choice"
]
] |
mjlbach/robovat
|
[
"4b46459531c50f3801e6557174e49bfec532d870"
] |
[
"robovat/envs/robot_env.py"
] |
[
"\"\"\"The parent class for robot environments.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\nimport random\nimport os.path\n\nimport gym\nimport gym.spaces\nimport numpy as np\n\nfrom robovat.simulation.simulator import Simulator\nfrom robovat.utils.string_utils import camelcase_to_snakecase\nfrom robovat.utils.yaml_config import YamlConfig\nfrom robovat.utils.logging import logger\n\n\ndef get_config_value(config):\n \"\"\"Get the value of an configuration item.\n\n If the config is None, return None. If the config is a value, return the\n value. Otherwise, the config must by a tuple or list represents low and\n high values to sample the property from.\n \"\"\"\n if config is None:\n return None\n elif isinstance(config, (int, float)):\n return config\n elif isinstance(config, (list, tuple)):\n return np.random.uniform(low=config[0], high=config[1])\n else:\n raise ValueError('config %r of type %r is not supported.'\n % (config, type(config)))\n\n\nclass RobotEnv(gym.Env):\n \"\"\"The parent class for robot environments.\"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n def __init__(self,\n observations,\n reward_fns,\n simulator=True,\n config=None,\n debug=False):\n \"\"\"Initialize.\n\n Args:\n observations: List of observations.\n reward_fns: List of reward functions.\n simulator: Instance of the simulator.\n config: Environment configuration.\n debug: True if it is debugging mode, False otherwise.\n \"\"\"\n if simulator is True:\n worker_id = random.randint(0, 2**32-1)\n simulator = Simulator(worker_id=worker_id)\n\n self.simulator = simulator\n\n self.config = config or self.default_config\n self.debug = debug\n\n self._num_episodes = 0\n self._num_steps = 0\n self._episode_reward = 0.0\n self._total_reward = 0.0\n self._is_done = True\n\n self.observations = observations\n self.reward_fns = reward_fns\n\n for obs in self.observations:\n obs.initialize(self)\n for reward_fn in self.reward_fns:\n reward_fn.initialize(self)\n\n self.observation_space = gym.spaces.Dict([\n (obs.name, obs.get_gym_space()) for obs in self.observations\n ])\n\n self.obs_data = None\n self.prev_obs_data = None\n self._obs_step = None\n\n @property\n def default_config(self):\n \"\"\"Load the default configuration file.\"\"\"\n env_name = camelcase_to_snakecase(type(self).__name__)\n config_path = os.path.join('configs', 'envs', '%s.yaml' % (env_name))\n assert os.path.exists(config_path), (\n 'Default configuration file %s does not exist' % (config_path)\n )\n return YamlConfig(config_path).as_easydict()\n\n @property\n def info(self):\n \"\"\"Information of the environment.\"\"\"\n return {'name': type(self).__name__}\n\n @property\n def num_episodes(self):\n \"\"\"Number of episodes.\"\"\"\n return self._num_episodes\n\n @property\n def num_steps(self):\n \"\"\"Number of steps of the current episode.\"\"\"\n return self._num_steps\n\n @property\n def episode_reward(self):\n \"\"\"Received reward of the current episode.\"\"\"\n return self._episode_reward\n\n @property\n def total_reward(self):\n \"\"\"Total reward received so far.\"\"\"\n return self._total_reward\n\n @property\n def is_done(self):\n \"\"\"If the episode is done.\"\"\"\n return self._is_done\n\n @property\n def action_space(self):\n \"\"\"The action space.\"\"\"\n raise NotImplementedError\n\n def reset(self):\n \"\"\"Reset.\"\"\"\n if not self._is_done and self._num_steps > 0:\n for obs in self.observations:\n obs.on_episode_end()\n for reward_fn in self.reward_fns:\n reward_fn.on_episode_end()\n\n self._num_episodes += 1\n self._num_steps = 0\n self._episode_reward = 0.0\n self._is_done = False\n\n if self.config.MAX_STEPS is not None:\n if self.config.MAX_STEPS == 0:\n self._is_done = True\n\n if self.simulator:\n self.simulator.reset()\n self.simulator.start()\n\n self.reset_scene()\n self.reset_robot()\n\n for obs in self.observations:\n obs.on_episode_start()\n for reward_fn in self.reward_fns:\n reward_fn.on_episode_start()\n\n logger.info('episode: %d', self.num_episodes)\n\n self.obs_data = None\n self.prev_obs_data = None\n self._obs_step = None\n return self.get_observation()\n\n def step(self, action):\n \"\"\"Take a step.\n\n See parent class.\n \"\"\"\n if self._is_done:\n raise ValueError('The environment is done. Forget to reset?')\n\n self.execute_action(action)\n self._num_steps += 1\n\n observation = self.get_observation()\n\n reward = 0.0\n\n for reward_fn in self.reward_fns:\n reward_value, termination = reward_fn.get_reward()\n reward += reward_value\n\n if termination:\n self._is_done = True\n\n reward = float(reward)\n self._episode_reward += reward\n\n if self.config.MAX_STEPS is not None:\n if self.num_steps >= self.config.MAX_STEPS:\n self._is_done = True\n\n logger.info('step: %d, reward: %.3f', self.num_steps, reward)\n\n if self._is_done:\n self._total_reward += self.episode_reward\n with open('random_rew_clip.txt', 'a') as f:\n f.write(str(self.episode_reward) + '\\n')\n logger.info(\n 'episode_reward: %.3f, avg_episode_reward: %.3f',\n self.episode_reward,\n float(self.total_reward) / (self._num_episodes + 1e-14),\n )\n\n return observation, reward, self._is_done, None\n\n def get_observation(self):\n \"\"\"Return the observation.\"\"\"\n if self._obs_step != self._num_steps:\n self._obs_step = self._num_steps\n self.prev_obs_data = self.obs_data\n\n self.obs_data = collections.OrderedDict()\n for obs in self.observations:\n self.obs_data[obs.name] = obs.get_observation()\n\n return self.obs_data\n\n @abc.abstractmethod\n def reset_scene(self):\n \"\"\"Reset the scene in simulation or the real world.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def reset_robot(self):\n \"\"\"Reset the robot in simulation or the real world.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def execute_action(self, action):\n \"\"\"Execute the robot action.\n \"\"\"\n pass\n"
] |
[
[
"numpy.random.uniform"
]
] |
usmanzaheer1995/udacity-ai-programming-nanodegree
|
[
"50c3dcd59e5a215089c51960d269b8878690ec5c"
] |
[
"train.py"
] |
[
"import time\nimport json\nfrom pathlib import Path\n\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import transforms, datasets, models\nfrom PIL import Image\n\nfrom workspace_utils import active_session\nfrom helper import classifier, save_checkpoint, load_checkpoint\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Imager classifier trainer\")\n parser.add_argument(\"data_dir\")\n parser.add_argument(\"--save_dir\", default=\"./checkpoints/\")\n parser.add_argument(\"--arch\", default=\"vgg16\", choices=[\"vgg16\", \"densenet121\", \"resnet50\"])\n parser.add_argument(\"--dropout\", default=\"0.5\")\n parser.add_argument(\"--learning_rate\", default=\"0.001\")\n parser.add_argument(\"--hidden_units\", default=\"512\")\n parser.add_argument(\"--epochs\", default=\"5\")\n parser.add_argument(\"--gpu\", default=\"gpu\")\n \n return parser.parse_args()\n\ndef transformers(args):\n data_dir = args.data_dir\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n \n training_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomRotation(30),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n validation_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n test_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n image_datasets = {\n \"train\": datasets.ImageFolder(train_dir, transform=training_transforms),\n \"test\": datasets.ImageFolder(test_dir, transform=test_transforms),\n \"validate\": datasets.ImageFolder(valid_dir, transform=validation_transforms)\n }\n\n dataloaders = {\n \"train\": torch.utils.data.DataLoader(image_datasets[\"train\"], batch_size=64, shuffle=True),\n \"test\": torch.utils.data.DataLoader(image_datasets[\"test\"], batch_size=64, shuffle=True),\n \"validate\": torch.utils.data.DataLoader(image_datasets[\"validate\"], batch_size=64, shuffle=True)\n }\n \n return image_datasets, dataloaders\n\ndef train(model, criterion, optimizer, trainloader, validationloader, epochs, device):\n if (device == \"gpu\"):\n device = \"cuda\"\n print(f\"Training {model} model...\")\n steps = 0\n running_loss = 0\n print_every = 10\n for epoch in range(epochs):\n for inputs, labels in trainloader:\n steps += 1\n # Move input and label tensors to the default device\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n logps = model.forward(inputs)\n loss = criterion(logps, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % print_every == 0:\n test_loss = 0\n accuracy = 0\n model.eval()\n with torch.no_grad():\n for inputs, labels in validationloader:\n inputs, labels = inputs.to(device), labels.to(device)\n logps = model.forward(inputs)\n batch_loss = criterion(logps, labels)\n\n test_loss += batch_loss.item()\n\n # Calculate accuracy\n ps = torch.exp(logps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n\n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Train loss: {running_loss/print_every:.3f}.. \"\n f\"Validation loss: {test_loss/len(validationloader):.3f}.. \"\n f\"Validation accuracy: {accuracy/len(validationloader):.3f}\")\n running_loss = 0\n model.train()\n print(\"Training complete!\")\n \ndef test_network(model, test_loader, criterion, device):\n print(\"Testing model accuracy...\")\n device = \"cuda\" if device == \"gpu\" else \"cpu\"\n test_loss = 0\n accuracy = 0\n with torch.no_grad():\n for inputs, labels in test_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n\n log_ps = model.forward(inputs)\n batch_loss = criterion(log_ps, labels)\n test_loss += batch_loss.item()\n\n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n\n print(f\"Test accuracy: {accuracy/len(test_loader):.3f}..\")\n\ndef main():\n args = parse_args()\n\n # if save_dir does not exist, create the directory\n Path(args.save_dir).mkdir(parents=True, exist_ok=True)\n \n image_datasets, dataloaders = transformers(args)\n \n model, criterion, optimizer = classifier(args.arch,\n float(args.dropout),\n int(args.hidden_units),\n float(args.learning_rate),\n args.gpu)\n \n model.class_to_idx = image_datasets['train'].class_to_idx\n train(model, criterion, optimizer, dataloaders[\"train\"], dataloaders[\"validate\"], int(args.epochs), args.gpu)\n test_network(model, dataloaders[\"test\"], criterion, args.gpu)\n save_checkpoint(args.save_dir, model, optimizer, args.arch, int(args.epochs), float(args.learning_rate))\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.exp",
"torch.no_grad",
"torch.utils.data.DataLoader"
]
] |
nicdnb/tensorflow
|
[
"ad5c0c4d091c93ef65e91c55cb4df065d0c7a989"
] |
[
"tensorflow/contrib/data/python/kernel_tests/optimize_dataset_op_test.py"
] |
[
"# Copyright 2018 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\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.contrib.data.python.ops import optimization\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import test\n\n\nclass OptimizeDatasetTest(test.TestCase, parameterized.TestCase):\n\n def testAssertSuffix(self):\n dataset = dataset_ops.Dataset.from_tensors(0).apply(\n optimization.assert_next([\"Map\"])).map(lambda x: x)\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n self.assertEqual(0, sess.run(get_next))\n\n def testAssertSuffixInvalid(self):\n dataset = dataset_ops.Dataset.from_tensors(0).apply(\n optimization.assert_next([\"Whoops\"])).map(lambda x: x)\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n with self.assertRaisesRegexp(\n errors.InvalidArgumentError,\n \"Asserted Whoops transformation at offset 0 but encountered \"\n \"Map transformation instead.\"):\n sess.run(get_next)\n\n def testAssertSuffixShort(self):\n dataset = dataset_ops.Dataset.from_tensors(0).apply(\n optimization.assert_next([\"Map\", \"Whoops\"])).map(lambda x: x)\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n with self.assertRaisesRegexp(\n errors.InvalidArgumentError,\n \"Asserted next 2 transformations but encountered only 1.\"):\n sess.run(get_next)\n\n def testOptimizationDefault(self):\n dataset = dataset_ops.Dataset.range(10).apply(\n optimization.assert_next(\n [\"Map\", \"Batch\"])).map(lambda x: x * x).batch(10).apply(\n optimization.optimize())\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n self.assertAllEqual([x * x for x in range(10)], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testOptimizationEmpty(self):\n dataset = dataset_ops.Dataset.range(10).apply(\n optimization.assert_next(\n [\"Map\", \"Batch\"])).map(lambda x: x * x).batch(10).apply(\n optimization.optimize([]))\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n self.assertAllEqual([x * x for x in range(10)], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testOptimizationFusion(self):\n dataset = dataset_ops.Dataset.range(10).apply(\n optimization.assert_next(\n [\"MapAndBatch\"])).map(lambda x: x * x).batch(10).apply(\n optimization.optimize([\"map_and_batch_fusion\"]))\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n self.assertAllEqual([x * x for x in range(10)], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testOptimizationStatefulFunction(self):\n dataset = dataset_ops.Dataset.range(10).map(\n lambda _: random_ops.random_uniform([])).batch(10).apply(\n optimization.optimize([\"map_and_batch_fusion\"]))\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(get_next)\n\n def testOptimizationLargeInputFromTensor(self):\n input_t = array_ops.placeholder(dtypes.int32, (None, None, None))\n dataset = dataset_ops.Dataset.from_tensors(input_t).apply(\n optimization.optimize())\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op, {input_t: np.ones([512, 1024, 1025], np.int32)})\n sess.run(get_next)\n\n def testOptimizationLargeInputFromTensorSlices(self):\n input_t = array_ops.placeholder(dtypes.int32, (None, None, None, None))\n dataset = dataset_ops.Dataset.from_tensor_slices(input_t).apply(\n optimization.optimize())\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op, {input_t: np.ones([1, 512, 1024, 1025], np.int32)})\n sess.run(get_next)\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] |
[
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.ones",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.platform.test.main",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"tensorflow.contrib.data.python.ops.optimization.assert_next",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.contrib.data.python.ops.optimization.optimize"
]
] |
romepeng/efinance
|
[
"6255dfaa7624a5ef28e55b5378c5263a63aa18e3"
] |
[
"efinance/bond/getter.py"
] |
[
"from ..utils import process_dataframe_and_series\nimport multitasking\nimport pandas as pd\nimport requests\nfrom typing import (List,\n Union,\n Dict)\n\nfrom ..common import get_history_bill as get_history_bill_for_bond\nfrom ..common import get_today_bill as get_today_bill_for_bond\nfrom ..common import get_quote_history as get_quote_history_for_bond\nfrom ..common import get_realtime_quotes_by_fs\n\nfrom ..utils import to_numeric\nfrom ..common.config import (EASTMONEY_REQUEST_HEADERS,\n FS_DICT)\n\nfrom .config import EASTMONEY_BOND_BASE_INFO_FIELDS\n\n\n@to_numeric\ndef get_base_info_single(bond_code: str) -> pd.Series:\n \"\"\"\n 获取单只债券基本信息\n\n Parameters\n ----------\n bond_code : str\n 债券代码\n\n Returns\n -------\n Series\n 债券的一些基本信息\n \"\"\"\n columns = EASTMONEY_BOND_BASE_INFO_FIELDS\n params = (\n ('reportName', 'RPT_BOND_CB_LIST'),\n ('columns', 'ALL'),\n ('source', 'WEB'),\n ('client', 'WEB'),\n ('filter', f'(SECURITY_CODE=\"{bond_code}\")'),\n )\n\n url = 'http://datacenter-web.eastmoney.com/api/data/v1/get'\n json_response = requests.get(url,\n headers=EASTMONEY_REQUEST_HEADERS,\n params=params).json()\n if json_response['result'] is None:\n return pd.Series(index=columns.values())\n items = json_response['result']['data']\n s = pd.Series(items[0]).rename(index=columns)\n s = s[columns.values()]\n return s\n\n\ndef get_base_info_multi(bond_codes: List[str]) -> pd.DataFrame:\n \"\"\"\n 获取多只债券基本信息\n\n Parameters\n ----------\n bond_codes : List[str]\n 债券代码构成的字符串列表\n\n Returns\n -------\n DataFrame\n 多只债券信息\n \"\"\"\n ss = []\n\n @multitasking.task\n def start(bond_code: str) -> None:\n s = get_base_info_single(bond_code)\n ss.append(s)\n for bond_code in bond_codes:\n start(bond_code)\n multitasking.wait_for_tasks()\n df = pd.DataFrame(ss)\n return df\n\n\ndef get_base_info(bond_codes: Union[str, List[str]]) -> Union[pd.DataFrame, pd.Series]:\n \"\"\"\n 获取单只或多只可转债基本信息\n\n Parameters\n ----------\n bond_codes : Union[str, List[str]]\n 可转债代码、名称 或者 可转债代码、名称构成的列表\n\n Returns\n -------\n Union[DataFrame, Series]\n 单只或多只可转债基本信息\n\n - ``DataFrame`` : 当 ``bond_codes`` 是字符串列表时\n - ``Series`` : 当 ``bond_codes`` 是字符串时\n\n Examples\n --------\n >>> import efinance as ef\n >>> # 单只债券\n >>> ef.bond.get_base_info('123111')\n 债券代码 123111\n 债券名称 东财转3\n 正股代码 300059\n 正股名称 东方财富\n 债券评级 AA+\n 申购日期 2021-04-07 00:00:00\n 发行规模(亿) 158\n 网上发行中签率(%) 0.05877\n 上市日期 2021-04-23 00:00:00\n 到期日期 2027-04-07 00:00:00\n 期限(年) 6\n 利率说明 第一年0.2%、第二年0.3%、第三年0.4%、第四年0.8%、第五年1.8%、第六年2.0%。\n dtype: object\n\n >>> 多只债券\n >>> bond_codes = ['123111','113050']\n >>> ef.bond.get_base_info(bond_codes)\n 债券代码 债券名称 正股代码 正股名称 ... 上市日期 到期日期 期限(年) 利率说明\n 0 113050 南银转债 601009 南京银行 ... 2021-07-01 00:00:00 2027-06-15 00:00:00 6 第一年0.20%、第二年0.40%、第三年0.70%、第四年1.20%\n 、第五年1.70%、第...\n 1 123111 东财转3 300059 东方财富 ... 2021-04-23 00:00:00 2027-04-07 00:00:00 6 第一年0.2%、第二年0.3%、第三年0.4%、第四年0.8%、第\n 五年1.8%、第六年2.0%。\n\n \"\"\"\n if isinstance(bond_codes, str):\n return get_base_info_single(bond_codes)\n elif hasattr(bond_codes, '__iter__'):\n return get_base_info_multi(bond_codes)\n\n\ndef get_all_base_info() -> pd.DataFrame:\n \"\"\"\n 获取全部可转债基本信息列表\n\n Returns\n -------\n DataFrame\n 可转债一些基本信息\n\n Examples\n --------\n >>> import efinance as ef\n >>> ef.bond.get_all_base_info()\n 债券代码 债券名称 正股代码 正股名称 债券评级 申购日期 发行规模(亿) 网上发行中签率(%) 上市日期 到期日期 期限(年) 利率说明\n 0 123120 隆华转债 300263 隆华科技 AA- 2021-07-30 00:00:00 7.989283 NaN None 2027-07-30 00:00:00 6 第一年为0.40%、第二年为0.70%、第三年为1.00%、第四年为1.60%、第五年为2....\n 1 110081 闻泰转债 600745 闻泰科技 AA+ 2021-07-28 00:00:00 86.000000 0.044030 None 2027-07-28 00:00:00 6 第一年0.10%、第二年0.20%、第三年0.30%、第四年1.50%、第五年1.80%、第...\n 2 118001 金博转债 688598 金博股份 A+ 2021-07-23 00:00:00 5.999010 0.001771 None 2027-07-23 00:00:00 6 第一年0.50%、第二年0.70%、第三年1.20%、第四年1.80%、第五年2.40%、第...\n 3 123119 康泰转2 300601 康泰生物 AA 2021-07-15 00:00:00 20.000000 0.014182 None 2027-07-15 00:00:00 6 第一年为0.30%、第二年为0.50%、第三年为1.00%、第 四年为1.50%、第五年为1....\n 4 113627 太平转债 603877 太平鸟 AA 2021-07-15 00:00:00 8.000000 0.000542 None 2027-07-15 00:00:00 6 第一年0.30%、第二年0.50%、第三年1.00%、第四年1.50%、第五年1.80%、第...\n .. ... ... ... ... ... ... ... ... ... ... ... ...\n 80 110227 赤化转债 600227 圣济堂 AAA 2007-10-10 00:00:00 4.500000 0.158854 2007-10-23 00:00:00 2009-05-25 00:00:00 1.6192 票面利率和付息日期:本次发行的可转债票面利率第一 年为1.5%、第二年为1.8%、第三年为2....\n 81 126006 07深高债 600548 深高速 AAA 2007-10-09 00:00:00 15.000000 0.290304 2007-10-30 00:00:00 2013-10-09 00:00:00 6 None\n 82 110971 恒源转债 600971 恒源煤电 AAA 2007-09-24 00:00:00 4.000000 5.311774 2007-10-12 00:00:00 2009-12-21 00:00:00 2.2484 票面利率为:第一年年利率1.5%,第二年年利率1.8%,第三年年利率2.1%,第四年年利率2...\n 83 110567 山鹰转债 600567 山鹰国际 AA 2007-09-05 00:00:00 4.700000 0.496391 2007-09-17 00:00:00 2010-02-01 00:00:00 2.4055 票面利率和付息日期:本次发行的可转债票面利率第一年为1.4%,第二年为1.7%,第三年为2....\n 84 110026 中海转债 600026 中远海能 AAA 2007-07-02 00:00:00 20.000000 1.333453 2007-07-12 00:00:00 2008-03-27 00:00:00 0.737 票面利率:第一年为1.84%,第二年为2.05%,第三年为2.26%,第四年为2.47%,第...\n\n \"\"\"\n page = 1\n dfs: List[pd.DataFrame] = []\n columns = EASTMONEY_BOND_BASE_INFO_FIELDS\n while 1:\n params = (\n ('sortColumns', 'PUBLIC_START_DATE'),\n ('sortTypes', '-1'),\n ('pageSize', '500'),\n ('pageNumber', f'{page}'),\n ('reportName', 'RPT_BOND_CB_LIST'),\n ('columns', 'ALL'),\n ('source', 'WEB'),\n ('client', 'WEB'),\n )\n\n url = 'http://datacenter-web.eastmoney.com/api/data/v1/get'\n json_response = requests.get(url,\n headers=EASTMONEY_REQUEST_HEADERS,\n params=params).json()\n if json_response['result'] is None:\n break\n data = json_response['result']['data']\n df = pd.DataFrame(data).rename(\n columns=columns)[columns.values()]\n dfs.append(df)\n page += 1\n\n df = pd.concat(dfs)\n return df\n\n\n@process_dataframe_and_series(remove_columns_and_indexes=['市场编号'])\n@to_numeric\ndef get_realtime_quotes() -> pd.DataFrame:\n \"\"\"\n 获取沪深市场全部可转债实时行情信息\n\n Returns\n -------\n DataFrame\n 沪深市场全部可转债实时行情信息\n\n Examples\n --------\n >>> import efinance as ef\n >>> ef.bond.get_realtime_quotes()\n 债券代码 债券名称 涨跌幅 最新价 最高 最低 今开 涨跌额 换手率 量比 动态市盈率 成交量 成交额 昨日收盘 总市值 流通市值 行情ID 市场类型\n 0 123051 今天转债 24.03 158.66 165.0 134.0 134.0 30.74 496.74 67.16 - 1388341 2185911136.0 127.92 443443594 443443594 0.123051 深A\n 1 123042 银河转债 16.04 219.309 224.0 193.11 194.5 30.309 1833.99 1.34 - 3042265 6402014720.0 189.0 363794813 363794813 0.123042 深A\n 2 113034 滨化转债 13.49 247.71 255.62 214.5 214.5 29.45 334.56 2.96 - 1585993 3798255024.0 218.26 1174284861 1174284861 1.113034 沪A\n 3 128064 司尔转债 11.29 148.01 150.34 133.007 133.73 15.01 277.06 7.04 - 887301 1305800336.0 133.0 474009426 474009426 0.128064 深A\n 4 113027 华钰转债 8.38 129.86 130.2 122.3 123.0 10.04 83.84 4.15 - 272641 346817120.0 119.82 422273164 422273164 1.113027 沪A\n .. ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...\n 390 113621 彤程转债 -4.45 188.57 198.22 188.0 196.01 -8.79 29.91 0.47 - 168709 326018848.0 197.36 1063693010 1063693010 1.113621 沪A\n 391 128017 金禾转债 -4.86 182.676 204.989 182.61 195.16 -9.324 35.58 2.0 - 196375 375750768.0 192.0 1008366222 1008366222 0.128017 深A\n 392 113548 石英转债 -5.16 250.22 267.57 246.56 262.3 -13.61 143.32 0.72 - 175893 452796304.0 263.83 307086749 307086749 1.113548 沪A\n 393 128093 百川转债 -5.71 429.042 449.97 426.078 443.1 -25.958 426.86 0.36 - 693261 3032643232.0 455.0 696810974 696810974 0.128093 深A\n 394 123066 赛意转债 -6.0 193.08 203.999 193.08 203.0 -12.32 323.13 0.22 - 133317 261546032.0 205.4 79660753 79660753 0.123066 深A\n\n \"\"\"\n df = get_realtime_quotes_by_fs(FS_DICT['bond'])\n df.rename(columns={'代码': '债券代码',\n '名称': '债券名称'},\n inplace=True)\n return df\n\n\ndef get_quote_history(bond_codes: Union[str, List[str]],\n beg: str = '19000101',\n end: str = '20500101',\n klt: int = 101,\n fqt: int = 1,\n **kwargs) -> Union[pd.DataFrame, Dict[str, pd.DataFrame]]:\n \"\"\"\n 获取债券的 K 线数据\n\n Parameters\n ----------\n bond_codes : Union[str,List[str]]\n 债券代码、名称 或者 代码、名称构成的列表\n beg : str, optional\n 开始日期,默认为 ``'19000101'`` ,表示 1900年1月1日\n end : str, optional\n 结束日期,默认为 ``'20500101'`` ,表示 2050年1月1日\n klt : int, optional\n 行情之间的时间间隔,默认为 ``101`` ,可选示例如下\n\n - ``1`` : 分钟\n - ``5`` : 5 分钟\n - ``15`` : 15 分钟\n - ``30`` : 30 分钟\n - ``60`` : 60 分钟\n - ``101`` : 日\n - ``102`` : 周\n - ``103`` : 月\n\n fqt : int, optional\n 复权方式,默认为 ``1`` ,可选示例如下\n\n - ``0`` : 不复权\n - ``1`` : 前复权\n - ``2`` : 后复权\n\n Returns\n -------\n Union[DataFrame, Dict[str, DataFrame]]\n 债券的 K 线数据\n\n - ``DataFrame`` : 当 ``codes`` 是 ``str`` 时\n - ``Dict[str, DataFrame]`` : 当 ``bond_codes`` 是 ``List[str]`` 时\n\n Examples\n --------\n >>> import efinance as ef\n >>> # 获取单只债券日 K 行情\n >>> ef.bond.get_quote_history('123111')\n 债券名称 债券代码 日期 开盘 收盘 最高 最低 成交量 成交额 振幅 涨跌幅 涨跌额 换手率\n 0 东财转3 123111 2021-04-23 130.000 130.000 130.000 130.000 1836427 2.387355e+09 0.00 30.00 30.000 11.62\n 1 东财转3 123111 2021-04-26 130.353 130.010 133.880 125.110 8610944 1.126033e+10 6.75 0.01 0.010 54.50\n 2 东财转3 123111 2021-04-27 129.000 129.600 130.846 128.400 1820766 2.357472e+09 1.88 -0.32 -0.410 11.52\n 3 东财转3 123111 2021-04-28 129.100 130.770 131.663 128.903 1467727 1.921641e+09 2.13 0.90 1.170 9.29\n 4 东财转3 123111 2021-04-29 130.690 131.208 133.150 130.560 1156934 1.525974e+09 1.98 0.33 0.438 7.32\n .. ... ... ... ... ... ... ... ... ... ... ... ... ...\n 72 东财转3 123111 2021-08-09 159.600 159.300 162.990 158.690 596124 9.585751e+08 2.69 -0.34 -0.550 3.77\n 73 东财转3 123111 2021-08-10 159.190 160.950 161.450 157.000 517237 8.234596e+08 2.79 1.04 1.650 3.27\n 74 东财转3 123111 2021-08-11 161.110 159.850 162.300 159.400 298906 4.800711e+08 1.80 -0.68 -1.100 1.89\n 75 东财转3 123111 2021-08-12 159.110 158.290 160.368 158.010 270641 4.298100e+08 1.48 -0.98 -1.560 1.71\n 76 东财转3 123111 2021-08-13 158.000 158.358 160.290 157.850 250059 3.975513e+08 1.54 0.04 0.068 1.58\n\n \"\"\"\n df = get_quote_history_for_bond(\n bond_codes,\n beg=beg,\n end=end,\n klt=klt,\n fqt=fqt\n )\n\n if isinstance(df, pd.DataFrame):\n\n df.rename(columns={'代码': '债券代码',\n '名称': '债券名称'\n },\n inplace=True)\n elif isinstance(df, dict):\n for bond_code in df.keys():\n df[bond_code].rename(columns={'代码': '债券代码',\n '名称': '债券名称'\n },\n inplace=True)\n # NOTE 扩展接口 设定此关键词即返回 DataFrame 而不是 dict\n if kwargs.get('return_df'):\n df: pd.DataFrame = pd.concat(df, axis=0, ignore_index=True)\n return df\n\n\ndef get_history_bill(bond_code: str) -> pd.DataFrame:\n \"\"\"\n 获取单支债券的历史单子流入流出数据\n\n Parameters\n ----------\n bond_code : str\n 债券代码\n\n Returns\n -------\n DataFrame\n 沪深市场单只债券历史单子流入流出数据\n\n Examples\n --------\n >>> import efinance as ef\n >>> ef.bond.get_history_bill('123111')\n\n \"\"\"\n\n df = get_history_bill_for_bond(bond_code)\n df.rename(columns={'代码': '债券代码',\n '名称': '债券名称'},\n inplace=True)\n return df\n\n\ndef get_today_bill(bond_code: str) -> pd.DataFrame:\n \"\"\"\n 获取单只债券最新交易日的日内分钟级单子流入流出数据\n\n Parameters\n ----------\n bond_code : str\n 债券代码\n\n Returns\n -------\n DataFrame\n 单只债券最新交易日的日内分钟级单子流入流出数据\n\n Examples\n --------\n >>> import efinance as ef\n >>> ef.bond.get_today_bill('123111')\n 债券名称 债券代码 时间 主力净流入 小单净流入 中单净流入 大单净流入 超大单净流入\n 0 东财转3 123111 2021-08-13 09:31 -278046.0 319657.0 -41611.0 -278046.0 0.0\n 1 东财转3 123111 2021-08-13 09:32 -988506.0 571643.0 416863.0 -988506.0 0.0\n 2 东财转3 123111 2021-08-13 09:33 -990089.0 501980.0 488109.0 -990089.0 0.0\n 3 东财转3 123111 2021-08-13 09:34 -1718728.0 9051.0 1709678.0 -1718728.0 0.0\n 4 东财转3 123111 2021-08-13 09:35 -1653717.0 -133654.0 1787373.0 -1653717.0 0.0\n .. ... ... ... ... ... ... ... ...\n 235 东财转3 123111 2021-08-13 14:56 5942063.0 -747717.0 -5194332.0 11700567.0 -5758504.0\n 236 东财转3 123111 2021-08-13 14:57 5916755.0 -483170.0 -5433570.0 11963346.0 -6046591.0\n 237 东财转3 123111 2021-08-13 14:58 5503692.0 -187241.0 -5316435.0 11757642.0 -6253950.0\n 238 东财转3 123111 2021-08-13 14:59 5503692.0 -187241.0 -5316435.0 11757642.0 -6253950.0\n 239 东财转3 123111 2021-08-13 15:00 5503692.0 -187241.0 -5316435.0 11757642.0 -6253950.0\n\n \"\"\"\n df = get_today_bill_for_bond(bond_code)\n df.rename(columns={\n '代码': '债券代码',\n '名称': '债券名称'},\n inplace=True)\n\n return df\n"
] |
[
[
"pandas.concat",
"pandas.Series",
"pandas.DataFrame"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.